<?php
require_once 'session.php';
require_once 'db.php';

if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
    header('Location: panel.php');
    exit;
}

$erreur = "";
$succes = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $prenom = trim($_POST['prenom']);
    $username = trim($_POST['username']);
    $date_naissance = $_POST['date_naissance'];
    $email = trim($_POST['email']);
    $email_confirm = trim($_POST['email_confirm']);
    $password = $_POST['password'];
    $password_confirm = $_POST['password_confirm'];

    if (empty($prenom) || empty($username) || empty($date_naissance) || empty($email) || empty($password)) {
        $erreur = "Tous les champs obligatoires doivent être remplis.";
    } elseif ($email !== $email_confirm) {
        $erreur = "Les deux adresses email ne correspondent pas.";
    } elseif ($password !== $password_confirm) {
        $erreur = "Les deux mots de passe ne correspondent pas.";
    } elseif (strlen($password) < 8) {
        $erreur = "Le mot de passe doit contenir au moins 8 caractères.";
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id FROM utilisateurs WHERE username = :username");
            $stmt->execute(['username' => $username]);
            if ($stmt->fetch()) {
                $erreur = "Ce nom d'utilisateur est déjà pris.";
            }

            if (empty($erreur)) {
                $stmt = $pdo->prepare("SELECT id FROM utilisateurs WHERE email = :email");
                $stmt->execute(['email' => $email]);
                if ($stmt->fetch()) {
                    $erreur = "Cette adresse email est déjà associée à un compte.";
                }
            }

            if (empty($erreur)) {
                $passwordHash = password_hash($password, PASSWORD_BCRYPT);
                $insert = $pdo->prepare("INSERT INTO utilisateurs (prenom, username, email, password, date_naissance) VALUES (:prenom, :username, :email, :password, :date_naissance)");
                $insert->execute([
                    'prenom' => $prenom,
                    'username' => $username,
                    'email' => $email,
                    'password' => $passwordHash,
                    'date_naissance' => $date_naissance
                ]);

                $succes = "Votre compte a été créé avec succès ! <a href='login.php'>Connectez-vous ici</a>.";
            }

        } catch (PDOException $e) {
            $erreur = "Une erreur technique est survenue.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inscription | ParcoTrip</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/auth.css">
</head>
<body>

    <div class="auth-container">
        <div class="auth-form-side">
            <div class="auth-header">
                <div class="logo"><a href="index.php">PARCO<span>TRIP</span></a></div>
                <h1>Créer un profil</h1>
                <p>Rejoignez-nous pour suivre l'évolution des files d'attente en temps réel.</p>
            </div>

            <?php if (!empty($erreur)): ?>
                <div class="auth-alert alert-danger"><i class="fa-solid fa-triangle-exclamation"></i> <?php echo $erreur; ?></div>
            <?php endif; ?>
            <?php if (!empty($succes)): ?>
                <div class="auth-alert alert-success"><i class="fa-solid fa-circle-check"></i> <?php echo $succes; ?></div>
            <?php endif; ?>

            <form action="register.php" method="POST" class="auth-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="prenom">Prénom</label>
                        <input type="text" id="prenom" name="prenom" required placeholder="Alex" value="<?php echo isset($_POST['prenom']) ? htmlspecialchars($_POST['prenom']) : ''; ?>">
                    </div>
                    <div class="form-group">
                        <label for="username">Nom d'utilisateur</label>
                        <input type="text" id="username" name="username" required placeholder="coaster_rider" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>">
                    </div>
                </div>

                <div class="form-group">
                    <label for="date_naissance">Date de naissance</label>
                    <input type="date" id="date_naissance" name="date_naissance" required value="<?php echo isset($_POST['date_naissance']) ? htmlspecialchars($_POST['date_naissance']) : ''; ?>">
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="email">Adresse Email</label>
                        <input type="email" id="email" name="email" required placeholder="nom@exemple.com" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                    </div>
                    <div class="form-group">
                        <label for="email_confirm">Répéter l'Email</label>
                        <input type="email" id="email_confirm" name="email_confirm" required placeholder="nom@exemple.com">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="password">Mot de passe (8 char. min)</label>
                        <input type="password" id="password" name="password" required placeholder="••••••••">
                    </div>
                    <div class="form-group">
                        <label for="password_confirm">Répéter le Mot de Passe</label>
                        <input type="password" id="password_confirm" name="password_confirm" required placeholder="••••••••">
                    </div>
                </div>

                <button type="submit" class="btn-auth-submit" style="margin-top: 15px;">Créer mon compte</button>
            </form>

            <div class="auth-footer">
                <p>Déjà inscrit ? <a href="login.php">Je me connecte</a></p>
                <p style="margin-top: 15px; font-size: 13px;">
                    <a href="index.php" style="color: #626262; font-weight: 600; text-decoration: none;">
                        <i class="fa-solid fa-arrow-left" style="font-size: 11px; margin-right: 5px;"></i> Retourner sur le site
                    </a>
                </p>
            </div>
        </div>

        <div class="auth-image-side" style="background-image: url('img/toutatis.jpeg');">
            <div class="image-overlay"></div>
            <div class="image-quote">
                <h2>"Le meilleur moyen de prévoir la file d'attente, c'est de posséder les bons outils."</h2>
                <p>Planifiez. Voyagez. Profitez.</p>
            </div>
        </div>
    </div>

</body>
</html>