<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once 'config.php';

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';

    if ($username && $password) {
        $stmt = $pdo->prepare("SELECT id, username, password, role, profile_picture, bio FROM utilisateurs WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user'] = [
                'id' => (int)$user['id'],
                'username' => $user['username'],
                'role' => $user['role'],
                'profile_picture' => $user['profile_picture'],
                'bio' => $user['bio'] ?? null
            ];
            $_SESSION['user_id'] = (int)$user['id'];
            header('Location: index.php');
            exit;
        } else {
            $message = "❌ Nom d'utilisateur ou mot de passe incorrect.";
        }
    } else {
        $message = "⚠️ Veuillez remplir tous les champs.";
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Connexion</title>
<style>
body {
    font-family: 'Poppins', sans-serif;
    background: #fff4f7;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
}
.container {
    background: white;
    padding: 40px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    width: 350px;
    text-align: center;
}
input {
    width: 90%;
    padding: 10px;
    margin: 8px 0;
    border: 1px solid #ddd;
    border-radius: 8px;
}
button {
    background: linear-gradient(45deg, #ff69b4, #ffa07a);
    border: none;
    color: white;
    padding: 10px 20px;
    border-radius: 20px;
    cursor: pointer;
    font-weight: 600;
}
button:hover { opacity: 0.9; }
.message { color: red; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="container">
    <h2>Connexion</h2>
    <?php if ($message): ?><div class="message"><?= $message ?></div><?php endif; ?>
    <form method="POST" action="login.php">
        <input type="text" name="username" placeholder="Nom d'utilisateur" required><br>
        <input type="password" name="password" placeholder="Mot de passe" required><br>
        <button type="submit">Se connecter</button>
    </form>
    <p><a href="register.php" style="color:#ff69b4;text-decoration:none;">Créer un compte</a></p>
</div>
</body>
</html>
