<?php
require_once __DIR__ . '/header.php';
perms_require('manage_users');

$user    = current_user();
$isSuper = perms_is_super($user);

$msg = ''; $err = '';

// Facilities for the dropdown
if ($isSuper) {
    $facilities = $pdo->query('SELECT id, name, code FROM facilities WHERE deleted_at IS NULL ORDER BY name')->fetchAll();
} else {
    $stmt = $pdo->prepare('SELECT id, name, code FROM facilities WHERE id = ? AND deleted_at IS NULL');
    $stmt->execute([$user['facility_id']]);
    $facilities = $stmt->fetchAll();
}

$creatableRoles = perms_creatable_roles($user);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_require();

    if (isset($_POST['create_user'])) {
        $username  = v_clean_string($_POST['username']  ?? '', 50);
        $full_name = v_clean_string($_POST['full_name'] ?? '', 100);
        $roleReq   = (string)($_POST['role'] ?? '');
        $facId     = ($_POST['facility_id'] ?? '') === '' ? null : v_int($_POST['facility_id'], 1);
        $password  = (string)($_POST['password'] ?? '');

        // Coordinators can only create examiners in their own facility
        if (!isset($creatableRoles[$roleReq])) {
            $err = 'You may not create users with that role.';
        } elseif (!$isSuper) {
            $facId = (int)$user['facility_id']; // force own facility
        }

        if (!$err) {
            $issues = [];
            if (!v_username($username)) $issues[] = 'invalid username';
            if ($full_name === '')      $issues[] = 'full name required';
            foreach (v_password_strong($password) as $i) $issues[] = "password $i";

            if ($issues) {
                $err = 'Cannot create user: ' . implode('; ', $issues) . '.';
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                try {
                    $pdo->prepare('INSERT INTO users (username, password_hash, full_name, role, facility_id, active) VALUES (?, ?, ?, ?, ?, 1)')
                        ->execute([$username, $hash, $full_name, $roleReq, $facId]);
                    audit_log($pdo, 'user_create', ['username'=>$username, 'role'=>$roleReq, 'facility_id'=>$facId]);
                    $msg = 'User created.';
                } catch (Throwable $e) {
                    $err = str_contains($e->getMessage(), 'Duplicate')
                        ? 'Username already exists.'
                        : 'Could not create user.';
                    if ($err === 'Could not create user.') error_log('user_create: ' . $e->getMessage());
                }
            }
        }
    }
    elseif (isset($_POST['update_user'])) {
        $id        = v_int($_POST['user_id'] ?? 0, 1);
        $full_name = v_clean_string($_POST['full_name'] ?? '', 100);
        $roleReq   = (string)($_POST['role'] ?? 'examiner');
        $facId     = ($_POST['facility_id'] ?? '') === '' ? null : v_int($_POST['facility_id'], 1);
        $active    = isset($_POST['active']) ? 1 : 0;
        $password  = (string)($_POST['password'] ?? '');

        $target = $pdo->prepare('SELECT * FROM users WHERE id = ?');
        $target->execute([$id]);
        $t = $target->fetch();

        if (!$t) { $err = 'User not found.'; }
        elseif (!$isSuper) {
            // Coordinators may only edit examiners in their own facility, and not super_admins
            $targetRole = perms_role($t);
            if ($targetRole !== 'examiner' || (int)$t['facility_id'] !== (int)$user['facility_id']) {
                $err = 'You may only edit examiners in your own facility.';
            } else {
                $roleReq = 'examiner';
                $facId   = (int)$user['facility_id'];
            }
        }

        if (!$err && $id > 0 && $full_name !== '') {
            if ($password !== '') {
                $issues = v_password_strong($password);
                if ($issues) { $err = 'Password issues: ' . implode(', ', $issues) . '.'; }
                else {
                    $hash = password_hash($password, PASSWORD_DEFAULT);
                    $pdo->prepare('UPDATE users SET full_name=?, role=?, facility_id=?, active=?, password_hash=? WHERE id=?')
                        ->execute([$full_name, $roleReq, $facId, $active, $hash, $id]);
                    audit_log($pdo, 'user_update', ['id'=>$id, 'password_changed'=>true]);
                    $msg = 'User updated (password changed).';
                }
            } else {
                $pdo->prepare('UPDATE users SET full_name=?, role=?, facility_id=?, active=? WHERE id=?')
                    ->execute([$full_name, $roleReq, $facId, $active, $id]);
                audit_log($pdo, 'user_update', ['id'=>$id]);
                $msg = 'User updated.';
            }
        }
    }
    elseif (isset($_POST['clear_face'])) {
        $id = v_int($_POST['user_id'] ?? 0, 1);
        if ($id > 0) {
            // permission: super, or coordinator in same facility
            $t = $pdo->prepare('SELECT facility_id FROM users WHERE id = ?');
            $t->execute([$id]); $tr = $t->fetch();
            if ($isSuper || ($tr && (int)$tr['facility_id'] === (int)$user['facility_id'])) {
                $pdo->prepare("UPDATE users SET face_descriptor=NULL, face_enrolled_at=NULL, face_login_enabled=0 WHERE id=?")->execute([$id]);
                audit_log($pdo, 'face_clear_admin', ['target_user_id' => $id]);
                $msg = 'Face data cleared.';
            } else $err = 'Permission denied.';
        }
    }
    elseif (isset($_POST['delete_user'])) {
        if (!$isSuper) { $err = 'Only super admin can delete users.'; }
        else {
            $id = v_int($_POST['delete_user'], 1);
            if ($id === (int)$user['id']) {
                $err = "You can't delete your own account.";
            } else {
                // Deactivate rather than hard-delete (preserves FKs from attempts/forms/etc)
                $pdo->prepare('UPDATE users SET active = 0 WHERE id = ?')->execute([$id]);
                audit_log($pdo, 'user_deactivate', ['id' => $id]);
                $msg = 'User deactivated.';
            }
        }
    }
}

// User list, scoped
if ($isSuper) {
    $users = $pdo->query('SELECT id, username, full_name, role, facility_id, active, face_enrolled_at, face_login_enabled FROM users ORDER BY role, username')->fetchAll();
} else {
    $stmt = $pdo->prepare("SELECT id, username, full_name, role, facility_id, active, face_enrolled_at, face_login_enabled FROM users WHERE facility_id = ? OR id = ? ORDER BY role, username");
    $stmt->execute([(int)$user['facility_id'], (int)$user['id']]);
    $users = $stmt->fetchAll();
}
?>
<h2>User Management</h2>
<?php if (!$isSuper): ?><p class="muted">As a coordinator, you can create and manage examiners in your facility only.</p><?php endif; ?>

<?php if ($msg): ?><div class="alert alert-success"><?php echo h($msg); ?></div><?php endif; ?>
<?php if ($err): ?><div class="alert alert-danger"><?php echo h($err); ?></div><?php endif; ?>

<?php if ($creatableRoles): ?>
<h3>Create User</h3>
<form method="post">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="create_user" value="1">
    <div class="form-row">
        <div class="field"><label>Username *</label><input type="text" name="username" required></div>
        <div class="field"><label>Full Name *</label><input type="text" name="full_name" required></div>
        <div class="field"><label>Role *</label>
            <select name="role">
                <?php foreach ($creatableRoles as $k => $v): ?>
                    <option value="<?php echo h($k); ?>"><?php echo h($v); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="field"><label>Facility</label>
            <select name="facility_id" <?php if (!$isSuper) echo 'disabled'; ?>>
                <?php if ($isSuper): ?><option value="">None / Global</option><?php endif; ?>
                <?php foreach ($facilities as $f): ?>
                    <option value="<?php echo (int)$f['id']; ?>"
                        <?php if (!$isSuper && (int)$f['id']===(int)$user['facility_id']) echo 'selected'; ?>>
                        <?php echo h($f['name']); ?><?php if ($f['code']) echo ' [' . h($f['code']) . ']'; ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <?php if (!$isSuper): ?><input type="hidden" name="facility_id" value="<?php echo (int)$user['facility_id']; ?>"><?php endif; ?>
        </div>
        <div class="field"><label>Password *</label><input type="password" name="password" required autocomplete="new-password"></div>
    </div>
    <button type="submit" class="btn btn-primary">Create User</button>
</form>
<?php endif; ?>

<h3 class="mt-3">Existing Users</h3>
<div class="table-wrap">
<table class="data">
    <thead><tr>
        <th>ID</th><th>Username</th><th>Full Name</th><th>Role</th><th>Facility</th>
        <th>Active</th><th>New Password</th><th>Face</th><th>Actions</th>
    </tr></thead>
    <tbody>
    <?php
    $allRoleLabels = perms_role_options(true);
    foreach ($users as $u):
        $canEditTarget = $isSuper || (perms_role($u) === 'examiner' && (int)$u['facility_id'] === (int)$user['facility_id']);
    ?>
        <tr<?php if (!$u['active']) echo ' style="opacity:.6"'; ?>>
            <form method="post">
                <?php echo csrf_field(); ?>
                <input type="hidden" name="user_id" value="<?php echo (int)$u['id']; ?>">
                <td data-label="ID"><?php echo (int)$u['id']; ?></td>
                <td data-label="Username"><?php echo h($u['username']); ?></td>
                <td data-label="Full Name">
                    <?php if ($canEditTarget): ?>
                        <input type="text" name="full_name" value="<?php echo h($u['full_name']); ?>">
                    <?php else: ?><?php echo h($u['full_name']); ?><?php endif; ?>
                </td>
                <td data-label="Role">
                    <?php if ($canEditTarget && $isSuper): ?>
                        <select name="role">
                            <?php foreach ($allRoleLabels as $k => $v): ?>
                                <option value="<?php echo h($k); ?>" <?php if ($u['role']===$k) echo 'selected'; ?>><?php echo h($v); ?></option>
                            <?php endforeach; ?>
                        </select>
                    <?php else: ?>
                        <?php echo h($allRoleLabels[$u['role']] ?? $u['role']); ?>
                        <?php if ($canEditTarget): ?><input type="hidden" name="role" value="examiner"><?php endif; ?>
                    <?php endif; ?>
                </td>
                <td data-label="Facility">
                    <?php if ($canEditTarget && $isSuper): ?>
                        <select name="facility_id">
                            <option value="">None / Global</option>
                            <?php foreach ($facilities as $f): ?>
                                <option value="<?php echo (int)$f['id']; ?>" <?php if ((int)$u['facility_id']===(int)$f['id']) echo 'selected'; ?>>
                                    <?php echo h($f['name']); ?><?php if ($f['code']) echo ' [' . h($f['code']) . ']'; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    <?php else: ?>
                        <?php
                        $facName = '';
                        foreach ($facilities as $f) if ((int)$f['id']===(int)$u['facility_id']) $facName = $f['name'];
                        echo h($facName ?: '—');
                        ?>
                        <?php if ($canEditTarget): ?><input type="hidden" name="facility_id" value="<?php echo (int)$user['facility_id']; ?>"><?php endif; ?>
                    <?php endif; ?>
                </td>
                <td data-label="Active">
                    <?php if ($canEditTarget): ?>
                        <input type="checkbox" name="active" <?php if ($u['active']) echo 'checked'; ?>>
                    <?php else: ?>
                        <?php echo $u['active'] ? '✓' : '—'; ?>
                    <?php endif; ?>
                </td>
                <td data-label="New Password">
                    <?php if ($canEditTarget): ?>
                        <input type="password" name="password" placeholder="leave blank to keep" autocomplete="new-password">
                    <?php endif; ?>
                </td>
                <td data-label="Face">
                    <?php if ($u['face_enrolled_at']): ?>
                        <span class="badge <?php echo $u['face_login_enabled'] ? 'badge-submitted' : 'badge-waiting'; ?>"
                              title="<?php echo h($u['face_enrolled_at']); ?>">
                            <?php echo $u['face_login_enabled'] ? '✓ enrolled' : 'disabled'; ?>
                        </span>
                    <?php else: ?>
                        <span class="muted">none</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($canEditTarget): ?>
                        <button type="submit" name="update_user" value="1" class="btn btn-sm">Update</button>
                        <?php if ($u['face_enrolled_at']): ?>
                            <button type="submit" name="clear_face" value="1" class="btn btn-sm btn-danger"
                                    onclick="return confirm('Delete face data for <?php echo h($u['username']); ?>?');">Clear Face</button>
                        <?php endif; ?>
                        <?php if ($isSuper && (int)$u['id'] !== (int)$user['id']): ?>
                            <button type="submit" name="delete_user" value="<?php echo (int)$u['id']; ?>" class="btn btn-sm btn-danger"
                                    onclick="return confirm('Deactivate <?php echo h($u['username']); ?>?');">Deactivate</button>
                        <?php endif; ?>
                    <?php endif; ?>
                </td>
            </form>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>

<?php require __DIR__ . '/footer.php'; ?>
