<?php
header('Content-Type: text/plain; charset=utf-8');
require_once 'config/database.php';

$username = isset($_REQUEST['username']) ? trim($_REQUEST['username']) : '';
$password = isset($_REQUEST['password']) ? trim($_REQUEST['password']) : '';

if (empty($username) || empty($password)) {
    die("ERR|Identifiants manquants");
}

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

    if ($user) {
        $hash = $user['password_hash'];
        $valid = false;

        // 1. Check bcrypt
        if (password_verify($password, $hash)) {
            $valid = true;
        } 
        // 2. Check plain text (legacy)
        elseif ($hash === $password) {
             $valid = true;
        } 
        // 3. Check MD5 (legacy)
        elseif (md5($password) === $hash) {
             $valid = true;
        }

        if ($valid) {
             // Return: OK|ROLE|FULL_NAME
             echo "OK|" . $user['role'] . "|" . $user['full_name'];
        } else {
             die("ERR|Mot de passe incorrect");
        }
    } else {
        die("ERR|Utilisateur inconnu");
    }
} catch (PDOException $e) {
    die("ERR|Erreur SQL: " . $e->getMessage());
}
?>