<?php
function fetchActiveCustomStylesheets($conn_rjllearning, $workspace_id, $institution_id = null, $branch_id = null)
{
    $sql = "
        SELECT *
        FROM marksheet_custom_styling
        WHERE workspace_id = ?
          AND (institution_id = ? OR institution_id IS NULL)
          AND (branch_id = ? OR branch_id IS NULL)
          AND status = 1
        ORDER BY 
            (branch_id IS NULL) ASC,      -- branch-specific first
            (institution_id IS NULL) ASC, -- institution-specific next
            id DESC                       -- newest record if tie
    ";

    $stmt = $conn_rjllearning->prepare($sql);
    $stmt->execute([$workspace_id, $institution_id, $branch_id]);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
