<?php
require_once 'config.php';
require_once 'functions.php';

if (isLoggedIn()) redirect('dashboard.php');

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $name     = trim($_POST['name'] ?? '');
    $email    = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['confirm_password'] ?? '';
    $age      = (int)($_POST['age'] ?? 0);

    if (empty($name))                                $errors[] = "Le nom complet est requis.";
    if ($age < 18)                                   $errors[] = "Vous devez avoir au moins 18 ans.";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL))  $errors[] = "Adresse email invalide.";
    if (strlen($password) < 8)                       $errors[] = "Le mot de passe doit faire au moins 8 caractères.";
    if ($password !== $confirm)                      $errors[] = "Les mots de passe ne correspondent pas.";

    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) $errors[] = "Cet email est déjà utilisé.";
    }

    if (empty($errors)) {
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
        $stmt = $pdo->prepare("INSERT INTO users (name, email, password, age) VALUES (?, ?, ?, ?)");
        if ($stmt->execute([$name, $email, $hash, $age])) {
            $_SESSION['flash'] = "Inscription réussie ! Connectez-vous pour commencer.";
            redirect('login.php');
        } else {
            $errors[] = "Erreur lors de l'inscription. Veuillez réessayer.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inscription - First Car</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php include 'header.php'; ?>
<main class="container">
  <div class="form-wrapper">
    <div style="text-align:center;margin-bottom:2rem;">
      <h1 style="font-family:'Cormorant Garamond',serif;font-size:2.5rem;font-weight:700;">Créer un compte</h1>
      <p style="color:var(--light2);font-size:.88rem;margin-top:.5rem;font-weight:300;">Rejoignez First Car et profitez d'un service de transport premium.</p>
    </div>

    <?php if (!empty($errors)): ?>
    <div class="alert error">
      <?php foreach ($errors as $e): ?><p>⚠ <?= sanitize($e) ?></p><?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="form">
      <form method="post" novalidate>
        <?= csrf_field() ?>
        <div class="form-group">
          <label for="name">Nom complet *</label>
          <input type="text" id="name" name="name" placeholder="Jean Dupont" required
                 value="<?= isset($_POST['name']) ? sanitize($_POST['name']) : '' ?>">
        </div>
        <div class="form-row">
          <div class="form-group">
            <label for="email">Email *</label>
            <input type="email" id="email" name="email" placeholder="vous@exemple.com" required
                   value="<?= isset($_POST['email']) ? sanitize($_POST['email']) : '' ?>">
          </div>
          <div class="form-group">
            <label for="age">Âge *</label>
            <input type="number" id="age" name="age" min="18" max="120" placeholder="18+" required
                   value="<?= isset($_POST['age']) ? (int)$_POST['age'] : '' ?>">
          </div>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label for="password">Mot de passe * <span style="font-weight:300;text-transform:none;">(min. 8 car.)</span></label>
            <input type="password" id="password" name="password" placeholder="••••••••" required autocomplete="new-password">
          </div>
          <div class="form-group">
            <label for="confirm_password">Confirmer *</label>
            <input type="password" id="confirm_password" name="confirm_password" placeholder="••••••••" required autocomplete="new-password">
          </div>
        </div>
        <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;padding:1rem;margin-top:.5rem;">
          Créer mon compte
        </button>
      </form>
    </div>
    <p class="text-center mt-2" style="color:var(--light2);font-size:.88rem;">
      Déjà un compte ? <a href="login.php" style="color:var(--orange);font-weight:600;">Connectez-vous</a>
    </p>
  </div>
</main>
<?php include 'footer.php'; ?>
</body>
</html>
