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

$q = trim((string)($_GET['q'] ?? ''));
$rows = [];
$error = '';

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

    if ($q !== '') {
        $stmt = $pdo->prepare(
            "SELECT u.user_id, u.full_name, u.email, u.phone, u.is_active,
                    sd.employee_code, sd.position, sd.specialization, sd.is_available
             FROM users u
             LEFT JOIN staff_details sd ON sd.user_id = u.user_id
             WHERE u.user_type = 'staff'
               AND (u.full_name LIKE :q OR u.email LIKE :q OR sd.employee_code LIKE :q)
             ORDER BY u.user_id DESC"
        );
        $stmt->execute(['q' => '%' . $q . '%']);
        $rows = $stmt->fetchAll();
    } else {
        $rows = $pdo->query(
            "SELECT u.user_id, u.full_name, u.email, u.phone, u.is_active,
                    sd.employee_code, sd.position, sd.specialization, sd.is_available
             FROM users u
             LEFT JOIN staff_details sd ON sd.user_id = u.user_id
             WHERE u.user_type = 'staff'
             ORDER BY u.user_id DESC"
        )->fetchAll();
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$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' => true],
    ['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-xl border bg-white p-6">
    <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold">Staff Management</h1>
            <p class="mt-1 text-sm text-slate-600">Add, edit, delete staff users.</p>
        </div>
        <a class="inline-flex items-center justify-center rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" href="/pest/public/admin/staff_add.php">Add Staff</a>
    </div>

    <form class="mt-5 flex gap-2" method="get" action="">
        <input class="w-full rounded-lg border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-slate-900" type="text" name="q" value="<?= e($q) ?>" placeholder="Search by name, email, employee code">
        <button class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" type="submit">Search</button>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="/pest/public/admin/staff.php">Reset</a>
    </form>

    <div class="mt-5 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">ID</th>
                    <th class="py-2 pr-4">Name</th>
                    <th class="py-2 pr-4">Email</th>
                    <th class="py-2 pr-4">Employee</th>
                    <th class="py-2 pr-4">Position</th>
                    <th class="py-2 pr-4">Active</th>
                    <th class="py-2 pr-4">Available</th>
                    <th class="py-2">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$rows): ?>
                    <tr class="border-b">
                        <td class="py-3 text-slate-500" colspan="8">No staff found.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $r): ?>
                        <tr class="border-b last:border-0">
                            <td class="py-3 pr-4"><?= e((string)$r['user_id']) ?></td>
                            <td class="py-3 pr-4 font-medium"><?= e((string)$r['full_name']) ?></td>
                            <td class="py-3 pr-4"><?= e((string)$r['email']) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($r['employee_code'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= e((string)($r['position'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= ((int)$r['is_active'] === 1) ? 'Yes' : 'No' ?></td>
                            <td class="py-3 pr-4"><?= ((int)($r['is_available'] ?? 0) === 1) ? 'Yes' : 'No' ?></td>
                            <td class="py-3">
                                <div class="flex flex-wrap gap-2">
                                    <a class="rounded-lg border px-3 py-1.5 text-xs hover:bg-slate-50" href="/pest/public/admin/staff_edit.php?id=<?= e((string)$r['user_id']) ?>">Edit</a>
                                    <form method="post" action="/pest/public/admin/staff_delete.php" onsubmit="return confirm('Delete this staff user?');">
                                        <input type="hidden" name="id" value="<?= e((string)$r['user_id']) ?>">
                                        <button class="rounded-lg border border-red-200 bg-red-50 px-3 py-1.5 text-xs text-red-700 hover:bg-red-100" type="submit">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
$content = ob_get_clean();

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