<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
auth_require_super_admin();

$id     = (int)($_GET['id'] ?? 0);
$action = $_GET['action'] ?? ($id ? 'edit' : '');
$is_add = ($action === 'add');

$user = $is_add ? ['email'=>'','first_name'=>'','last_name'=>'','role'=>'admin','active'=>1] : null;
if (!$is_add) {
    $user = db_row('SELECT * FROM admin_users WHERE id=:id', ['id'=>$id]);
    if (!$user) { http_response_code(404); echo 'Admin not found.'; exit; }
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $email      = strtolower(trim($_POST['email'] ?? ''));
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name  = trim($_POST['last_name']  ?? '');
    $role       = $_POST['role'] ?? 'admin';
    $active     = !empty($_POST['active']) ? 1 : 0;
    $password   = (string)($_POST['password'] ?? '');

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Valid email is required.';
    if (!in_array($role, ['super_admin','admin','staff'], true)) $errors[] = 'Invalid role.';
    if ($is_add && strlen($password) < 8)         $errors[] = 'Password must be at least 8 characters when creating a user.';
    if (!$is_add && $password !== '' && strlen($password) < 8) $errors[] = 'New password must be at least 8 characters.';

    // Don't let super_admin demote themselves to a lower role (would lock them out of user management)
    if (!$is_add && (int)$user['id'] === (int)auth_admin_id() && $role !== 'super_admin') {
        $errors[] = 'You can\'t change your own role.';
    }
    // Don't let super_admin deactivate themselves
    if (!$is_add && (int)$user['id'] === (int)auth_admin_id() && $active === 0) {
        $errors[] = 'You can\'t deactivate yourself.';
    }

    // Email uniqueness
    if (!$errors) {
        $exists = db_row(
            'SELECT id FROM admin_users WHERE email = :e AND id <> :id',
            ['e' => $email, 'id' => $is_add ? 0 : $id]
        );
        if ($exists) $errors[] = 'That email is already used by another admin.';
    }

    if (!$errors) {
        $data = [
            'email'      => $email,
            'first_name' => $first_name,
            'last_name'  => $last_name,
            'role'       => $role,
            'active'     => $active,
        ];
        if ($password !== '') {
            $cost = defined('AUTH_BCRYPT_COST') ? AUTH_BCRYPT_COST : 12;
            $data['password_hash'] = password_hash($password, PASSWORD_BCRYPT, ['cost' => $cost]);
        }

        if ($is_add) {
            $new_id = db_insert('admin_users', $data);
            app_log("Admin user created: $email by admin #" . auth_admin_id());
            header('Location: users.php?msg=created'); exit;
        } else {
            db_update('admin_users', $id, $data);
            app_log("Admin user #$id updated by admin #" . auth_admin_id());
            header('Location: users.php?msg=saved'); exit;
        }
    }

    // On error, repopulate form
    $user = array_merge($user, [
        'email'=>$email,'first_name'=>$first_name,'last_name'=>$last_name,
        'role'=>$role,'active'=>$active,
    ]);
}

$page_title = $is_add ? 'New admin user' : 'Edit admin user';
require __DIR__ . '/_guard.php';
?>

<style>
.b-card{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;max-width:620px;}
</style>

<section class="section">
<div class="container">

<p class="muted" style="margin:0;"><a href="users.php">← Admin users</a></p>
<h1 style="margin:.25rem 0 1.25rem;"><?= $is_add ? 'Add admin user' : 'Edit admin user' ?></h1>

<?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="max-width:620px;margin-bottom:1rem;">
        <?= implode('<br>', array_map('htmlspecialchars', $errors)) ?>
    </div>
<?php endif; ?>

<form method="post" class="b-card">
    <?= csrf_field() ?>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;">
        <div>
            <label>First name</label>
            <input type="text" name="first_name" value="<?= htmlspecialchars($user['first_name']) ?>">
        </div>
        <div>
            <label>Last name</label>
            <input type="text" name="last_name" value="<?= htmlspecialchars($user['last_name']) ?>">
        </div>
    </div>

    <label>Email *</label>
    <input type="email" name="email" required value="<?= htmlspecialchars($user['email']) ?>">

    <label>Role *</label>
    <select name="role" required>
        <option value="staff"       <?= $user['role']==='staff'?'selected':'' ?>>Staff (limited)</option>
        <option value="admin"       <?= $user['role']==='admin'?'selected':'' ?>>Admin (full access)</option>
        <option value="super_admin" <?= $user['role']==='super_admin'?'selected':'' ?>>Super admin (can manage other admins)</option>
    </select>
    <p class="muted" style="font-size:.78rem;margin:.25rem 0 1rem;">
        Only Super admins can access this user-management page.
    </p>

    <label style="display:flex;align-items:center;gap:.5rem;font-weight:normal;cursor:pointer;">
        <input type="checkbox" name="active" value="1" <?= $user['active']?'checked':'' ?>>
        <span>Active (can sign in)</span>
    </label>

    <hr style="margin:1.5rem 0;border:none;border-top:1px solid var(--line);">

    <label>Password <?= $is_add ? '*' : '<small>(leave blank to keep existing)</small>' ?></label>
    <input type="password" name="password" <?= $is_add?'required minlength="8"':'minlength="8"' ?>
           autocomplete="new-password" placeholder="<?= $is_add?'At least 8 characters':'Leave blank to keep current' ?>">

    <div style="display:flex;gap:.75rem;margin-top:1.5rem;">
        <button type="submit" class="btn"><?= $is_add ? 'Create user' : 'Save changes' ?></button>
        <a href="users.php" class="btn btn-outline">Cancel</a>
    </div>
</form>

</div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>