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

$action = $_GET['action'] ?? '';
$id     = (int)($_GET['id'] ?? 0);
$errors = [];
$editCar = null;

if ($action === 'toggle' && $id) {
    $pdo->prepare("UPDATE cars SET active = 1-active WHERE id=?")->execute([$id]);
    redirect('cars.php');
}
if ($action === 'edit' && $id) {
    $editCar = $pdo->prepare("SELECT * FROM cars WHERE id=?");
    $editCar->execute([$id]);
    $editCar = $editCar->fetch();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $name     = trim($_POST['name'] ?? '');
    $desc     = trim($_POST['description'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $seats    = (int)($_POST['seats'] ?? 4);
    $price    = (float)($_POST['price_km'] ?? 0);
    $editId   = (int)($_POST['edit_id'] ?? 0);

    if (empty($name))  $errors[] = "Le nom est requis.";
    if ($price <= 0)   $errors[] = "Le tarif doit être positif.";

    if (empty($errors)) {
        if ($editId) {
            $pdo->prepare("UPDATE cars SET name=?,description=?,category=?,seats=?,price_km=? WHERE id=?")
                ->execute([$name,$desc,$category,$seats,$price,$editId]);
        } else {
            $pdo->prepare("INSERT INTO cars (name,description,category,seats,price_km) VALUES (?,?,?,?,?)")
                ->execute([$name,$desc,$category,$seats,$price]);
        }
        redirect('cars.php');
    }
}

$cars = $pdo->query("SELECT * FROM cars ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Véhicules – 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;}
      .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;}
      .admin-two-col{display:grid;grid-template-columns:1fr 380px;gap:2rem;align-items:start;}
      @media(max-width:900px){.admin-two-col{grid-template-columns:1fr;}}
    </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">📅 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" class="active">🚗 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">
    <h1 style="font-family:'Cormorant Garamond',serif;font-size:2rem;margin-bottom:1.5rem;">Véhicules</h1>
    <div class="admin-two-col">
      <div class="reservations-table-wrapper">
        <table class="reservations-table">
          <thead><tr><th>Nom</th><th>Catégorie</th><th>Places</th><th>Tarif/km</th><th>Statut</th><th>Actions</th></tr></thead>
          <tbody>
            <?php foreach ($cars as $c): ?>
            <tr>
              <td><strong><?= sanitize($c['name']) ?></strong></td>
              <td><?= sanitize($c['category']) ?></td>
              <td><?= $c['seats'] ?></td>
              <td><?= number_format($c['price_km'],2,',','.') ?> €</td>
              <td><span class="status <?= $c['active']?'confirmée':'annulée' ?>"><?= $c['active']?'Actif':'Inactif' ?></span></td>
              <td>
                <div class="td-actions">
                  <a href="cars.php?action=edit&id=<?= $c['id'] ?>" class="btn small btn-ghost">Modifier</a>
                  <a href="cars.php?action=toggle&id=<?= $c['id'] ?>" class="btn small btn-ghost"><?= $c['active']?'Désactiver':'Activer' ?></a>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="form" style="margin:0;">
        <h3 style="font-family:'Cormorant Garamond',serif;font-size:1.3rem;margin-bottom:1.2rem;">
          <?= $editCar ? 'Modifier le véhicule' : 'Ajouter un véhicule' ?>
        </h3>
        <?php if (!empty($errors)): ?>
        <div class="alert error"><?php foreach($errors as $e): ?><p><?= sanitize($e) ?></p><?php endforeach; ?></div>
        <?php endif; ?>
        <form method="post">
          <?= csrf_field() ?>
          <input type="hidden" name="edit_id" value="<?= $editCar?$editCar['id']:0 ?>">
          <div class="form-group"><label>Nom *</label>
            <input type="text" name="name" required value="<?= sanitize($editCar['name']??'') ?>"></div>
          <div class="form-group"><label>Description</label>
            <textarea name="description" style="min-height:80px;resize:vertical;"><?= sanitize($editCar['description']??'') ?></textarea></div>
          <div class="form-row">
            <div class="form-group"><label>Catégorie</label>
              <input type="text" name="category" value="<?= sanitize($editCar['category']??'Berline') ?>"></div>
            <div class="form-group"><label>Places</label>
              <input type="number" name="seats" min="1" max="20" value="<?= $editCar['seats']??4 ?>"></div>
          </div>
          <div class="form-group"><label>Tarif (€/km) *</label>
            <input type="number" name="price_km" step="0.01" min="0.01" value="<?= $editCar['price_km']??2.50 ?>" required></div>
          <div style="display:flex;gap:.8rem;">
            <?php if ($editCar): ?><a href="cars.php" class="btn btn-ghost" style="flex:1;justify-content:center;">Annuler</a><?php endif; ?>
            <button type="submit" class="btn btn-primary" style="flex:2;justify-content:center;"><?= $editCar?'Mettre à jour':'Ajouter' ?></button>
          </div>
        </form>
      </div>
    </div>
  </main>
</div>
</body>
</html>
