<?php

function secureQuery($conn, $sql, $params = [])
{
    if (!isset($_SESSION['user'])) {
        throw new Exception("Utilisateur non authentifié");
    }

    $user = $_SESSION['user'];
    $conditions = [];

    /* =============================
       MULTI ENTREPRISE
    ============================= */

    if (strpos($sql, 'entreprise_id') !== false) {
        $conditions[] = "entreprise_id = ?";
        $params[] = $user['entreprise_id'];
    }

    /* =============================
       RESTRICTION CAISSES
    ============================= */

    if (!empty($_SESSION['allowed_caisses']) && strpos($sql, 'caisse_id') !== false) {

        $placeholders = implode(',', array_fill(0, count($_SESSION['allowed_caisses']), '?'));

        $conditions[] = "caisse_id IN ($placeholders)";

        foreach ($_SESSION['allowed_caisses'] as $c) {
            $params[] = $c;
        }
    }

    /* =============================
       RESTRICTION DEPOTS
    ============================= */

    if (!empty($_SESSION['allowed_depots']) && strpos($sql, 'depot_id') !== false) {

        $placeholders = implode(',', array_fill(0, count($_SESSION['allowed_depots']), '?'));

        $conditions[] = "depot_id IN ($placeholders)";

        foreach ($_SESSION['allowed_depots'] as $d) {
            $params[] = $d;
        }
    }

    /* =============================
       AJOUT CONDITIONS SQL
    ============================= */

    if (!empty($conditions)) {

        $conditionSQL = implode(' AND ', $conditions);

        // détecter ORDER BY
        if (stripos($sql, 'ORDER BY') !== false) {

            $parts = preg_split('/ORDER BY/i', $sql);

            if (stripos($parts[0], 'WHERE') !== false) {
                $parts[0] .= " AND " . $conditionSQL . " ";
            } else {
                $parts[0] .= " WHERE " . $conditionSQL . " ";
            }

            $sql = $parts[0] . " ORDER BY " . $parts[1];

        } else {

            if (stripos($sql, 'WHERE') !== false) {
                $sql .= " AND " . $conditionSQL;
            } else {
                $sql .= " WHERE " . $conditionSQL;
            }
        }
    }

    $stmt = $conn->prepare($sql);
    $stmt->execute($params);

    return $stmt;
}