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

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

if ($action === 'terminate' && $id) {
    $pdo->prepare("UPDATE reservations SET status='terminée' WHERE id=?")->execute([$id]);
    $_SESSION['flash'] = "Réservation marquée comme terminée.";
    redirect('reservations.php');
}
if ($action === 'cancel' && $id) {
    $pdo->prepare("UPDATE reservations SET status='annulée' WHERE id=?")->execute([$id]);
    $_SESSION['flash'] = "Réservation annulée.";
    redirect('reservations.php');
}

// Filtres
$status  = $_GET['status'] ?? 'all';
$search  = trim($_GET['q'] ?? '');

$sql = "SELECT r.*, u.name as user_name, u.email as user_email,
               c.name as car_name, ch.name as chauffeur_name
        FROM reservations r
        JOIN users u ON r.user_id=u.id
        JOIN cars c ON r.car_id=c.id
        JOIN chauffeurs ch ON r.chauffeur_id=ch.id
        WHERE 1=1";
$params = [];
if ($status !== 'all') { $sql .= " AND r.status=?"; $params[] = $status; }
if ($search) {
    $sql .= " AND (u.name LIKE ? OR c.name LIKE ? OR ch.name LIKE ?)";
    $params = array_merge($params, ["%$search%","%$search%","%$search%"]);
}
$sql .= " ORDER BY r.reservation_date DESC, r.reservation_time DESC LIMIT 100";
$reservations = $pdo->prepare($sql);
$reservations->execute($params);
$reservations = $reservations->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Réservations – 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;overflow-y:auto;}
      .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;}
      .search-bar{display:flex;gap:.8rem;flex-wrap:wrap;margin-bottom:1.5rem;align-items:center;}
      .search-bar input{flex:1;min-width:200px;padding:.7rem 1rem;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.1);border-radius:8px;color:var(--light);font-family:inherit;font-size:.88rem;}
      .search-bar input:focus{outline:none;border-color:var(--orange);}
    </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" class="active">📅 Réservations</a></li>
      <li><a href="users.php">👥 Utilisateurs</a></li>
      <li><a href="chauffeurs.php">🎩 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; ?>

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

    <!-- Filtres -->
    <form method="get" class="search-bar">
      <input type="text" name="q" placeholder="Rechercher client, voiture, chauffeur…" value="<?= sanitize($search) ?>">
      <?php foreach (['all'=>'Toutes','confirmée'=>'Confirmées','terminée'=>'Terminées','annulée'=>'Annulées'] as $v=>$l): ?>
      <button type="submit" name="status" value="<?= $v ?>" class="btn small <?= $status===$v?'btn-primary':'btn-ghost' ?>"><?= $l ?></button>
      <?php endforeach; ?>
    </form>

    <div class="reservations-table-wrapper">
      <table class="reservations-table">
        <thead>
          <tr><th>ID</th><th>Client</th><th>Véhicule</th><th>Chauffeur</th><th>Date</th><th>Heure</th><th>Départ</th><th>Statut</th><th>Actions</th></tr>
        </thead>
        <tbody>
          <?php foreach ($reservations as $r): ?>
          <tr>
            <td style="opacity:.5;">#<?= $r['id'] ?></td>
            <td>
              <strong><?= sanitize($r['user_name']) ?></strong><br>
              <span style="font-size:.75rem;color:var(--light2);"><?= sanitize($r['user_email']) ?></span>
            </td>
            <td><?= sanitize($r['car_name']) ?></td>
            <td><?= sanitize($r['chauffeur_name']) ?></td>
            <td><?= date('d/m/Y', strtotime($r['reservation_date'])) ?></td>
            <td><?= substr($r['reservation_time'],0,5) ?></td>
            <td style="font-size:.8rem;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?= sanitize($r['pickup_address'] ?: '—') ?></td>
            <td><span class="status <?= $r['status'] ?>"><?= $r['status'] ?></span></td>
            <td>
              <div class="td-actions">
                <?php if ($r['status']==='confirmée'): ?>
                <a href="reservations.php?action=terminate&id=<?= $r['id'] ?>" class="btn small btn-ghost"
                   onclick="return confirm('Marquer comme terminée ?')">✅</a>
                <a href="reservations.php?action=cancel&id=<?= $r['id'] ?>" class="btn small danger"
                   onclick="return confirm('Annuler cette réservation ?')">✖</a>
                <?php endif; ?>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </main>
</div>
</body>
</html>
