<?php
require_once 'config.php';
require_once 'functions.php';
requireLogin();

$userId = (int)$_SESSION['user_id'];

// Filtre statut
$filterStatus = $_GET['status'] ?? 'all';
$allowedFilters = ['all', 'confirmée', 'annulée', 'terminée'];
if (!in_array($filterStatus, $allowedFilters)) $filterStatus = 'all';

$sql = "SELECT r.*, c.name as car_name, ch.name as chauffeur_name,
               (SELECT rat.stars FROM ratings rat WHERE rat.reservation_id = r.id LIMIT 1) as rating_stars
        FROM reservations r
        JOIN cars c        ON r.car_id       = c.id
        JOIN chauffeurs ch ON r.chauffeur_id = ch.id
        WHERE r.user_id = ?";
$params = [$userId];
if ($filterStatus !== 'all') { $sql .= " AND r.status = ?"; $params[] = $filterStatus; }
$sql .= " ORDER BY r.reservation_date DESC, r.reservation_time DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$reservations = $stmt->fetchAll();

// Compter par statut pour badges
$counts = $pdo->prepare("SELECT status, COUNT(*) as n FROM reservations WHERE user_id = ? GROUP BY status");
$counts->execute([$userId]);
$statusCounts = ['confirmée'=>0,'annulée'=>0,'terminée'=>0,'all'=>0];
foreach ($counts->fetchAll() as $row) {
    $statusCounts[$row['status']] = $row['n'];
    $statusCounts['all'] += $row['n'];
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mes réservations - First Car</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php include 'header.php'; ?>
<main class="container">
  <div style="display:flex;justify-content:space-between;align-items:flex-end;flex-wrap:wrap;gap:1rem;margin-bottom:1.5rem;">
    <h1 class="page-title" style="margin-bottom:0;">Mes réservations</h1>
    <a href="dashboard.php" class="btn btn-primary small">+ Nouvelle réservation</a>
  </div>

  <!-- Filtres -->
  <div style="display:flex;gap:.6rem;flex-wrap:wrap;margin-bottom:1.8rem;">
    <?php
    $filters = ['all'=>'Toutes','confirmée'=>'Confirmées','terminée'=>'Terminées','annulée'=>'Annulées'];
    foreach ($filters as $val => $label):
      $active = $filterStatus === $val;
    ?>
    <a href="my_reservations.php?status=<?= $val ?>"
       class="btn btn-ghost small"
       style="<?= $active ? 'background:var(--orange);color:var(--dark);border-color:var(--orange);' : '' ?>">
      <?= $label ?>
      <span style="opacity:.7;font-weight:400;">(<?= $statusCounts[$val] ?>)</span>
    </a>
    <?php endforeach; ?>
  </div>

  <?php if (empty($reservations)): ?>
  <div class="empty-state">
    <div class="empty-icon">🚗</div>
    <h3>Aucune réservation</h3>
    <p>Aucune réservation <?= $filterStatus !== 'all' ? '"'.$filterStatus.'"' : '' ?> trouvée.</p>
    <a href="dashboard.php" class="btn btn-primary">Voir nos véhicules</a>
  </div>
  <?php else: ?>
  <div class="reservations-table-wrapper">
    <table class="reservations-table">
      <thead>
        <tr>
          <th>Véhicule</th>
          <th>Chauffeur</th>
          <th>Date</th>
          <th>Heure</th>
          <th>Statut</th>
          <th>Note</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($reservations as $res):
          $isPast   = strtotime($res['reservation_date']) < strtotime(date('Y-m-d'));
          $isToday  = $res['reservation_date'] === date('Y-m-d');
          $canEdit  = $res['status'] === 'confirmée' && !$isPast;
          $canRate  = ($res['status'] === 'terminée' || ($res['status'] === 'confirmée' && $isPast)) && !$res['rating_stars'];
        ?>
        <tr>
          <td><strong><?= sanitize($res['car_name']) ?></strong></td>
          <td><?= sanitize($res['chauffeur_name']) ?></td>
          <td>
            <?= date('d/m/Y', strtotime($res['reservation_date'])) ?>
            <?php if ($isToday && $res['status'] === 'confirmée'): ?>
              <span class="car-badge" style="margin-left:.4rem;font-size:.62rem;">Aujourd'hui</span>
            <?php endif; ?>
          </td>
          <td><?= substr($res['reservation_time'], 0, 5) ?></td>
          <td><span class="status <?= $res['status'] ?>"><?= $res['status'] ?></span></td>
          <td>
            <?php if ($res['rating_stars']): ?>
              <span style="color:var(--orange);letter-spacing:.05em;"><?= str_repeat('★', $res['rating_stars']) ?><?= str_repeat('☆', 5-$res['rating_stars']) ?></span>
            <?php elseif ($canRate): ?>
              <a href="rate_reservation.php?id=<?= $res['id'] ?>" class="btn small btn-ghost" title="Laisser un avis">⭐ Noter</a>
            <?php else: ?>
              <span style="color:var(--light2);opacity:.4;">—</span>
            <?php endif; ?>
          </td>
          <td>
            <div class="td-actions">
              <?php if ($canEdit): ?>
                <a href="edit_reservation.php?id=<?= $res['id'] ?>" class="btn small btn-ghost">Modifier</a>
                <a href="cancel_reservation.php?id=<?= $res['id'] ?>" class="btn small danger"
                   onclick="return confirm('Annuler cette réservation ?')">Annuler</a>
              <?php else: ?>
                <span style="color:var(--light2);opacity:.4;font-size:.8rem;">—</span>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</main>
<?php include 'footer.php'; ?>
</body>
</html>
