<?php
$pageTitle = 'Gestion des Utilisateurs';
require_once __DIR__ . '/includes/header.php';
requireRole(['admin']);
$db = getDB();

$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
    if ($id == $_SESSION['user_id']) { flash('error', 'Impossible de supprimer votre propre compte.'); redirect('/utilisateurs.php'); }
    $db->prepare("UPDATE users SET status='inactif' WHERE id=?")->execute([$id]);
    logAction($_SESSION['user_id'], 'user_delete', "Utilisateur #$id désactivé");
    flash('success', 'Utilisateur désactivé.');
    redirect('/utilisateurs.php');
}

if ($action === 'activate' && $id) {
    $db->prepare("UPDATE users SET status='actif' WHERE id=?")->execute([$id]);
    flash('success', 'Utilisateur réactivé.');
    redirect('/utilisateurs.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $editId = intval($_POST['id'] ?? 0);
    $username = sanitize($_POST['username'] ?? '');
    $fullName = sanitize($_POST['full_name'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $phone = sanitize($_POST['phone'] ?? '');
    $role = $_POST['role'] ?? 'agent';
    $password = $_POST['password'] ?? '';

    // Check unique username
    $check = $db->prepare("SELECT id FROM users WHERE username=? AND id!=?");
    $check->execute([$username, $editId]);
    if ($check->fetch()) {
        flash('error', 'Ce nom d\'utilisateur existe déjà.');
        redirect('/utilisateurs.php?action=' . ($editId ? "edit&id=$editId" : 'add'));
    }

    if ($editId) {
        $sql = "UPDATE users SET username=?, full_name=?, email=?, phone=?, role=?, updated_at=datetime('now')";
        $params = [$username, $fullName, $email, $phone, $role];
        if ($password) {
            $sql .= ", password=?";
            $params[] = password_hash($password, PASSWORD_DEFAULT);
        }
        $sql .= " WHERE id=?";
        $params[] = $editId;
        $db->prepare($sql)->execute($params);
        logAction($_SESSION['user_id'], 'user_update', "Utilisateur #$editId modifié");
        flash('success', 'Utilisateur modifié.');
    } else {
        if (!$password) { flash('error', 'Le mot de passe est obligatoire.'); redirect('/utilisateurs.php?action=add'); }
        $db->prepare("INSERT INTO users (username, password, full_name, email, phone, role) VALUES (?,?,?,?,?,?)")
            ->execute([$username, password_hash($password, PASSWORD_DEFAULT), $fullName, $email, $phone, $role]);
        logAction($_SESSION['user_id'], 'user_create', "Utilisateur créé: $username");
        flash('success', 'Utilisateur créé.');
    }
    redirect('/utilisateurs.php');
}

// Form
if ($action === 'add' || $action === 'edit') {
    $user = null;
    if ($action === 'edit' && $id) {
        $stmt = $db->prepare("SELECT * FROM users WHERE id=?"); $stmt->execute([$id]); $user = $stmt->fetch();
    }
    $roles = ['admin'=>'Administrateur','responsable'=>'Responsable Tourisme/Hajj/Omra','comptable'=>'Comptable','agent'=>'Agent commercial'];
?>
    <div class="d-flex justify-content-between mb-4">
        <a href="<?= APP_URL ?>/utilisateurs.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Retour</a>
    </div>
    <div class="card table-card">
        <div class="card-header"><i class="bi bi-person-plus me-2"></i><?= $user ? 'Modifier l\'utilisateur' : 'Nouvel utilisateur' ?></div>
        <div class="card-body p-4">
            <form method="POST">
                <input type="hidden" name="id" value="<?= $user['id'] ?? '' ?>">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">Nom d'utilisateur *</label>
                        <input type="text" name="username" class="form-control" value="<?= sanitize($user['username'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Nom complet *</label>
                        <input type="text" name="full_name" class="form-control" value="<?= sanitize($user['full_name'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Rôle *</label>
                        <select name="role" class="form-select" required>
                            <?php foreach ($roles as $k=>$v): ?>
                                <option value="<?= $k ?>" <?= ($user['role'] ?? '')==$k?'selected':'' ?>><?= $v ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" value="<?= sanitize($user['email'] ?? '') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Téléphone</label>
                        <input type="text" name="phone" class="form-control" value="<?= sanitize($user['phone'] ?? '') ?>">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Mot de passe <?= $user ? '(laisser vide pour ne pas changer)' : '*' ?></label>
                        <input type="password" name="password" class="form-control" <?= !$user ? 'required' : '' ?>>
                    </div>
                </div>
                <div class="d-flex gap-2 mt-4">
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Enregistrer</button>
                    <a href="<?= APP_URL ?>/utilisateurs.php" class="btn btn-outline-secondary">Annuler</a>
                </div>
            </form>
        </div>
    </div>
<?php require_once __DIR__ . '/includes/footer.php'; exit; }

// List
$users = $db->query("SELECT * FROM users ORDER BY role, full_name")->fetchAll();
$roleLabels = ['admin'=>'Administrateur','responsable'=>'Responsable','comptable'=>'Comptable','agent'=>'Agent'];
$roleBadges = ['admin'=>'bg-danger','responsable'=>'bg-primary','comptable'=>'bg-warning text-dark','agent'=>'bg-info'];
?>

<div class="d-flex justify-content-between mb-4">
    <h6 class="text-muted mb-0"><?= count($users) ?> utilisateur(s)</h6>
    <a href="<?= APP_URL ?>/utilisateurs.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Nouvel utilisateur</a>
</div>

<div class="card table-card">
    <div class="table-responsive">
        <table class="table table-hover">
            <thead><tr><th>Utilisateur</th><th>Nom complet</th><th>Rôle</th><th>Email</th><th>Téléphone</th><th>Dernière connexion</th><th>Statut</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($users as $u): ?>
                <tr>
                    <td><strong><?= sanitize($u['username']) ?></strong></td>
                    <td><?= sanitize($u['full_name']) ?></td>
                    <td><span class="badge <?= $roleBadges[$u['role']] ?? 'bg-secondary' ?>"><?= $roleLabels[$u['role']] ?? $u['role'] ?></span></td>
                    <td><?= sanitize($u['email'] ?: '-') ?></td>
                    <td><?= sanitize($u['phone'] ?: '-') ?></td>
                    <td><small><?= $u['last_login'] ? formatDateTime($u['last_login']) : 'Jamais' ?></small></td>
                    <td><?= getStatusBadge($u['status']) ?></td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <a href="<?= APP_URL ?>/utilisateurs.php?action=edit&id=<?= $u['id'] ?>" class="btn btn-outline-warning"><i class="bi bi-pencil"></i></a>
                            <?php if ($u['status'] === 'inactif'): ?>
                                <a href="<?= APP_URL ?>/utilisateurs.php?action=activate&id=<?= $u['id'] ?>" class="btn btn-outline-success" title="Réactiver"><i class="bi bi-check-lg"></i></a>
                            <?php elseif ($u['id'] != $_SESSION['user_id']): ?>
                                <a href="<?= APP_URL ?>/utilisateurs.php?action=delete&id=<?= $u['id'] ?>" class="btn btn-outline-danger" onclick="return confirmDelete('Désactiver cet utilisateur ?')"><i class="bi bi-x-lg"></i></a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
