<?php

require_once __DIR__ . '/db/auth.php';

auth_start_session();
auth_bootstrap();

header('Content-Type: application/json; charset=UTF-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'message' => 'Méthode non autorisée.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$submitted_cl_auth_user = trim((string) ($_POST['cl_auth_user'] ?? ''));
$submitted_cl_auth_pass = (string) ($_POST['cl_auth_pass'] ?? '');

if ($submitted_cl_auth_user === '' || $submitted_cl_auth_pass === '') {
    http_response_code(422);
    echo json_encode([
        'success' => false,
        'message' => 'Identifiants incomplets.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$stmt_tbl_auth = db()->prepare(
    'SELECT cl_auth_id, cl_auth_user, cl_auth_pass, cl_auth_right
     FROM tbl_auth
     WHERE cl_auth_user = :cl_auth_user
     LIMIT 1'
);
$stmt_tbl_auth->execute([
    'cl_auth_user' => $submitted_cl_auth_user,
]);
$tbl_auth = $stmt_tbl_auth->fetch();

if (!$tbl_auth) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Identifiants invalides.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$cl_auth_id = (int) $tbl_auth['cl_auth_id'];
$cl_auth_user = (string) $tbl_auth['cl_auth_user'];
$cl_auth_pass = (string) $tbl_auth['cl_auth_pass'];
$cl_auth_right = (string) $tbl_auth['cl_auth_right'];
unset($cl_auth_id);

if (!password_verify($submitted_cl_auth_pass, $cl_auth_pass)) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Identifiants invalides.',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if (password_needs_rehash($cl_auth_pass, PASSWORD_DEFAULT)) {
    $rehash_cl_auth_pass = password_hash($submitted_cl_auth_pass, PASSWORD_DEFAULT);
    $stmt_update_password = db()->prepare(
        'UPDATE tbl_auth SET cl_auth_pass = :cl_auth_pass WHERE cl_auth_user = :cl_auth_user'
    );
    $stmt_update_password->execute([
        'cl_auth_pass' => $rehash_cl_auth_pass,
        'cl_auth_user' => $cl_auth_user,
    ]);
}

session_regenerate_id(true);
$_SESSION['user'] = $cl_auth_user;
$_SESSION['role'] = $cl_auth_right;
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

echo json_encode([
    'success' => true,
    'message' => 'Connexion réussie.',
    'user' => $cl_auth_user,
    'role' => $cl_auth_right,
    'adminUrl' => 'admin.php',
    'logoutUrl' => 'logout.php',
], JSON_UNESCAPED_UNICODE);
