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

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

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = (string)$_SESSION['csrf_token'];

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

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $postedToken = (string)($_POST['csrf_token'] ?? '');
        if ($postedToken === '' || !hash_equals($csrfToken, $postedToken)) {
            throw new RuntimeException('Invalid request.');
        }

        $targetId = (int)($_POST['id'] ?? 0);
        $action = trim((string)($_POST['action'] ?? ''));

        if ($targetId <= 0) {
            throw new RuntimeException('Invalid user selection.');
        }

        $myId = (int)($user['user_id'] ?? 0);
        if ($myId > 0 && $targetId === $myId) {
            throw new RuntimeException('You cannot deactivate your own account.');
        }

        if ($action !== 'deactivate' && $action !== 'activate') {
            throw new RuntimeException('Invalid action.');
        }

        $isActive = ($action === 'activate') ? 1 : 0;
        $stmtUp = $pdo->prepare('UPDATE users SET is_active = :a WHERE user_id = :id');
        $stmtUp->execute(['a' => $isActive, 'id' => $targetId]);

        $success = ($action === 'activate') ? 'User activated.' : 'User deactivated.';
    }

    $where = [];
    $params = [];

    if ($role !== '' && in_array($role, ['admin', 'staff', 'customer'], true)) {
        $where[] = 'u.user_type = :role';
        $params['role'] = $role;
    }

    if ($q !== '') {
        $where[] = '(u.full_name LIKE :q OR u.email LIKE :q OR u.phone LIKE :q)';
        $params['q'] = '%' . $q . '%';
    }

    $sql =
        "SELECT u.user_id, u.full_name, u.email, u.user_type, u.phone, u.is_active, u.last_login, u.created_at
         FROM users u";

    if ($where) {
        $sql .= ' WHERE ' . implode(' AND ', $where);
    }

    $sql .= ' ORDER BY u.user_id DESC';

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll();
} catch (Throwable $e) {
    $error = $e->getMessage();
}

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

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; ?>

<?php if ($success !== '' && $error === ''): ?>
    <div class="rounded-xl border border-green-200 bg-green-50 p-4 text-sm text-green-700">
        <?= e($success) ?>
    </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">User Management</h1>
            <p class="mt-1 text-sm text-slate-600">Search and edit user accounts (including password resets).</p>
        </div>
        <div class="flex flex-wrap gap-2">
            <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="<?= e(Constants::APP_ROOT) ?>/admin/user_add.php">Add Admin</a>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/staff_add.php">Add Staff</a>
            <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/customer_add.php">Add Customer</a>
        </div>
    </div>

    <form class="mt-5 grid grid-cols-1 gap-2 md:grid-cols-3" 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 md:col-span-2" type="text" name="q" value="<?= e($q) ?>" placeholder="Search by name, email, phone">
        <select class="w-full rounded-lg border px-3 py-2 text-sm" name="role">
            <option value="">All Roles</option>
            <option value="admin" <?= $role === 'admin' ? 'selected' : '' ?>>Admin</option>
            <option value="staff" <?= $role === 'staff' ? 'selected' : '' ?>>Staff</option>
            <option value="customer" <?= $role === 'customer' ? 'selected' : '' ?>>Customer</option>
        </select>
        <div class="md:col-span-3 flex flex-wrap gap-2">
            <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="<?= e(Constants::APP_ROOT) ?>/admin/users.php">Reset</a>
        </div>
    </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">Role</th>
                    <th class="py-2 pr-4">Active</th>
                    <th class="py-2 pr-4">Last Login</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="7">No users 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['user_type'] ?? '')) ?></td>
                            <td class="py-3 pr-4"><?= ((int)($r['is_active'] ?? 0) === 1) ? 'Yes' : 'No' ?></td>
                            <td class="py-3 pr-4"><?= e((string)($r['last_login'] ?? '')) ?></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="<?= e(Constants::APP_ROOT) ?>/admin/user_edit.php?id=<?= e((string)$r['user_id']) ?>">Edit</a>
                                    <?php if ((int)($user['user_id'] ?? 0) !== (int)($r['user_id'] ?? 0)): ?>
                                        <?php if ((int)($r['is_active'] ?? 0) === 1): ?>
                                            <form method="post" action="" onsubmit="return confirm('Deactivate this user?');">
                                                <input type="hidden" name="csrf_token" value="<?= e((string)$csrfToken) ?>">
                                                <input type="hidden" name="id" value="<?= e((string)$r['user_id']) ?>">
                                                <input type="hidden" name="action" value="deactivate">
                                                <button class="rounded-lg border border-rose-200 bg-rose-50 px-3 py-1.5 text-xs text-rose-700 hover:bg-rose-100" type="submit">Delete</button>
                                            </form>
                                        <?php else: ?>
                                            <form method="post" action="" onsubmit="return confirm('Activate this user?');">
                                                <input type="hidden" name="csrf_token" value="<?= e((string)$csrfToken) ?>">
                                                <input type="hidden" name="id" value="<?= e((string)$r['user_id']) ?>">
                                                <input type="hidden" name="action" value="activate">
                                                <button class="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-1.5 text-xs text-emerald-700 hover:bg-emerald-100" type="submit">Activate</button>
                                            </form>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
$content = ob_get_clean();
require __DIR__ . '/../../includes/dashboard_layout.php';
