<?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 = 'Admin Dashboard';

$todayTasks = [];
$error = '';

$totalCustomers = 0;
$activeStaff = 0;
$todayTasksCount = 0;
$completedServices = 0;
$todoServices = 0;
$complaintsCount = 0;

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

    $totalCustomers = (int)($pdo->query(
        "SELECT COUNT(*) FROM users WHERE user_type = 'customer' AND is_active = 1"
    )->fetchColumn() ?: 0);

    $activeStaff = (int)($pdo->query(
        "SELECT COUNT(*) FROM users u JOIN staff_details sd ON u.user_id = sd.user_id WHERE u.user_type = 'staff' AND u.is_active = 1"
    )->fetchColumn() ?: 0);

    $todayTasks = $pdo->query('SELECT task_id, custom_task_id, staff_name, customer_name, service_name, scheduled_time, status, property_address FROM admin_today_tasks LIMIT 8')->fetchAll();
    $todayTasksCount = count($todayTasks);

    $completedServices = (int)($pdo->query(
        "SELECT COUNT(*) FROM tasks WHERE status = 'completed'"
    )->fetchColumn() ?: 0);

    $todoServices = (int)($pdo->query(
        "SELECT COUNT(*) FROM tasks WHERE status IN ('pending', 'accepted', 'started') AND status <> 'cancelled'"
    )->fetchColumn() ?: 0);

    $complaintsCount = (int)($pdo->query(
        "SELECT COUNT(*) FROM complaints WHERE status IN ('pending', 'in_progress')"
    )->fetchColumn() ?: 0);
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$nav = [
    ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'active' => true],
    ['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' => false],
    ['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],
];

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-2xl bg-gradient-to-br from-slate-900 to-slate-700 p-6 text-white shadow-sm">
    <div class="flex items-center gap-3">
        <svg class="h-12 w-12 opacity-90" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
        </svg>
        <div class="flex-1">
            <div class="text-xs/5 opacity-90">Welcome, Administrator</div>
            <div class="mt-1 text-2xl font-semibold tracking-tight"><?= e((string)($user['full_name'] ?? 'Admin')) ?></div>
            <div class="mt-1 text-xs/5 opacity-90">User ID: <span class="font-medium"><?= e((string)($user['user_id'] ?? '')) ?></span> • Role: <span class="font-medium">Admin</span></div>
        </div>
    </div>
</div>

<div class="mt-6 grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
    <a class="block rounded-2xl bg-gradient-to-br from-blue-600 to-indigo-600 p-5 text-white shadow-sm transition hover:opacity-95" href="/pest/public/admin/customers.php">
        <div class="flex items-center justify-between">
            <div class="text-xs/5 opacity-90">Total Customers</div>
            <svg class="h-5 w-5 opacity-75" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
            </svg>
        </div>
        <div class="mt-2 text-2xl font-semibold tracking-tight"><?= e((string)$totalCustomers) ?></div>
        <div class="mt-1 text-xs/5 opacity-90">Active customer accounts</div>
    </a>

    <a class="block rounded-2xl bg-gradient-to-br from-emerald-600 to-teal-600 p-5 text-white shadow-sm transition hover:opacity-95" href="/pest/public/admin/staff.php">
        <div class="flex items-center justify-between">
            <div class="text-xs/5 opacity-90">Active Staff</div>
            <svg class="h-5 w-5 opacity-75" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
        </div>
        <div class="mt-2 text-2xl font-semibold tracking-tight"><?= e((string)$activeStaff) ?></div>
        <div class="mt-1 text-xs/5 opacity-90">Staff members available</div>
    </a>

    <a class="block rounded-2xl bg-gradient-to-br from-sky-600 to-cyan-500 p-5 text-white shadow-sm transition hover:opacity-95" href="/pest/public/admin/task_assignment.php">
        <div class="flex items-center justify-between">
            <div class="text-xs/5 opacity-90">Today's Tasks</div>
            <svg class="h-5 w-5 opacity-75" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
        </div>
        <div class="mt-2 text-2xl font-semibold tracking-tight"><?= e((string)$todayTasksCount) ?></div>
        <div class="mt-1 text-xs/5 opacity-90">Scheduled for today</div>
    </a>

    <a class="block rounded-2xl bg-gradient-to-br from-green-600 to-lime-600 p-5 text-white shadow-sm transition hover:opacity-95" href="/pest/public/admin/task_assignment.php?view=completed">
        <div class="flex items-center justify-between">
            <div class="text-xs/5 opacity-90">Completed Services</div>
            <svg class="h-5 w-5 opacity-75" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
        </div>
        <div class="mt-2 text-2xl font-semibold tracking-tight"><?= e((string)$completedServices) ?></div>
        <div class="mt-1 text-xs/5 opacity-90">Total services completed</div>
    </a>

    <a class="block rounded-2xl bg-gradient-to-br from-amber-600 to-orange-600 p-5 text-white shadow-sm transition hover:opacity-95" href="/pest/public/admin/todo_tasks.php">
        <div class="flex items-center justify-between">
            <div class="text-xs/5 opacity-90">To Do Services</div>
            <svg class="h-5 w-5 opacity-75" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
            </svg>
        </div>
        <div class="mt-2 text-2xl font-semibold tracking-tight"><?= e((string)$todoServices) ?></div>
        <div class="mt-1 text-xs/5 opacity-90">Pending & in progress</div>
    </a>

    <a class="block rounded-2xl bg-gradient-to-br from-rose-600 to-pink-600 p-5 text-white shadow-sm transition hover:opacity-95" href="/pest/public/admin/complaints.php">
        <div class="flex items-center justify-between">
            <div class="text-xs/5 opacity-90">Complaints</div>
            <svg class="h-5 w-5 opacity-75" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
        </div>
        <div class="mt-2 text-2xl font-semibold tracking-tight"><?= e((string)$complaintsCount) ?></div>
        <div class="mt-1 text-xs/5 opacity-90">Pending complaints</div>
    </a>
</div>

<div class="grid grid-cols-1 gap-6 xl:grid-cols-2">
    <div class="rounded-xl border bg-white p-6 xl:col-span-2">
        <div class="flex items-center justify-between">
            <h2 class="text-base font-semibold">Today’s Tasks</h2>
            <span class="text-xs text-slate-500">View: admin_today_tasks</span>
        </div>
        <div class="mt-4 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 ID</th>
                        <th class="py-2 pr-4">Time</th>
                        <th class="py-2 pr-4">Staff</th>
                        <th class="py-2 pr-4">Customer</th>
                        <th class="py-2">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$todayTasks): ?>
                        <tr class="border-b"><td class="py-3 text-slate-500" colspan="5">No tasks scheduled today.</td></tr>
                    <?php else: ?>
                        <?php foreach ($todayTasks as $t): ?>
                            <tr class="border-b last:border-0">
                                <td class="py-3 pr-4 font-medium">#<?= e((string)($t['custom_task_id'] ?? $t['task_id'])) ?></td>
                                <td class="py-3 pr-4"><?= e(format_time((string)$t['scheduled_time'])) ?></td>
                                <td class="py-3 pr-4 font-medium"><?= e((string)$t['staff_name']) ?></td>
                                <td class="py-3 pr-4"><?= e((string)$t['customer_name']) ?></td>
                                <td class="py-3"><?= e((string)$t['status']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php
$content = ob_get_clean();

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