<?php
session_start(); 
include 'connexion.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['login'])) {
        if (isset($_POST['username']) && isset($_POST['password'])) {
            $username = $_POST['username'];
            $password = $_POST['password'];

            $stmt = $pdo->prepare("SELECT * FROM user WHERE username = :username"); 
            $stmt->execute([':username' => $username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && password_verify($password, $user['password_hash'])) {  
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];
                session_regenerate_id(true); 
                header("Location: sommaire.php");
                exit;
            } else {
                $error = "Identifiants invalides.";
            }
        } else {
            $error = "Veuillez remplir tous les champs.";
        }
    } elseif (isset($_POST['register'])) {
        if (isset($_POST['username']) && isset($_POST['password'])) {
            $username = $_POST['username'];
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // Hachage du mot de passe

            $stmt = $pdo->prepare("INSERT INTO user (username, password_hash, role) VALUES (:username, :password, 'gp')");
            $stmt->execute([':username' => $username, ':password' => $password]);

            echo "<p>Inscription réussie. Vous pouvez vous connecter.</p>";
        } else {
            $error = "Veuillez remplir tous les champs.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Connexion</title>
    <link rel="stylesheet" href="style/login.css">   

    <!-- Favicon -->
    <link rel="icon" type="image/png" href="images/sallon du jeu .png"> 

</head>
<body>
    <div class="logo-container">
        <img src="images/sallon du jeu.png" alt="Logo du site" class="logo"> 
    </div>

    <h1>Connexion</h1>

    <form method="post" action="">
        <label for="username">Nom d'utilisateur :</label>
        <input type="text" name="username" required>
        
        <label for="password">Mot de passe :</label>
        <input type="password" name="password" required>
        
        <button type="submit" name="login">Se connecter</button>
    </form>

    <h2>Inscription (Grand Public uniquement)</h2>

    <form method="post" action="">
        <label for="username">Nom d'utilisateur :</label>
        <input type="text" name="username" required>
        
        <label for="password">Mot de passe :</label>
        <input type="password" name="password" required>
        
        <button type="submit" name="register">S'inscrire</button>
    </form>

    <?php if (isset($error)): ?>
        <p class="error"><?= htmlspecialchars($error) ?></p>
    <?php endif; ?>
</body>
</html>