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

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

$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],
];

$error = '';
$success = '';
$row = null;

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

try {
    $pdo = Database::pdo();
    $stmt = $pdo->prepare(
        'SELECT user_id, full_name, email, user_type, phone, address, is_active, created_at, last_login
         FROM users
         WHERE user_id = :id
         LIMIT 1'
    );
    $stmt->execute(['id' => $id]);
    $row = $stmt->fetch();

    if (!$row) {
        http_response_code(404);
        echo 'User not found';
        exit;
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

$values = [
    'full_name' => (string)($row['full_name'] ?? ''),
    'email' => (string)($row['email'] ?? ''),
    'password' => '',
    'phone' => (string)($row['phone'] ?? ''),
    'address' => (string)($row['address'] ?? ''),
    'is_active' => ((int)($row['is_active'] ?? 1) === 1) ? '1' : '0',
];

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

    foreach ($values as $k => $v) {
        $values[$k] = trim((string)($_POST[$k] ?? ''));
    }

    if ($values['full_name'] === '' || $values['email'] === '') {
        $error = 'Name and email are required.';
    } elseif (!filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email address.';
    } else {
        try {
            $pdo = Database::pdo();

            $stmtCheck = $pdo->prepare('SELECT COUNT(*) FROM users WHERE email = :email AND user_id <> :id');
            $stmtCheck->execute(['email' => $values['email'], 'id' => $id]);
            if ((int)$stmtCheck->fetchColumn() > 0) {
                $error = 'Email already exists.';
            } else {
                if ($values['password'] !== '') {
                    if (strlen($values['password']) < 6) {
                        $error = 'Password must be at least 6 characters.';
                    } else {
                        $hash = password_hash($values['password'], PASSWORD_BCRYPT);
                        $stmtU = $pdo->prepare(
                            'UPDATE users
                             SET full_name=:full_name, email=:email, password_hash=:password_hash, phone=:phone, address=:address, is_active=:is_active
                             WHERE user_id=:id'
                        );
                        $stmtU->execute([
                            'full_name' => $values['full_name'],
                            'email' => $values['email'],
                            'password_hash' => $hash,
                            'phone' => ($values['phone'] !== '' ? $values['phone'] : null),
                            'address' => ($values['address'] !== '' ? $values['address'] : null),
                            'is_active' => ((int)$values['is_active'] === 1) ? 1 : 0,
                            'id' => $id,
                        ]);
                        $success = 'User updated (password changed).';
                        $values['password'] = '';
                    }
                } else {
                    $stmtU = $pdo->prepare(
                        'UPDATE users
                         SET full_name=:full_name, email=:email, phone=:phone, address=:address, is_active=:is_active
                         WHERE user_id=:id'
                    );
                    $stmtU->execute([
                        'full_name' => $values['full_name'],
                        'email' => $values['email'],
                        'phone' => ($values['phone'] !== '' ? $values['phone'] : null),
                        'address' => ($values['address'] !== '' ? $values['address'] : null),
                        'is_active' => ((int)$values['is_active'] === 1) ? 1 : 0,
                        'id' => $id,
                    ]);
                    $success = 'User updated.';
                }

                $stmt = $pdo->prepare(
                    'SELECT user_id, full_name, email, user_type, phone, address, is_active, created_at, last_login
                     FROM users
                     WHERE user_id = :id
                     LIMIT 1'
                );
                $stmt->execute(['id' => $id]);
                $row = $stmt->fetch();
            }
        } 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; ?>

<?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 items-start justify-between gap-4">
        <div>
            <h1 class="text-xl font-semibold">Edit User</h1>
            <p class="mt-1 text-sm text-slate-600">Update profile details and optionally reset password.</p>
        </div>
        <a class="rounded-lg border px-4 py-2 text-sm hover:bg-slate-50" href="<?= e(Constants::APP_ROOT) ?>/admin/users.php">Back</a>
    </div>

    <div class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-2 text-sm">
        <div class="rounded-xl border bg-slate-50 p-4">
            <div class="text-xs font-medium text-slate-600">Account</div>
            <div class="mt-2">
                <div><span class="text-slate-500">User ID:</span> <span class="font-medium">#<?= e((string)($row['user_id'] ?? '')) ?></span></div>
                <div class="mt-1"><span class="text-slate-500">Role:</span> <span class="font-medium"><?= e((string)($row['user_type'] ?? '')) ?></span></div>
                <div class="mt-1"><span class="text-slate-500">Created:</span> <span class="font-medium"><?= e((string)($row['created_at'] ?? '')) ?></span></div>
                <div class="mt-1"><span class="text-slate-500">Last Login:</span> <span class="font-medium"><?= e((string)($row['last_login'] ?? '')) ?></span></div>
            </div>
        </div>

        <div class="rounded-xl border bg-white p-4">
            <form class="grid grid-cols-1 gap-4" method="post" action="">
                <input type="hidden" name="csrf_token" value="<?= e((string)$csrfToken) ?>">
                <div>
                    <label class="block text-sm font-medium">Full name</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="full_name" value="<?= e($values['full_name']) ?>" required>
                </div>

                <div>
                    <label class="block text-sm font-medium">Email</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="email" name="email" value="<?= e($values['email']) ?>" required>
                </div>

                <div>
                    <label class="block text-sm font-medium">Phone</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="phone" value="<?= e($values['phone']) ?>">
                </div>

                <div>
                    <label class="block text-sm font-medium">Address</label>
                    <textarea class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="address" rows="3"><?= e($values['address']) ?></textarea>
                </div>

                <div>
                    <label class="block text-sm font-medium">Active</label>
                    <select class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" name="is_active">
                        <option value="1" <?= ($values['is_active'] === '1') ? 'selected' : '' ?>>Yes</option>
                        <option value="0" <?= ($values['is_active'] === '0') ? 'selected' : '' ?>>No</option>
                    </select>
                </div>

                <div>
                    <label class="block text-sm font-medium">New password (optional)</label>
                    <input class="mt-1 w-full rounded-lg border px-3 py-2 text-sm" type="password" name="password" value="<?= e($values['password']) ?>" placeholder="Leave blank to keep current password">
                    <div class="mt-1 text-xs text-slate-500">Minimum 6 characters.</div>
                </div>

                <div>
                    <button class="w-full rounded-lg bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800" type="submit">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

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