<?php
session_start();
require_once 'config/database.php';
require_once 'includes/functions.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header('Location: index.php'); exit; }

$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

if (empty($username) || empty($password)) {
    $_SESSION['error'] = "Veuillez remplir tous les champs.";
    header('Location: index.php');
    exit;
}

$pdo = getPDO();
$stmt = $pdo->prepare("SELECT id, nom, username, email, password_hash, role, signature_path FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

if ($user && password_verify($password, $user['password_hash'])) {
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_nom'] = $user['nom'];
    $_SESSION['user_username'] = $user['username'];
    $_SESSION['user_email'] = $user['email'];
    $_SESSION['user_role'] = $user['role'];
    $_SESSION['user_signature'] = $user['signature_path'] ?? null;
    logAction($pdo, $user['id'], 'connexion');
    header('Location: dashboard.php');
    exit;
} else {
    $_SESSION['error'] = "Nom d'utilisateur ou mot de passe incorrect.";
    header('Location: index.php');
    exit;
}