<?php

declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db.php';

// 🎀 Active la session securisee pour gerer CSRF et etat utilisateur 🎀
startSecureSession();

// 🎀 Si l'utilisateur est deja connecte, on le renvoie a l'accueil 🎀
if (isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

$error = '';

// 🎀 Traite l'inscription uniquement lors d'un envoi du formulaire 🎀
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 🎀 Bloque les requetes sans token CSRF valide 🎀
    if (!verifyCsrfToken($_POST['csrf_token'] ?? null)) {
        $error = 'Session invalide. Recharge la page et reessaie.';
    }

    $name = trim((string)($_POST['name'] ?? ''));
    $email = strtolower(trim((string)($_POST['email'] ?? '')));
    $password = (string)($_POST['password'] ?? '');
    $confirmPassword = (string)($_POST['confirm_password'] ?? '');

    if ($error === '' && ($name === '' || $email === '' || $password === '' || $confirmPassword === '')) {
        $error = 'Merci de remplir tous les champs.';
    } elseif ($error === '' && (strlen($name) < 2 || strlen($name) > 100)) {
        $error = 'Le nom doit contenir entre 2 et 100 caracteres.';
    } elseif ($error === '' && (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > 190)) {
        $error = 'Adresse e-mail invalide.';
    } elseif ($error === '' && strlen($password) < 6) {
        $error = 'Le mot de passe doit contenir au moins 6 caracteres.';
    } elseif ($error === '' && $password !== $confirmPassword) {
        $error = 'Les mots de passe ne correspondent pas.';
    } elseif ($error === '') {
        try {
            $pdo = getPdo();

            // 🎀 Verifie qu'aucun compte n'existe deja avec cet e-mail 🎀
            $checkStmt = $pdo->prepare('SELECT id FROM users WHERE email = :email LIMIT 1');
            $checkStmt->execute(['email' => $email]);

            if ($checkStmt->fetch()) {
                $error = 'Ce compte existe deja. Connecte-toi.';
            } else {
                // 🎀 Le mot de passe est hache avant insertion en base 🎀
                $hash = password_hash($password, PASSWORD_DEFAULT);

                $insertStmt = $pdo->prepare('INSERT INTO users (name, email, password_hash) VALUES (:name, :email, :password_hash)');
                $insertStmt->execute([
                    'name' => $name,
                    'email' => $email,
                    'password_hash' => $hash,
                ]);

                header('Location: login.php?created=1');
                exit;
            }
        } catch (Throwable $e) {
            $error = 'Impossible de creer le compte: verifie que MySQL MAMP est lance.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inscription | MindGallery</title>
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/login.css">
</head>
<body>
    <main class="auth-layout">
        <h1>Creer un compte</h1>

        <?php if ($error !== ''): ?>
            <p class="auth-message auth-error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p>
        <?php endif; ?>

        <form class="auth-form" action="register.php" method="post">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrfToken(), ENT_QUOTES, 'UTF-8') ?>">
            <label for="name">Nom</label>
            <input id="name" name="name" type="text" placeholder="Ton nom" required>

            <label for="email">Adresse e-mail</label>
            <input id="email" name="email" type="email" placeholder="exemple@mail.com" required>

            <label for="password">Mot de passe</label>
            <input id="password" name="password" type="password" placeholder="Minimum 6 caracteres" required>

            <label for="confirm_password">Confirmer le mot de passe</label>
            <input id="confirm_password" name="confirm_password" type="password" placeholder="Retape ton mot de passe" required>

            <button type="submit">Creer le compte</button>
        </form>

        <p class="auth-text">Tu as deja un compte ? <a href="login.php">Se connecter</a></p>
        <a class="auth-back" href="index.php">Retour a l'accueil</a>
    </main>
</body>
</html>
