<?php
function get_hearing_notifications(PDO $pdo, int $branchId, string $role): array
{
    date_default_timezone_set('Asia/Dubai');

    $today = date('Y-m-d');
    $tomorrow = date('Y-m-d', strtotime('+1 day'));
    $threeDays = date('Y-m-d', strtotime('+3 day'));

    $params = [];
    $branchFilter = '';

    if (!in_array($role, ['OWNER','ADMIN'])) {
        $branchFilter = " AND c.branch_id = ? ";
        $params[] = $branchId;
    }

    $sql = "
    SELECT
        cs.id,
        cs.case_id,
        cs.session_date,
        cs.session_time,
        cs.status,
        c.case_no,
        c.title,
        c.client_name
    FROM case_sessions cs
    INNER JOIN cases c ON c.id = cs.case_id
    WHERE 1=1
    $branchFilter
    ";

    $st = $pdo->prepare($sql);
    $st->execute($params);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);

    $notifications = [];

    foreach ($rows as $r) {

        if ($r['session_date'] === $today) {
            $notifications[] = [
                'type' => 'today',
                'text' => "جلسة اليوم للقضية {$r['case_no']} - {$r['title']}",
                'case_id' => $r['case_id']
            ];
        }

        if ($r['session_date'] === $tomorrow) {
            $notifications[] = [
                'type' => 'tomorrow',
                'text' => "جلسة غداً للقضية {$r['case_no']}",
                'case_id' => $r['case_id']
            ];
        }

        if ($r['session_date'] > $today && $r['session_date'] <= $threeDays) {
            $notifications[] = [
                'type' => 'soon',
                'text' => "جلسة قريبة للقضية {$r['case_no']} بتاريخ {$r['session_date']}",
                'case_id' => $r['case_id']
            ];
        }

        if ($r['session_date'] < $today && $r['status'] === 'SCHEDULED') {
            $notifications[] = [
                'type' => 'missing',
                'text' => "جلسة لم يتم إدخال نتيجتها للقضية {$r['case_no']}",
                'case_id' => $r['case_id']
            ];
        }

        if ($r['status'] === 'POSTPONED') {
            $notifications[] = [
                'type' => 'postponed',
                'text' => "جلسة مؤجلة للقضية {$r['case_no']}",
                'case_id' => $r['case_id']
            ];
        }
    }

    return $notifications;
}