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

$userId = (int)$_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

$errors  = [];
$success = false;
$tab     = $_GET['tab'] ?? 'info';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $tab = $_POST['tab'] ?? 'info';

    if ($tab === 'info') {
        $name  = trim($_POST['name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');

        if (empty($name)) $errors[] = "Le nom ne peut pas être vide.";
        if (empty($errors)) {
            $pdo->prepare("UPDATE users SET name=?, phone=? WHERE id=?")
                ->execute([$name, $phone ?: null, $userId]);
            $_SESSION['user_name'] = $name;
            $user['name']  = $name;
            $user['phone'] = $phone;
            $success = "Informations mises à jour avec succès.";
        }

    } elseif ($tab === 'password') {
        $current = $_POST['current_password'] ?? '';
        $new     = $_POST['new_password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? '';

        if (!verifyPassword($pdo, $user, $current)) $errors[] = "Mot de passe actuel incorrect.";
        elseif (strlen($new) < 8)                   $errors[] = "Le nouveau mot de passe doit faire au moins 8 caractères.";
        elseif ($new !== $confirm)                   $errors[] = "Les mots de passe ne correspondent pas.";

        if (empty($errors)) {
            $hash = password_hash($new, PASSWORD_BCRYPT, ['cost' => 12]);
            $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([$hash, $userId]);
            // Re-fetch user après update
            $stmt2 = $pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt2->execute([$userId]);
            $user = $stmt2->fetch();
            $success = "Mot de passe mis à jour avec succès.";
        }
    }
}

// Stats
$statsStmt = $pdo->prepare("SELECT
    COUNT(*) as total,
    SUM(CASE WHEN status='confirmée' THEN 1 ELSE 0 END) as actives,
    SUM(CASE WHEN status='annulée'   THEN 1 ELSE 0 END) as annulees,
    SUM(CASE WHEN status='terminée'  THEN 1 ELSE 0 END) as terminees
    FROM reservations WHERE user_id=?");
$statsStmt->execute([$userId]);
$stats = $statsStmt->fetch();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mon profil - First Car</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php include 'header.php'; ?>
<main class="container">

  <h1 class="page-title">Mon profil</h1>

  <!-- Stats centrées -->
  <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:1rem;max-width:700px;margin:0 auto 2.5rem auto;">
    <div style="background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);border-radius:12px;padding:1.2rem;text-align:center;">
      <div style="font-family:'Cormorant Garamond',serif;font-size:2.2rem;font-weight:700;color:var(--orange);"><?= (int)$stats['total'] ?></div>
      <div style="font-size:.7rem;text-transform:uppercase;letter-spacing:.1em;color:var(--light2);margin-top:.3rem;">Total</div>
    </div>
    <div style="background:rgba(76,175,80,.06);border:1px solid rgba(76,175,80,.2);border-radius:12px;padding:1.2rem;text-align:center;">
      <div style="font-family:'Cormorant Garamond',serif;font-size:2.2rem;font-weight:700;color:#4caf50;"><?= (int)$stats['actives'] ?></div>
      <div style="font-size:.7rem;text-transform:uppercase;letter-spacing:.1em;color:var(--light2);margin-top:.3rem;">Confirmées</div>
    </div>
    <div style="background:rgba(232,130,12,.06);border:1px solid rgba(232,130,12,.2);border-radius:12px;padding:1.2rem;text-align:center;">
      <div style="font-family:'Cormorant Garamond',serif;font-size:2.2rem;font-weight:700;color:var(--orange);"><?= (int)$stats['terminees'] ?></div>
      <div style="font-size:.7rem;text-transform:uppercase;letter-spacing:.1em;color:var(--light2);margin-top:.3rem;">Terminées</div>
    </div>
    <div style="background:rgba(244,67,54,.06);border:1px solid rgba(244,67,54,.2);border-radius:12px;padding:1.2rem;text-align:center;">
      <div style="font-family:'Cormorant Garamond',serif;font-size:2.2rem;font-weight:700;color:#f44336;"><?= (int)$stats['annulees'] ?></div>
      <div style="font-size:.7rem;text-transform:uppercase;letter-spacing:.1em;color:var(--light2);margin-top:.3rem;">Annulées</div>
    </div>
  </div>

  <!-- Tabs centrés -->
  <div style="max-width:560px;margin:0 auto;">
    <div style="display:flex;gap:.5rem;margin-bottom:1.5rem;border-bottom:1px solid rgba(255,255,255,.08);padding-bottom:0;">
      <?php foreach (['info' => 'Mes informations', 'password' => 'Changer le mot de passe'] as $t => $label): ?>
      <a href="profile.php?tab=<?= $t ?>"
         style="padding:.7rem 1.4rem;font-size:.78rem;font-weight:700;letter-spacing:.07em;text-transform:uppercase;text-decoration:none;border-bottom:2px solid transparent;margin-bottom:-1px;transition:all .2s;
                <?= $tab === $t ? 'color:var(--orange);border-bottom-color:var(--orange);' : 'color:var(--light2);' ?>">
        <?= $label ?>
      </a>
      <?php endforeach; ?>
    </div>

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

    <!-- Formulaire -->
    <div class="form" style="margin:0;">
      <?php if ($tab === 'info'): ?>
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="tab" value="info">
        <div class="form-group">
          <label>Nom complet *</label>
          <input type="text" name="name" required value="<?= sanitize($user['name']) ?>">
        </div>
        <div class="form-group">
          <label>Email <span style="font-weight:300;text-transform:none;font-size:.85em;">(non modifiable)</span></label>
          <input type="email" value="<?= sanitize($user['email']) ?>" disabled
                 style="opacity:.45;cursor:not-allowed;background:rgba(255,255,255,.03);">
        </div>
        <div class="form-group">
          <label>Téléphone <span style="font-weight:300;text-transform:none;font-size:.85em;">(facultatif)</span></label>
          <input type="tel" name="phone" placeholder="06 XX XX XX XX"
                 value="<?= sanitize($user['phone'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label>Âge <span style="font-weight:300;text-transform:none;font-size:.85em;">(non modifiable)</span></label>
          <input type="number" value="<?= (int)$user['age'] ?>" disabled
                 style="opacity:.45;cursor:not-allowed;background:rgba(255,255,255,.03);">
        </div>
        <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;padding:1rem;">
          Enregistrer les modifications
        </button>
      </form>

      <?php else: ?>
      <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="tab" value="password">
        <div class="form-group">
          <label>Mot de passe actuel *</label>
          <input type="password" name="current_password" required placeholder="••••••••" autocomplete="current-password">
        </div>
        <div class="form-group">
          <label>Nouveau mot de passe * <span style="font-weight:300;text-transform:none;font-size:.85em;">(min. 8 car.)</span></label>
          <input type="password" name="new_password" required placeholder="••••••••" autocomplete="new-password">
        </div>
        <div class="form-group">
          <label>Confirmer le nouveau mot de passe *</label>
          <input type="password" name="confirm_password" required placeholder="••••••••" autocomplete="new-password">
        </div>
        <button type="submit" class="btn btn-primary" style="width:100%;justify-content:center;padding:1rem;">
          Mettre à jour le mot de passe
        </button>
      </form>
      <?php endif; ?>
    </div>

    <!-- Lien retour -->
    <div style="text-align:center;margin-top:1.5rem;">
      <a href="dashboard.php" class="back-link">← Retour aux véhicules</a>
    </div>
  </div>

</main>
<?php include 'footer.php'; ?>
</body>
</html>
