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

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

$stmt = $pdo->prepare("SELECT r.*, c.name as car_name, ch.name as chauffeur_name, ch.photo as chauffeur_photo,
                              ch.total_trips, ch.punctuality_rate
                        FROM reservations r
                        JOIN cars c  ON r.car_id       = c.id
                        JOIN chauffeurs ch ON r.chauffeur_id = ch.id
                        WHERE r.id = ? AND r.user_id = ?");
$stmt->execute([$reservationId, $_SESSION['user_id']]);
$reservation = $stmt->fetch();

if (!$reservation) redirect('my_reservations.php');

if ($reservation['status'] !== 'confirmée' || strtotime($reservation['reservation_date']) < strtotime(date('Y-m-d'))) {
    $_SESSION['error'] = "Cette réservation ne peut plus être modifiée.";
    redirect('my_reservations.php');
}

$step = isset($_POST['step']) ? (int)$_POST['step'] : 1;

// Récupérer les avis des chauffeurs
$ratingsStmt = $pdo->prepare("SELECT rat.*, u.name as user_name 
                               FROM ratings rat
                               JOIN users u ON rat.user_id = u.id
                               WHERE rat.reservation_id IN (SELECT id FROM reservations WHERE chauffeur_id = ?)
                               ORDER BY rat.created_at DESC
                               LIMIT 5");
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modifier la réservation - First Car</title>
    <link rel="stylesheet" href="style.css">
    <style>
        /* Centrage du conteneur */
        .edit-container {
            max-width: 900px;
            margin: 0 auto;
        }
        
        .edit-container h2 {
            text-align: center;
            font-family: 'Cormorant Garamond', serif;
            font-size: 1.8rem;
            margin-bottom: 1.5rem;
        }
        
        /* Style pour le résumé actuel */
        .current-reservation {
            background: linear-gradient(135deg, rgba(232,130,12,0.1), rgba(0,0,0,0.3));
            border: 1px solid rgba(232,130,12,0.2);
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1.2rem;
        }
        
        .current-item {
            text-align: center;
        }
        
        .current-item .label {
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            color: var(--orange);
            margin-bottom: 0.3rem;
        }
        
        .current-item .value {
            font-size: 1rem;
            font-weight: 600;
            color: var(--light);
        }
        
        .current-item .value i {
            color: var(--orange);
            margin-right: 0.3rem;
        }
        
        /* Style pour la carte chauffeur dans l'étape 2 */
        .chauffeur-detail-card {
            background: linear-gradient(145deg, rgba(30,30,30,0.95), rgba(20,20,20,0.98));
            border: 1px solid rgba(232,130,12,0.2);
            border-radius: 20px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            display: flex;
            gap: 2rem;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .chauffeur-detail-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid var(--orange);
        }
        
        .chauffeur-detail-info h3 {
            font-family: 'Cormorant Garamond', serif;
            font-size: 1.6rem;
            margin-bottom: 0.3rem;
        }
        
        .chauffeur-detail-stats {
            display: flex;
            gap: 1.5rem;
            margin-top: 0.8rem;
        }
        
        .stat {
            text-align: center;
        }
        
        .stat .number {
            font-size: 1.2rem;
            font-weight: 700;
            color: var(--orange);
        }
        
        .stat .label {
            font-size: 0.65rem;
            text-transform: uppercase;
            color: var(--light2);
        }
        
        /* Style pour la grille des chauffeurs */
        .chauffeur-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
            margin: 2rem 0;
        }
        
        .chauffeur-card {
            background: linear-gradient(145deg, rgba(30,30,30,0.9), rgba(20,20,20,0.95));
            border: 1px solid rgba(232,130,12,0.15);
            border-radius: 15px;
            padding: 1.2rem;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .chauffeur-card:hover {
            transform: translateY(-3px);
            border-color: rgba(232,130,12,0.4);
            box-shadow: 0 10px 20px rgba(232,130,12,0.2);
        }
        
        .chauffeur-card.selected {
            border: 2px solid var(--orange);
            background: linear-gradient(145deg, rgba(232,130,12,0.1), rgba(20,20,20,0.95));
        }
        
        .chauffeur-card-header {
            display: flex;
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .chauffeur-card-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid var(--orange);
        }
        
        .chauffeur-card-info h4 {
            font-size: 1.1rem;
            margin-bottom: 0.2rem;
        }
        
        .chauffeur-card-rating {
            color: var(--orange);
            font-size: 0.8rem;
        }
        
        .chauffeur-card-badges {
            display: flex;
            flex-wrap: wrap;
            gap: 0.3rem;
            margin: 0.5rem 0;
        }
        
        .badge {
            font-size: 0.65rem;
            padding: 0.2rem 0.5rem;
            background: rgba(255,255,255,0.05);
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 20px;
            color: var(--light2);
        }
        
        .badge.orange {
            background: rgba(232,130,12,0.15);
            border-color: rgba(232,130,12,0.3);
            color: var(--orange);
        }
        
        .chauffeur-card-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 0.8rem;
            font-size: 0.75rem;
            color: var(--light2);
        }
        
        .selector {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 2px solid rgba(255,255,255,0.2);
        }
        
        .chauffeur-card.selected .selector {
            background: var(--orange);
            border-color: var(--orange);
            position: relative;
        }
        
        .chauffeur-card.selected .selector::after {
            content: '✓';
            color: var(--dark);
            font-size: 0.7rem;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        
        /* Style pour la modal des avis */
        .reviews-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        
        .reviews-modal.active {
            display: flex;
        }
        
        .reviews-content {
            background: linear-gradient(145deg, #1a1a1a, #0f0f0f);
            border: 1px solid var(--orange);
            border-radius: 20px;
            padding: 2rem;
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .reviews-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }
        
        .reviews-header h3 {
            font-family: 'Cormorant Garamond', serif;
            font-size: 1.5rem;
        }
        
        .close-btn {
            font-size: 2rem;
            cursor: pointer;
            color: var(--light2);
        }
        
        .close-btn:hover {
            color: var(--orange);
        }
        
        .review-item {
            border-bottom: 1px solid rgba(255,255,255,0.1);
            padding: 1rem 0;
        }
        
        .review-item:last-child {
            border-bottom: none;
        }
        
        .review-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
        }
        
        .review-stars {
            color: var(--orange);
        }
        
        .review-author {
            font-size: 0.8rem;
            color: var(--light2);
        }
        
        .review-comment {
            font-size: 0.9rem;
            color: var(--light);
            line-height: 1.5;
        }
        
        .review-date {
            font-size: 0.7rem;
            color: var(--light2);
            margin-top: 0.3rem;
            text-align: right;
        }
        
        .view-reviews-btn {
            background: none;
            border: 1px solid var(--orange);
            color: var(--orange);
            padding: 0.2rem 0.8rem;
            border-radius: 20px;
            font-size: 0.7rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .view-reviews-btn:hover {
            background: var(--orange);
            color: var(--dark);
        }
        
        /* Centrage du formulaire étape 1 */
        .form-center {
            max-width: 500px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
<?php include 'header.php'; ?>
<main class="container edit-container">
  <a href="my_reservations.php" class="back-link">← Retour à mes réservations</a>
  <h1 class="page-title" style="text-align:center;">Modifier la réservation</h1>

  <!-- Récap actuel amélioré -->
  <div class="current-reservation">
    <div class="current-item">
      <div class="label">Véhicule</div>
      <div class="value"><i>🚗</i> <?= htmlspecialchars($reservation['car_name']) ?></div>
    </div>
    <div class="current-item">
      <div class="label">Chauffeur actuel</div>
      <div class="value"><i>🎩</i> <?= htmlspecialchars($reservation['chauffeur_name']) ?></div>
    </div>
    <div class="current-item">
      <div class="label">Date actuelle</div>
      <div class="value"><i>📅</i> <?= date('d/m/Y', strtotime($reservation['reservation_date'])) ?></div>
    </div>
    <div class="current-item">
      <div class="label">Heure actuelle</div>
      <div class="value"><i>⏰</i> <?= substr($reservation['reservation_time'],0,5) ?></div>
    </div>
  </div>

  <?php if ($step == 1): ?>
  <!-- ── ÉTAPE 1 : Nouveau créneau (centré) ── -->
  <div class="form form-center">
    <h2>Nouveau créneau</h2>
    <form method="post">
      <?= csrf_field() ?>
      <input type="hidden" name="step" value="2">
      <input type="hidden" name="reservation_id" value="<?= $reservation['id'] ?>">
      <div class="form-row">
        <div class="form-group">
          <label>Nouvelle date</label>
          <input type="date" name="date" min="<?= date('Y-m-d') ?>" value="<?= $reservation['reservation_date'] ?>" required>
        </div>
        <div class="form-group">
          <label>Nouvelle heure</label>
          <input type="time" name="time" value="<?= substr($reservation['reservation_time'],0,5) ?>" required>
        </div>
      </div>
      <div style="display:flex;gap:1rem;margin-top:1.5rem;">
        <a href="my_reservations.php" class="btn btn-outline" style="flex:1;">Annuler</a>
        <button type="submit" class="btn btn-primary" style="flex:2;">Voir les chauffeurs disponibles →</button>
      </div>
    </form>
  </div>

  <?php elseif ($step == 2): ?>
  <?php
  $newDate = $_POST['date'] ?? '';
  $newTime = $_POST['time'] ?? '';

  if (strtotime($newDate) < strtotime(date('Y-m-d'))) {
      $_SESSION['error'] = "La date ne peut pas être dans le passé.";
      redirect("edit_reservation.php?id=$reservationId");
  }
  $availableChauffeurs = getAvailableChauffeurs($pdo, $newDate, $newTime);
  
  // Récupérer les notes moyennes des chauffeurs
  $avgRatings = [];
  $ratingsStmt = $pdo->query("SELECT chauffeur_id, ROUND(AVG(stars), 1) as avg_rating, COUNT(*) as rating_count 
                               FROM ratings r 
                               JOIN reservations res ON r.reservation_id = res.id 
                               GROUP BY chauffeur_id");
  foreach ($ratingsStmt->fetchAll() as $rating) {
      $avgRatings[$rating['chauffeur_id']] = [
          'avg' => $rating['avg_rating'],
          'count' => $rating['rating_count']
      ];
  }
  ?>

  <div class="trip-summary" style="background:rgba(232,130,12,0.1);border:1px solid rgba(232,130,12,0.2);border-radius:12px;padding:1.2rem;margin-bottom:1.5rem;text-align:center;">
    <p style="font-size:1rem;">
      <strong>Nouveau créneau :</strong> 
      <span style="color:var(--orange);"><?= date('d/m/Y',strtotime($newDate)) ?> à <?= $newTime ?></span>
    </p>
  </div>

  <?php if (empty($availableChauffeurs)): ?>
  <div class="alert warning" style="text-align:center;">
    <strong>Aucun chauffeur disponible</strong> à ce créneau. Essayez un autre horaire.
  </div>
  <div style="text-align:center;margin-top:1.5rem;">
    <a href="edit_reservation.php?id=<?= $reservation['id'] ?>" class="btn btn-outline">← Choisir un autre créneau</a>
  </div>
  <?php else: ?>
  
  <h2 style="text-align:center;font-family:'Cormorant Garamond',serif;font-size:1.8rem;margin-bottom:1rem;">Choisissez un chauffeur</h2>
  <p style="text-align:center;color:var(--light2);margin-bottom:2rem;"><?= count($availableChauffeurs) ?> chauffeur(s) disponible(s) pour ce créneau</p>
  
  <!-- Modal pour les avis -->
  <div class="reviews-modal" id="reviewsModal">
    <div class="reviews-content">
      <div class="reviews-header">
        <h3>Avis des clients</h3>
        <span class="close-btn" onclick="closeReviews()">&times;</span>
      </div>
      <div id="reviewsList"></div>
    </div>
  </div>

  <form method="post" action="update_reservation.php">
    <?= csrf_field() ?>
    <input type="hidden" name="reservation_id" value="<?= $reservation['id'] ?>">
    <input type="hidden" name="date" value="<?= htmlspecialchars($newDate) ?>">
    <input type="hidden" name="time" value="<?= htmlspecialchars($newTime) ?>">
    
    <div class="chauffeur-grid">
      <?php foreach ($availableChauffeurs as $ch): 
          $avgRating = $avgRatings[$ch['id']]['avg'] ?? 4.5;
          $ratingCount = $avgRatings[$ch['id']]['count'] ?? 0;
          $isCurrent = ($ch['id'] == $reservation['chauffeur_id']);
          
          // Récupérer les avis pour ce chauffeur
          $reviewsStmt = $pdo->prepare("SELECT rat.*, u.name as user_name 
                                         FROM ratings rat
                                         JOIN users u ON rat.user_id = u.id
                                         JOIN reservations res ON rat.reservation_id = res.id
                                         WHERE res.chauffeur_id = ?
                                         ORDER BY rat.created_at DESC
                                         LIMIT 3");
          $reviewsStmt->execute([$ch['id']]);
          $reviews = $reviewsStmt->fetchAll();
      ?>
      <div class="chauffeur-card <?= $isCurrent ? 'selected' : '' ?>">
        <input type="radio" name="chauffeur_id" value="<?= $ch['id'] ?>" id="ch_<?= $ch['id'] ?>" <?= $isCurrent ? 'checked' : '' ?> required style="display:none;">
        <label for="ch_<?= $ch['id'] ?>" style="cursor:pointer;">
          <div class="chauffeur-card-header">
            <?php if (!empty($ch['photo'])): ?>
              <img src="images/<?= htmlspecialchars($ch['photo']) ?>" alt="" class="chauffeur-card-avatar">
            <?php else: ?>
              <div class="chauffeur-card-avatar" style="background:rgba(232,130,12,0.2);display:flex;align-items:center;justify-content:center;">🎩</div>
            <?php endif; ?>
            <div class="chauffeur-card-info">
              <h4><?= htmlspecialchars($ch['name']) ?></h4>
              <div class="chauffeur-card-rating">
                <?= str_repeat('★', floor($avgRating)) ?><?= ($avgRating - floor($avgRating)) >= 0.5 ? '½' : '' ?>
                <span style="color:var(--light2);font-size:0.7rem;">(<?= $ratingCount ?> avis)</span>
              </div>
              <div style="font-size:0.7rem;color:var(--light2);">
                📞 <?= htmlspecialchars($ch['phone'] ?: 'Non renseigné') ?>
              </div>
            </div>
            <div class="selector"></div>
          </div>
          
          <div class="chauffeur-card-badges">
            <span class="badge orange">⭐ <?= $ch['total_trips'] ?? 120 ?> trajets</span>
            <span class="badge">⏱️ <?= $ch['punctuality_rate'] ?? 98 ?>% ponctuel</span>
            <?php if ($isCurrent): ?>
            <span class="badge orange">✓ Chauffeur actuel</span>
            <?php endif; ?>
          </div>
          
          <!-- Aperçu des avis -->
          <?php if (!empty($reviews)): ?>
          <div style="margin-top:0.8rem;background:rgba(0,0,0,0.3);border-radius:8px;padding:0.5rem;">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.3rem;">
              <span style="font-size:0.7rem;color:var(--orange);">Derniers avis</span>
              <button type="button" class="view-reviews-btn" onclick='showReviews(<?= json_encode($reviews) ?>, "<?= htmlspecialchars($ch['name']) ?>")'>Voir tout</button>
            </div>
            <?php foreach (array_slice($reviews, 0, 1) as $review): ?>
            <div style="font-size:0.75rem;color:var(--light2);">
              <span style="color:var(--orange);"><?= str_repeat('★', $review['stars']) ?></span> "<?= htmlspecialchars(substr($review['comment'], 0, 50)) ?>..."
            </div>
            <?php endforeach; ?>
          </div>
          <?php endif; ?>
        </label>
      </div>
      <?php endforeach; ?>
    </div>
    
    <div style="display:flex;gap:1rem;justify-content:center;margin-top:2rem;">
      <a href="edit_reservation.php?id=<?= $reservation['id'] ?>" class="btn btn-outline" style="min-width:150px;">← Retour</a>
      <button type="submit" class="btn btn-primary" style="min-width:200px;">Mettre à jour ✓</button>
    </div>
  </form>
  
  <script>
  function showReviews(reviews, chauffeurName) {
      const modal = document.getElementById('reviewsModal');
      const reviewsList = document.getElementById('reviewsList');
      
      let html = `<h4 style="margin-bottom:1rem;color:var(--orange);">Avis pour ${chauffeurName}</h4>`;
      
      reviews.forEach(review => {
          html += `
              <div class="review-item">
                  <div class="review-header">
                      <span class="review-stars">${'★'.repeat(review.stars)}${'☆'.repeat(5-review.stars)}</span>
                      <span class="review-author">${review.user_name}</span>
                  </div>
                  <div class="review-comment">${review.comment}</div>
                  <div class="review-date">${new Date(review.created_at).toLocaleDateString('fr-FR')}</div>
              </div>
          `;
      });
      
      reviewsList.innerHTML = html;
      modal.classList.add('active');
  }
  
  function closeReviews() {
      document.getElementById('reviewsModal').classList.remove('active');
  }
  
  // Fermer la modal en cliquant en dehors
  window.onclick = function(event) {
      const modal = document.getElementById('reviewsModal');
      if (event.target === modal) {
          closeReviews();
      }
  }
  
  // Gestion de la sélection des cartes
  document.querySelectorAll('.chauffeur-card').forEach(card => {
      card.addEventListener('click', function() {
          document.querySelectorAll('.chauffeur-card').forEach(c => c.classList.remove('selected'));
          this.classList.add('selected');
          const radio = this.querySelector('input[type="radio"]');
          if (radio) radio.checked = true;
      });
  });
  </script>
  
  <?php endif; ?>
  <?php endif; ?>
</main>
<?php include 'footer.php'; ?>
</body>
</html>