<?php
function genererNumeroFiche($pdo, $sous_dossier_id) {
    $stmt = $pdo->prepare("
        SELECT p.nom as projet_nom, d.nom as dossier_nom, sd.nom as sous_dossier_nom
        FROM sous_dossiers sd
        JOIN dossiers d ON sd.dossier_id = d.id
        JOIN projets p ON d.projet_id = p.id
        WHERE sd.id = ?
    ");
    $stmt->execute([$sous_dossier_id]);
    $infos = $stmt->fetch();
    if (!$infos) return false;

    $projet_code = substr(preg_replace('/[^A-Z0-9]/', '', strtoupper($infos['projet_nom'])), 0, 6);
    $dossier_code = preg_replace('/[^A-Z0-9]/', '', strtoupper($infos['dossier_nom']));
    $sous_dossier_code = substr(preg_replace('/[^A-Z0-9]/', '', strtoupper($infos['sous_dossier_nom'])), 0, 6);

    $prefixe = "CIBER_{$projet_code}_{$dossier_code}_{$sous_dossier_code}";

    $stmt = $pdo->prepare("SELECT dernier_numero FROM compteurs_fiches WHERE sous_dossier_id = ?");
    $stmt->execute([$sous_dossier_id]);
    $row = $stmt->fetch();

    if ($row) {
        $numero = $row['dernier_numero'] + 1;
        $stmt = $pdo->prepare("UPDATE compteurs_fiches SET dernier_numero = ? WHERE sous_dossier_id = ?");
        $stmt->execute([$numero, $sous_dossier_id]);
    } else {
        $numero = 1;
        $stmt = $pdo->prepare("INSERT INTO compteurs_fiches (projet_id, sous_dossier_id, prefixe, dernier_numero)
                               SELECT d.projet_id, ?, ?, ? FROM sous_dossiers sd JOIN dossiers d ON sd.dossier_id = d.id WHERE sd.id = ?");
        $stmt->execute([$sous_dossier_id, $prefixe, $numero, $sous_dossier_id]);
    }

    return $prefixe . str_pad($numero, 5, '0', STR_PAD_LEFT);
}

function logAction($pdo, $user_id, $action, $details = null) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $stmt = $pdo->prepare("INSERT INTO logs (user_id, action, details, ip_address) VALUES (?, ?, ?, ?)");
    $stmt->execute([$user_id, $action, $details, $ip]);
}

/**
 * Vérifie les permissions
 * @param string $required_role 'superadmin', 'admin', 'personnel' ou 'any'
 */
function checkPermission($required_role = 'personnel') {
    if (!isset($_SESSION['user_id'])) return false;
    $user_role = $_SESSION['user_role'];
    if ($required_role === 'any') return true;
    if ($user_role === 'superadmin') return true; // superadmin a tous les droits
    if ($required_role === 'superadmin') return false; // requis superadmin mais pas superadmin
    if ($required_role === 'admin' && $user_role !== 'admin') return false;
    if ($required_role === 'personnel' && !in_array($user_role, ['admin','personnel'])) return false;
    return true;
}

function savePasswordHistory($pdo, $user_id, $new_hash) {
    $stmt = $pdo->prepare("INSERT INTO password_history (user_id, password_hash) VALUES (?, ?)");
    $stmt->execute([$user_id, $new_hash]);
}