<?php

declare(strict_types=1);

require_once __DIR__ . '/../../includes/bootstrap.php';

$config = require __DIR__ . '/../../config/config.php';

auth_start_session();
auth_require_role(['admin']);

$user = auth_user();
$title = 'Service Details';

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    http_response_code(400);
    echo 'Invalid ID';
    exit;
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => false],
    ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'active' => false],
    ['label' => 'Staff', 'href' => '/pest/public/admin/staff.php', 'active' => false],
    ['label' => 'Staff Locations', 'href' => '/pest/public/admin/staff_locations.php', 'active' => false],
    ['label' => 'Services', 'href' => '/pest/public/admin/services.php', 'active' => true],
    ['label' => 'Task Assignment', 'href' => '/pest/public/admin/task_assignment.php', 'active' => false],
    ['label' => 'Payments', 'href' => '/pest/public/admin/payments.php', 'active' => false],
    ['label' => 'Complaints', 'href' => '/pest/public/admin/complaints.php', 'active' => false],
    ['label' => 'Reports', 'href' => '/pest/public/admin/reports.php', 'active' => false],
];

$error = '';
$service = null;
$recentTasks = [];

try {
    $pdo = Database::pdo();

    $stmt = $pdo->prepare(
        'SELECT service_id, service_name, description, price, duration_minutes, category, is_active, created_at
         FROM services
         WHERE service_id = :id
         LIMIT 1'
    );
    $stmt->execute(['id' => $id]);
    $service = $stmt->fetch();

    if (!$service) {
        http_response_code(404);
        echo 'Service not found';
        exit;
    }

    $stmt2 = $pdo->prepare(
        "SELECT
            t.task_id,
            t.scheduled_date,
            t.scheduled_time,
            t.status AS task_status,
            c.full_name AS customer_name,
            s.full_name AS staff_name
         FROM tasks t
         JOIN service_requests sr ON sr.request_id = t.request_id
         LEFT JOIN users c ON c.user_id = sr.customer_id
         LEFT JOIN users s ON s.user_id = t.assigned_staff_id
         WHERE sr.service_id = :sid
         ORDER BY t.scheduled_date DESC, t.scheduled_time DESC, t.task_id DESC
         LIMIT 20"
    );
    $stmt2->execute(['sid' => $id]);
    $recentTasks = $stmt2->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

ob_start();
?>
<?php if ($error !== ''): ?>
    <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
        <?= e($error) ?>
    </div>
<?php endif; ?>

<div class="rounded-xl border bg-white p-6">
    <div class="flex items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">Service Details</h1>
            <p class="mt-1 text-sm text-slate-600">Read-only service view with recent work done.</p>
        </div>
        <div class="flex gap-2">
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/service_edit.php?id=<?= e((string)$id) ?>">Edit</a>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/services.php">Back</a>
        </div>
    </div>

    <?php if ($service): ?>
        <div class="mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2">
            <div class="rounded-xl border bg-slate-50 p-4">
                <div class="text-xs font-medium text-slate-600">Service</div>
                <div class="mt-2 text-sm">
                    <div><span class="text-slate-500">Service ID:</span> <span class="font-medium">#<?= e((string)$service['service_id']) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Name:</span> <span class="font-medium"><?= e((string)$service['service_name']) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Category:</span> <span class="font-medium"><?= e((string)($service['category'] ?? '')) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Active:</span> <span class="font-medium"><?= ((int)($service['is_active'] ?? 1) === 1) ? 'Yes' : 'No' ?></span></div>
                </div>
            </div>

            <div class="rounded-xl border bg-slate-50 p-4">
                <div class="text-xs font-medium text-slate-600">Pricing & Duration</div>
                <div class="mt-2 text-sm">
                    <div><span class="text-slate-500">Price:</span> <span class="font-medium"><?= e((string)($service['price'] ?? '')) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Duration (mins):</span> <span class="font-medium"><?= e((string)($service['duration_minutes'] ?? '')) ?></span></div>
                    <div class="mt-1"><span class="text-slate-500">Created:</span> <span class="font-medium"><?= e((string)($service['created_at'] ?? '')) ?></span></div>
                </div>
            </div>
        </div>

        <?php if (!empty($service['description'])): ?>
            <div class="mt-6 rounded-xl border bg-white p-4">
                <div class="text-sm font-semibold">Description</div>
                <div class="mt-2 text-sm text-slate-700 whitespace-pre-line"><?= e((string)$service['description']) ?></div>
            </div>
        <?php endif; ?>

        <div class="mt-6 rounded-xl border bg-white p-4">
            <div class="flex items-center justify-between">
                <div class="text-sm font-semibold">Recent Work Done (Tasks)</div>
                <div class="text-xs text-slate-500">Latest 20</div>
            </div>

            <div class="mt-3 overflow-x-auto">
                <table class="min-w-full text-sm">
                    <thead class="text-left text-slate-600">
                        <tr class="border-b">
                            <th class="py-2 pr-4">Task</th>
                            <th class="py-2 pr-4">Customer</th>
                            <th class="py-2 pr-4">Staff</th>
                            <th class="py-2 pr-4">Scheduled</th>
                            <th class="py-2">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$recentTasks): ?>
                            <tr class="border-b"><td class="py-3 text-slate-500" colspan="5">No tasks found for this service.</td></tr>
                        <?php else: ?>
                            <?php foreach ($recentTasks as $t): ?>
                                <tr class="border-b last:border-0">
                                    <td class="py-3 pr-4">
                                        <a class="font-semibold text-slate-900 hover:underline" href="/pest/public/admin/task_details.php?id=<?= e((string)$t['task_id']) ?>">#<?= e((string)$t['task_id']) ?></a>
                                    </td>
                                    <td class="py-3 pr-4"><?= e((string)($t['customer_name'] ?? '')) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)($t['staff_name'] ?? '')) ?></td>
                                    <td class="py-3 pr-4"><?= e((string)($t['scheduled_date'] ?? '')) ?> <?= e((string)($t['scheduled_time'] ?? '')) ?></td>
                                    <td class="py-3"><?= e((string)($t['task_status'] ?? '')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>
<?php
$content = ob_get_clean();

require __DIR__ . '/../../includes/dashboard_layout.php';
