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

$step  = isset($_POST['step']) ? (int)$_POST['step'] : 1;
$carId = isset($_GET['car_id']) ? (int)$_GET['car_id'] : (isset($_POST['car_id']) ? (int)$_POST['car_id'] : 0);

$stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ? AND active = 1");
$stmt->execute([$carId]);
$car = $stmt->fetch();
if (!$car) redirect('dashboard.php');

$catInfo = [
    'Tesla Model Y'    => ['badge'=>'Électrique',    'specs'=>['SUV Premium','5 passagers','100% Électrique'],'price'=>'3,20 €/km'],
    'Toyota'           => ['badge'=>'Berline',        'specs'=>['Berline Confort','4 passagers','Hybride'],   'price'=>'2,20 €/km'],
    'Mercedes Viano'   => ['badge'=>'Monospace VIP',  'specs'=>['Grand Monospace','7 passagers','Luxe'],      'price'=>'3,80 €/km'],
    'Volkswagen Jetta' => ['badge'=>'Berline Sport',  'specs'=>['Berline','4 passagers','Dynamique'],         'price'=>'2,50 €/km'],
];
$info = $catInfo[$car['name']] ?? ['badge'=>'Véhicule','specs'=>[],'price'=>number_format($car['price_km'],2,',','.').' €/km'];

// Récupérer les évaluations des chauffeurs pour afficher les notes
$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");
$chauffeurRatings = [];
foreach ($ratingsStmt->fetchAll() as $rating) {
    $chauffeurRatings[$rating['chauffeur_id']] = [
        'avg' => $rating['avg_rating'],
        'count' => $rating['rating_count']
    ];
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Réserver <?= sanitize($car['name']) ?> - First Car</title>
    <link rel="stylesheet" href="style.css">
    <style>
        /* Style supplémentaire pour le centrage */
        .booking-form-center {
            max-width: 600px;
            margin: 0 auto;
        }
        .booking-form-center h2 {
            text-align: center;
        }
        
        /* Style amélioré pour les cartes chauffeurs - DESIGN ÉLÉGANT */
        .chauffeur-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 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: 20px;
            padding: 1.5rem;
            transition: all 0.3s ease;
            position: relative;
            cursor: pointer;
            box-shadow: 0 10px 20px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        .chauffeur-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 5px;
            background: linear-gradient(90deg, var(--orange), #ffb347, var(--orange));
            transform: scaleX(0);
            transition: transform 0.3s ease;
        }
        
        .chauffeur-card:hover {
            transform: translateY(-5px);
            border-color: rgba(232,130,12,0.4);
            box-shadow: 0 15px 30px rgba(232,130,12,0.25);
        }
        
        .chauffeur-card:hover::before {
            transform: scaleX(1);
        }
        
        .chauffeur-card.selected {
            border: 2px solid var(--orange);
            background: linear-gradient(145deg, rgba(232,130,12,0.1), rgba(20,20,20,0.95));
            box-shadow: 0 0 25px rgba(232,130,12,0.4);
        }
        
        .chauffeur-card.selected::before {
            transform: scaleX(1);
        }
        
        .chauffeur-header {
            display: flex;
            align-items: center;
            gap: 1.2rem;
            margin-bottom: 1.2rem;
        }
        
        .chauffeur-avatar-container {
            position: relative;
        }
        
        .chauffeur-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid var(--orange);
            box-shadow: 0 5px 15px rgba(232,130,12,0.3);
        }
        
        .chauffeur-avatar-placeholder {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(135deg, #2a2a2a, #1a1a1a);
            border: 3px solid var(--orange);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.5rem;
            box-shadow: 0 5px 15px rgba(232,130,12,0.3);
        }
        
        .chauffeur-status {
            position: absolute;
            bottom: 5px;
            right: 5px;
            width: 15px;
            height: 15px;
            background: #4caf50;
            border-radius: 50%;
            border: 2px solid var(--dark);
        }
        
        .chauffeur-name-title h3 {
            font-family: 'Cormorant Garamond', serif;
            font-size: 1.4rem;
            font-weight: 700;
            margin: 0 0 0.3rem 0;
            color: var(--light);
        }
        
        .chauffeur-rating {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .stars {
            color: var(--orange);
            font-size: 1rem;
            letter-spacing: 2px;
        }
        
        .rating-count {
            color: var(--light2);
            font-size: 0.75rem;
            background: rgba(255,255,255,0.1);
            padding: 0.2rem 0.5rem;
            border-radius: 20px;
        }
        
        .chauffeur-badges {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
            margin: 1rem 0;
        }
        
        .badge {
            display: inline-flex;
            align-items: center;
            gap: 0.3rem;
            font-size: 0.7rem;
            font-weight: 600;
            padding: 0.3rem 0.8rem;
            border-radius: 30px;
            background: rgba(255,255,255,0.05);
            border: 1px solid rgba(255,255,255,0.1);
            color: var(--light2);
        }
        
        .badge i {
            color: var(--orange);
            font-size: 0.8rem;
        }
        
        .badge.orange {
            background: rgba(232,130,12,0.15);
            border-color: rgba(232,130,12,0.3);
            color: var(--orange);
        }
        
        .chauffeur-bio {
            font-size: 0.8rem;
            color: var(--light2);
            line-height: 1.6;
            margin: 1rem 0;
            padding: 0.8rem;
            background: rgba(0,0,0,0.3);
            border-radius: 10px;
            border-left: 3px solid var(--orange);
            font-style: italic;
        }
        
        .chauffeur-meta {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.8rem;
            margin-top: 1rem;
        }
        
        .meta-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.75rem;
            color: var(--light2);
        }
        
        .meta-item .emoji {
            font-size: 1rem;
            background: rgba(232,130,12,0.1);
            width: 25px;
            height: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
        }
        
        .chauffeur-selector {
            position: absolute;
            top: 1rem;
            right: 1rem;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            border: 2px solid rgba(255,255,255,0.2);
            background: rgba(0,0,0,0.5);
            transition: all 0.2s ease;
        }
        
        .chauffeur-card.selected .chauffeur-selector {
            background: var(--orange);
            border-color: var(--orange);
        }
        
        .chauffeur-card.selected .chauffeur-selector::after {
            content: '✓';
            color: var(--dark);
            font-size: 0.8rem;
            font-weight: 700;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        
        .chauffeur-card input[type="radio"] {
            position: absolute;
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .chauffeur-card label {
            cursor: pointer;
            display: block;
            width: 100%;
        }
        
        .chauffeur-phone {
            font-size: 0.8rem;
            color: var(--orange);
            font-weight: 600;
        }
        
        .trip-summary {
            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.2rem 1.5rem;
            margin-bottom: 2rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .trip-info {
            display: flex;
            align-items: center;
            gap: 1rem;
            flex-wrap: wrap;
        }
        
        .trip-date {
            background: rgba(232,130,12,0.15);
            padding: 0.5rem 1rem;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .trip-address {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--light2);
            font-size: 0.85rem;
        }
        
        .trip-arrow {
            color: var(--orange);
            font-size: 1rem;
        }
        
        .chauffeur-section-title {
            font-family: 'Cormorant Garamond', serif;
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: var(--light);
        }
        
        .chauffeur-section-subtitle {
            color: var(--light2);
            font-size: 0.9rem;
            margin-bottom: 1.5rem;
            font-weight: 300;
        }
    </style>
</head>
<body>
<?php include 'header.php'; ?>
<main class="container">
  <a href="dashboard.php" class="back-link">← Retour aux véhicules</a>

  <!-- Étapes -->
  <div class="booking-steps">
    <div class="step-item <?= $step>=1?'active':'' ?>">
      <div class="step-num">1</div><span class="step-label">Date & Adresses</span>
    </div>
    <div class="step-line"></div>
    <div class="step-item <?= $step>=2?'active':'' ?>">
      <div class="step-num">2</div><span class="step-label">Chauffeur</span>
    </div>
    <div class="step-line"></div>
    <div class="step-item">
      <div class="step-num">3</div><span class="step-label">Confirmation</span>
    </div>
  </div>

  <!-- Véhicule choisi -->
  <div class="booking-car-info">
    <img class="booking-car-img" src="images/<?= sanitize($car['image']) ?>" alt="<?= sanitize($car['name']) ?>">
    <div>
      <span class="car-badge"><?= $info['badge'] ?></span>
      <h2><?= sanitize($car['name']) ?></h2>
      <div class="car-specs" style="margin-top:.5rem;">
        <?php foreach ($info['specs'] as $s): ?>
        <span class="car-spec"><?= $s ?></span>
        <?php endforeach; ?>
        <span class="car-spec" style="color:var(--orange);border-color:rgba(232,130,12,.3);">💰 <?= $info['price'] ?></span>
      </div>
    </div>
  </div>

  <?php if ($step == 1): ?>
  <!-- ── ÉTAPE 1 : date / heure / adresses centrée ── -->
  <div class="form booking-form-center">
    <h2 style="font-family:'Cormorant Garamond',serif;font-size:1.6rem;margin-bottom:1.5rem;">Détails du trajet</h2>
    <form method="post">
      <?= csrf_field() ?>
      <input type="hidden" name="step" value="2">
      <input type="hidden" name="car_id" value="<?= $carId ?>">
      <div class="form-row">
        <div class="form-group">
          <label for="date">Date de réservation</label>
          <input type="date" id="date" name="date" min="<?= date('Y-m-d') ?>" required
                 value="<?= isset($_POST['date'])?sanitize($_POST['date']):'' ?>">
        </div>
        <div class="form-group">
          <label for="time">Heure</label>
          <input type="time" id="time" name="time" required
                 value="<?= isset($_POST['time'])?sanitize($_POST['time']):'' ?>">
        </div>
      </div>
      <div class="form-group">
        <label for="pickup">Adresse de prise en charge *</label>
        <input type="text" id="pickup" name="pickup_address" placeholder="Ex : 12 rue de la Paix, Paris 75001" required
               value="<?= isset($_POST['pickup_address'])?sanitize($_POST['pickup_address']):'' ?>">
      </div>
      <div class="form-group">
        <label for="dropoff">Adresse de destination *</label>
        <input type="text" id="dropoff" name="dropoff_address" placeholder="Ex : Aéroport CDG, Terminal 2" required
               value="<?= isset($_POST['dropoff_address'])?sanitize($_POST['dropoff_address']):'' ?>">
      </div>
      <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;">
        Voir les chauffeurs disponibles →
      </button>
    </form>
  </div>

  <?php elseif ($step == 2): ?>
  <!-- ── ÉTAPE 2 : choix du chauffeur ── -->
  <?php
  $date           = $_POST['date'] ?? '';
  $time           = $_POST['time'] ?? '';
  $pickupAddress  = trim($_POST['pickup_address'] ?? '');
  $dropoffAddress = trim($_POST['dropoff_address'] ?? '');

  // Vérification des données
  if (empty($date) || empty($time) || empty($pickupAddress) || empty($dropoffAddress)) {
      echo '<div class="alert error">Données manquantes. Veuillez recommencer.</div>';
      echo '<a href="book.php?car_id='.$carId.'" class="btn btn-outline">← Retour</a>';
  } elseif (strtotime($date) < strtotime(date('Y-m-d'))) {
      echo '<div class="alert error">La date choisie est dans le passé.</div>';
      echo '<a href="book.php?car_id='.$carId.'" class="btn btn-outline">← Modifier</a>';
  } else {
      $availableChauffeurs = getAvailableChauffeurs($pdo, $date, $time);

      if (empty($availableChauffeurs)):
  ?>
    <div class="alert warning">
      <strong>Aucun chauffeur disponible</strong> le <?= date('d/m/Y', strtotime($date)) ?> à <?= $time ?>.<br>
      Veuillez essayer un autre créneau.
    </div>
    <a href="book.php?car_id=<?= $carId ?>" class="btn btn-outline" style="margin-top:1rem;">← Choisir un autre créneau</a>
  <?php else: ?>
  
    <!-- Résumé du trajet -->
    <div class="trip-summary">
      <div class="trip-info">
        <div class="trip-date">
          📅 <?= date('d/m/Y', strtotime($date)) ?> à <?= $time ?>
        </div>
        <div class="trip-address">
          <span><?= sanitize(substr($pickupAddress, 0, 25)) ?><?= strlen($pickupAddress) > 25 ? '...' : '' ?></span>
          <span class="trip-arrow">→</span>
          <span><?= sanitize(substr($dropoffAddress, 0, 25)) ?><?= strlen($dropoffAddress) > 25 ? '...' : '' ?></span>
        </div>
      </div>
      <div class="trip-price">
        <span style="color:var(--orange);font-weight:700;"><?= $info['price'] ?></span>
      </div>
    </div>

    <h2 class="chauffeur-section-title">Choisissez votre chauffeur</h2>
    <p class="chauffeur-section-subtitle">Nos chauffeurs professionnels sont disponibles pour ce créneau</p>

    <form method="post" action="confirm_booking.php" id="chauffeurForm">
      <?= csrf_field() ?>
      <input type="hidden" name="car_id"         value="<?= $carId ?>">
      <input type="hidden" name="date"            value="<?= sanitize($date) ?>">
      <input type="hidden" name="time"            value="<?= sanitize($time) ?>">
      <input type="hidden" name="pickup_address"  value="<?= sanitize($pickupAddress) ?>">
      <input type="hidden" name="dropoff_address" value="<?= sanitize($dropoffAddress) ?>">

      <div class="chauffeur-grid">
        <?php foreach ($availableChauffeurs as $index => $ch): 
            // Définir des valeurs par défaut si les nouvelles colonnes n'existent pas encore
            $experience = $ch['experience_years'] ?? rand(3, 12);
            $languages = $ch['languages'] ?? 'Français, Anglais';
            $bio = $ch['bio'] ?? 'Chauffeur professionnel avec plusieurs années d\'expérience. Ponctuel, discret et courtois. Spécialiste des trajets urbains et longue distance.';
            $vehicleType = $ch['vehicle_type'] ?? 'Véhicule adapté';
            
            // Note du chauffeur
            $rating = $chauffeurRatings[$ch['id']]['avg'] ?? 4.5;
            $ratingCount = $chauffeurRatings[$ch['id']]['count'] ?? rand(12, 48);
            
            // Déterminer si c'est le premier pour le sélectionner par défaut
            $isChecked = ($index === 0);
        ?>
        <div class="chauffeur-card <?= $isChecked ? 'selected' : '' ?>">
          <input type="radio" name="chauffeur_id" value="<?= $ch['id'] ?>" id="ch_<?= $ch['id'] ?>" <?= $isChecked ? 'checked' : '' ?> required>
          <label for="ch_<?= $ch['id'] ?>">
            <div class="chauffeur-selector"></div>
            
            <div class="chauffeur-header">
              <div class="chauffeur-avatar-container">
                <?php if (!empty($ch['photo'])): ?>
                  <img src="images/<?= sanitize($ch['photo']) ?>" alt="<?= sanitize($ch['name']) ?>" class="chauffeur-avatar">
                <?php else: ?>
                  <div class="chauffeur-avatar-placeholder">🎩</div>
                <?php endif; ?>
                <div class="chauffeur-status"></div>
              </div>
              
              <div class="chauffeur-name-title">
                <h3><?= sanitize($ch['name']) ?></h3>
                <div class="chauffeur-rating">
                  <span class="stars"><?= str_repeat('★', floor($rating)) ?><?= ($rating - floor($rating)) >= 0.5 ? '½' : '' ?></span>
                  <span class="rating-count">(<?= $ratingCount ?> avis)</span>
                </div>
              </div>
            </div>
            
            <div class="chauffeur-badges">
              <span class="badge orange"><i>⭐</i> <?= $experience ?> ans exp.</span>
              <span class="badge"><i>🗣️</i> <?= explode(',', $languages)[0] ?> +<?= substr_count($languages, ',') ?></span>
              <span class="badge"><i>🚗</i> <?= explode(' ', $vehicleType)[0] ?></span>
            </div>
            
            <div class="chauffeur-bio">
              "<?= sanitize(substr($bio, 0, 100)) ?><?= strlen($bio) > 100 ? '...' : '' ?>"
            </div>
            
            <div class="chauffeur-meta">
              <div class="meta-item">
                <span class="emoji">📞</span>
                <span><?= sanitize($ch['phone'] ?: '06 XX XX XX XX') ?></span>
              </div>
              <div class="meta-item">
                <span class="emoji">🎯</span>
                <span>97% ponctualité</span>
              </div>
              <div class="meta-item">
                <span class="emoji">📍</span>
                <span>Région parisienne</span>
              </div>
              <div class="meta-item">
                <span class="emoji">✨</span>
                <span>Premium</span>
              </div>
            </div>
          </label>
        </div>
        <?php endforeach; ?>
      </div>
      
      <div style="display:flex;gap:1rem;margin-top:2rem;justify-content:center;">
        <a href="book.php?car_id=<?= $carId ?>" class="btn btn-outline" style="min-width:150px;">← Modifier le trajet</a>
        <button type="submit" class="btn btn-primary" style="min-width:200px;justify-content:center;">Confirmer la réservation ✓</button>
      </div>
    </form>
    
    <script>
    // Script pour la sélection visuelle des chauffeurs
    document.querySelectorAll('.chauffeur-card').forEach(card => {
        const radio = card.querySelector('input[type="radio"]');
        if (radio) {
            card.addEventListener('click', () => {
                // Désélectionner toutes les cartes
                document.querySelectorAll('.chauffeur-card').forEach(c => c.classList.remove('selected'));
                // Sélectionner la carte cliquée
                card.classList.add('selected');
                // Cocher le radio
                radio.checked = true;
            });
            
            // Si déjà coché, s'assurer que la classe selected est présente
            if (radio.checked) {
                card.classList.add('selected');
            }
        }
    });
    </script>
    
  <?php 
      endif; 
  } 
  ?>
  <?php endif; ?>
</main>
<?php include 'footer.php'; ?>
</body>
</html>