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

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

$stmt = $pdo->prepare("SELECT r.*, c.name as car_name, ch.name as chauffeur_name
                        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([$id, $_SESSION['user_id']]);
$res = $stmt->fetch();
if (!$res) redirect('my_reservations.php');

// Vérifier qu'il n'y a pas déjà une note
$existing = $pdo->prepare("SELECT id FROM ratings WHERE reservation_id = ?");
$existing->execute([$id]);
if ($existing->fetch()) {
    $_SESSION['error'] = "Vous avez déjà noté cette réservation.";
    redirect('my_reservations.php');
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $stars   = (int)($_POST['stars'] ?? 0);
    $comment = trim($_POST['comment'] ?? '');

    if ($stars < 1 || $stars > 5) {
        $error = "Veuillez sélectionner une note entre 1 et 5 étoiles.";
    } else {
        $pdo->prepare("INSERT INTO ratings (reservation_id, user_id, stars, comment) VALUES (?, ?, ?, ?)")
            ->execute([$id, $_SESSION['user_id'], $stars, $comment ?: null]);
        $_SESSION['flash'] = "Merci pour votre avis !";
        redirect('my_reservations.php');
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Noter votre trajet - First Car</title>
    <link rel="stylesheet" href="style.css">
    <style>
      .stars-input { display:flex; gap:.5rem; flex-direction:row-reverse; justify-content:flex-end; margin:.8rem 0; }
      .stars-input input { display:none; }
      .stars-input label {
        font-size:2.5rem; cursor:pointer; color:rgba(255,255,255,.15);
        transition:color .15s, transform .15s;
      }
      .stars-input label:hover,
      .stars-input label:hover ~ label,
      .stars-input input:checked ~ label { color:var(--orange); }
      .stars-input label:hover { transform:scale(1.15); }
    </style>
</head>
<body>
<?php include 'header.php'; ?>
<main class="container">
  <a href="my_reservations.php" class="back-link">← Retour à mes réservations</a>
  <div class="form-wrapper" style="max-width:560px;margin:0;">
    <div style="margin-bottom:2rem;">
      <h1 class="page-title">Noter votre trajet</h1>
      <div style="background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:10px;padding:1rem 1.5rem;">
        <p style="font-size:.85rem;color:var(--light2);">
          🚗 <strong style="color:var(--light)"><?= sanitize($res['car_name']) ?></strong>
          &nbsp;·&nbsp; 👤 <?= sanitize($res['chauffeur_name']) ?>
          &nbsp;·&nbsp; 📅 <?= date('d/m/Y', strtotime($res['reservation_date'])) ?>
        </p>
      </div>
    </div>

    <?php if ($error): ?>
    <div class="alert error"><?= sanitize($error) ?></div>
    <?php endif; ?>

    <div class="form">
      <form method="post">
        <?= csrf_field() ?>
        <div class="form-group">
          <label>Votre note *</label>
          <div class="stars-input">
            <?php for ($i=5; $i>=1; $i--): ?>
            <input type="radio" id="star<?= $i ?>" name="stars" value="<?= $i ?>" <?= (($_POST['stars']??0)==$i)?'checked':'' ?>>
            <label for="star<?= $i ?>" title="<?= $i ?> étoile<?= $i>1?'s':'' ?>">★</label>
            <?php endfor; ?>
          </div>
        </div>
        <div class="form-group">
          <label for="comment">Commentaire <span style="font-weight:300;text-transform:none;">(facultatif)</span></label>
          <textarea id="comment" name="comment" placeholder="Partagez votre expérience..." style="resize:vertical;min-height:110px;"><?= sanitize($_POST['comment'] ?? '') ?></textarea>
        </div>
        <div style="display:flex;gap:1rem;">
          <a href="my_reservations.php" class="btn btn-ghost">Annuler</a>
          <button type="submit" class="btn btn-primary" style="flex:1;justify-content:center;">Envoyer mon avis ⭐</button>
        </div>
      </form>
    </div>
  </div>
</main>
<?php include 'footer.php'; ?>
</body>
</html>
