<?php
require_once '../config.php';
require_once '../functions.php';
requireAdmin();

$errors  = [];
$success = '';
$editCh  = null;

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

// Toggle actif
if ($action === 'toggle' && $id) {
    $pdo->prepare("UPDATE chauffeurs SET active = 1 - active WHERE id=?")->execute([$id]);
    redirect('chauffeurs.php');
}

// Suppression
if ($action === 'delete' && $id) {
    try {
        $pdo->prepare("DELETE FROM chauffeurs WHERE id=?")->execute([$id]);
        $_SESSION['flash'] = "Chauffeur supprimé.";
    } catch (PDOException) {
        $_SESSION['error'] = "Impossible de supprimer ce chauffeur (réservations existantes).";
    }
    redirect('chauffeurs.php');
}

// Édition — charger données
if ($action === 'edit' && $id) {
    $editCh = $pdo->prepare("SELECT * FROM chauffeurs WHERE id=?");
    $editCh->execute([$id]);
    $editCh = $editCh->fetch();
}

// Formulaire (ajout ou modif)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $name    = trim($_POST['name'] ?? '');
    $phone   = trim($_POST['phone'] ?? '');
    $editId  = (int)($_POST['edit_id'] ?? 0);

    if (empty($name)) $errors[] = "Le nom est requis.";

    if (empty($errors)) {
        if ($editId) {
            $pdo->prepare("UPDATE chauffeurs SET name=?, phone=? WHERE id=?")
                ->execute([$name, $phone ?: null, $editId]);
            $success = "Chauffeur mis à jour.";
        } else {
            $pdo->prepare("INSERT INTO chauffeurs (name, phone) VALUES (?,?)")
                ->execute([$name, $phone ?: null]);
            $success = "Chauffeur ajouté.";
        }
        redirect('chauffeurs.php');
    }
}

$chauffeurs = $pdo->query("SELECT c.*, COUNT(ca.id) as nb_slots FROM chauffeurs c
                            LEFT JOIN chauffeur_availability ca ON c.id=ca.chauffeur_id
                            GROUP BY c.id ORDER BY c.name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Chauffeurs – Admin First Car</title>
    <link rel="stylesheet" href="../style.css">
    <style>
      .admin-layout{display:grid;grid-template-columns:220px 1fr;min-height:100vh;}
      .admin-sidebar{background:rgba(0,0,0,.6);border-right:1px solid rgba(232,130,12,.15);padding:2rem 1.2rem;position:sticky;top:0;height:100vh;}
      .admin-sidebar .nav-logo{font-size:1.4rem;display:block;margin-bottom:.3rem;}
      .admin-sidebar .admin-badge{font-size:.65rem;text-transform:uppercase;letter-spacing:.12em;color:var(--orange);font-weight:700;margin-bottom:2rem;display:block;}
      .sidebar-nav{list-style:none;}.sidebar-nav li{margin-bottom:.3rem;}
      .sidebar-nav a{display:block;padding:.65rem 1rem;border-radius:8px;color:var(--light2);text-decoration:none;font-size:.82rem;font-weight:500;transition:all .2s;}
      .sidebar-nav a:hover,.sidebar-nav a.active{background:rgba(232,130,12,.12);color:var(--orange);}
      .admin-main{padding:2rem 2.5rem;}
      .admin-two-col{display:grid;grid-template-columns:1fr 360px;gap:2rem;align-items:start;}
      @media(max-width:900px){.admin-two-col{grid-template-columns:1fr;}}
    </style>
</head>
<body>
<div class="admin-layout">
  <aside class="admin-sidebar">
    <a href="../index.php" class="nav-logo">First Car<span>.</span></a>
    <span class="admin-badge">Administration</span>
    <ul class="sidebar-nav">
      <li><a href="index.php">📊 Tableau de bord</a></li>
      <li><a href="reservations.php">📅 Réservations</a></li>
      <li><a href="users.php">👥 Utilisateurs</a></li>
      <li><a href="chauffeurs.php" class="active">🎩 Chauffeurs</a></li>
      <li><a href="cars.php">🚗 Véhicules</a></li>
      <li><a href="ratings.php">⭐ Avis clients</a></li>
      <li style="margin-top:2rem;border-top:1px solid rgba(255,255,255,.06);padding-top:1rem;">
        <a href="../dashboard.php">← Espace client</a></li>
      <li><a href="../logout.php" style="color:#f44336;">Déconnexion</a></li>
    </ul>
  </aside>
  <main class="admin-main">
    <?php if (isset($_SESSION['flash'])): ?>
    <div class="alert success"><?= sanitize($_SESSION['flash']) ?></div>
    <?php unset($_SESSION['flash']); endif; ?>
    <?php if (isset($_SESSION['error'])): ?>
    <div class="alert error"><?= sanitize($_SESSION['error']) ?></div>
    <?php unset($_SESSION['error']); endif; ?>

    <h1 style="font-family:'Cormorant Garamond',serif;font-size:2rem;margin-bottom:1.5rem;">Chauffeurs</h1>

    <div class="admin-two-col">
      <!-- Liste -->
      <div class="reservations-table-wrapper">
        <table class="reservations-table">
          <thead><tr><th>Nom</th><th>Téléphone</th><th>Créneaux</th><th>Statut</th><th>Actions</th></tr></thead>
          <tbody>
            <?php foreach ($chauffeurs as $ch): ?>
            <tr>
              <td><strong><?= sanitize($ch['name']) ?></strong></td>
              <td><?= sanitize($ch['phone'] ?: '—') ?></td>
              <td><?= $ch['nb_slots'] ?></td>
              <td>
                <?php if ($ch['active']): ?>
                  <span class="status confirmée">Actif</span>
                <?php else: ?>
                  <span class="status annulée">Inactif</span>
                <?php endif; ?>
              </td>
              <td>
                <div class="td-actions">
                  <a href="chauffeurs.php?action=edit&id=<?= $ch['id'] ?>" class="btn small btn-ghost">Modifier</a>
                  <a href="chauffeurs.php?action=toggle&id=<?= $ch['id'] ?>" class="btn small btn-ghost">
                    <?= $ch['active'] ? 'Désactiver' : 'Activer' ?>
                  </a>
                  <a href="chauffeurs.php?action=delete&id=<?= $ch['id'] ?>" class="btn small danger"
                     onclick="return confirm('Supprimer ce chauffeur ?')">✖</a>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <!-- Formulaire ajout/modif -->
      <div class="form" style="margin:0;">
        <h3 style="font-family:'Cormorant Garamond',serif;font-size:1.3rem;margin-bottom:1.2rem;">
          <?= $editCh ? 'Modifier le chauffeur' : 'Ajouter un chauffeur' ?>
        </h3>
        <?php if (!empty($errors)): ?>
        <div class="alert error"><?php foreach($errors as $e): ?><p><?= sanitize($e) ?></p><?php endforeach; ?></div>
        <?php endif; ?>
        <form method="post">
          <?= csrf_field() ?>
          <input type="hidden" name="edit_id" value="<?= $editCh ? $editCh['id'] : 0 ?>">
          <div class="form-group">
            <label>Nom complet *</label>
            <input type="text" name="name" required value="<?= sanitize($editCh['name'] ?? '') ?>">
          </div>
          <div class="form-group">
            <label>Téléphone</label>
            <input type="text" name="phone" placeholder="06 XX XX XX XX" value="<?= sanitize($editCh['phone'] ?? '') ?>">
          </div>
          <div style="display:flex;gap:.8rem;">
            <?php if ($editCh): ?>
            <a href="chauffeurs.php" class="btn btn-ghost" style="flex:1;justify-content:center;">Annuler</a>
            <?php endif; ?>
            <button type="submit" class="btn btn-primary" style="flex:2;justify-content:center;">
              <?= $editCh ? 'Mettre à jour' : 'Ajouter' ?>
            </button>
          </div>
        </form>
      </div>
    </div>
  </main>
</div>
</body>
</html>
