<?php
require_once 'db/config.php';
session_start();

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'register') {
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $password_confirm = $_POST['password_confirm'] ?? '';

        if (empty($username) || empty($email) || empty($password)) {
            $error = 'Tous les champs sont obligatoires.';
        } elseif ($password !== $password_confirm) {
            $error = 'Les mots de passe ne correspondent pas.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Email invalide.';
        } else {
            $db = db();
            // Check if user exists
            $stmt = $db->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $email]);
            if ($stmt->fetch()) {
                $error = 'Ce nom d\'utilisateur ou cet email est déjà utilisé.';
            } else {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $db->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
                try {
                    $stmt->execute([$username, $email, $hashed_password]);
                    $success = 'Compte créé avec succès ! Vous pouvez maintenant vous connecter.';
                } catch (Exception $e) {
                    $error = 'Erreur lors de la création du compte.';
                }
            }
        }
    } elseif ($action === 'login') {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

        if (empty($username) || empty($password)) {
            $error = 'Tous les champs sont obligatoires.';
        } else {
            $db = db();
            $stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
            $stmt->execute([$username]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];
                
                $db->prepare("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?")->execute([$user['id']]);
                
                header('Location: index.php');
                exit;
            } else {
                $error = 'Identifiants incorrects.';
            }
        }
    }
}

if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}

$page = $_GET['page'] ?? 'login';
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page === 'register' ? 'Création de compte' : 'Connexion'; ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: #000;
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            color: #fff;
            background-image: radial-gradient(circle at 50% 50%, #1a2a4a 0%, #000 70%);
            background-attachment: fixed;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        .auth-container {
            background: rgba(10, 15, 30, 0.95);
            border: 1px solid #4c566a;
            padding: 30px;
            width: 100%;
            max-width: 400px;
            box-shadow: 0 0 20px rgba(0,0,0,0.8);
        }
        h2 { text-transform: uppercase; color: #88c0d0; border-bottom: 1px solid #4c566a; padding-bottom: 10px; margin-top: 0; text-align: center; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; color: #8c92a3; font-size: 14px; }
        input { width: 100%; padding: 10px; background: #000; border: 1px solid #4c566a; color: #fff; box-sizing: border-box; }
        button { width: 100%; padding: 12px; background: #5e81ac; border: none; color: #fff; font-weight: bold; cursor: pointer; text-transform: uppercase; margin-top: 10px; }
        button:hover { background: #81a1c1; }
        .alert { padding: 10px; margin-bottom: 15px; font-size: 14px; }
        .alert-error { background: rgba(191, 97, 106, 0.2); border: 1px solid #bf616a; color: #bf616a; }
        .alert-success { background: rgba(163, 190, 140, 0.2); border: 1px solid #a3be8c; color: #a3be8c; }
        .switch-link { text-align: center; margin-top: 15px; font-size: 13px; }
        .switch-link a { color: #88c0d0; text-decoration: none; }
        .switch-link a:hover { text-decoration: underline; }
        .back-link { display: block; text-align: center; margin-top: 20px; color: #4c566a; text-decoration: none; font-size: 12px; }
    </style>
</head>
<body>
    <div class="auth-container">
        <?php if ($page === 'register'): ?>
            <h2>Créer un compte</h2>
            <?php if ($error): ?><div class="alert alert-error"><?php echo $error; ?></div><?php endif; ?>
            <?php if ($success): ?><div class="alert alert-success"><?php echo $success; ?></div><?php endif; ?>
            <form method="POST">
                <input type="hidden" name="action" value="register">
                <div class="form-group">
                    <label>Nom d\'utilisateur</label>
                    <input type="text" name="username" required value="<?php echo htmlspecialchars($username ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" required value="<?php echo htmlspecialchars($email ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>Mot de passe</label>
                    <input type="password" name="password" required>
                </div>
                <div class="form-group">
                    <label>Confirmer le mot de passe</label>
                    <input type="password" name="password_confirm" required>
                </div>
                <button type="submit">S\'inscrire</button>
            </form>
            <div class="switch-link"> Déjà un compte ? <a href="?page=login">Se connecter</a> </div>
        <?php else: ?>
            <h2>Connexion</h2>
            <?php if ($error): ?><div class="alert alert-error"><?php echo $error; ?></div><?php endif; ?>
            <?php if ($success): ?><div class="alert alert-success"><?php echo $success; ?></div><?php endif; ?>
            <form method="POST">
                <input type="hidden" name="action" value="login">
                <div class="form-group">
                    <label>Nom d\'utilisateur</label>
                    <input type="text" name="username" required value="<?php echo htmlspecialchars($username ?? ''); ?>">
                </div>
                <div class="form-group">
                    <label>Mot de passe</label>
                    <input type="password" name="password" required>
                </div>
                <button type="submit">Entrer dans le nexus</button>
            </form>
            <div class="switch-link"> Pas encore de compte ? <a href="?page=register">Créer un compte</a> </div>
        <?php endif; ?>
        <a href="index.php" class="back-link"><i class="fa-solid fa-arrow-left"></i> Retour à la galaxie</a>
    </div>
</body>
</html>
