<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

date_default_timezone_set('Asia/Dubai');

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

if (empty($_SESSION['user_id'])) {
    header("Location: ../index.html?e=1");
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$role  = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$branchId = (int)($_SESSION['branch_id'] ?? 1);

$sql = "
    SELECT
        cs.id,
        c.case_no,
        c.title,
        c.client_name,
        c.lawyer_name,
        cs.court_name,
        cs.session_type,
        cs.session_date,
        cs.session_time,
        cs.location,
        cs.status,
        b.name_ar AS branch_name
    FROM case_sessions cs
    INNER JOIN cases c ON c.id = cs.case_id
    LEFT JOIN branches b ON b.id = c.branch_id
    WHERE 1=1
";

$params = [];

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

$sql .= " ORDER BY cs.session_date ASC, cs.session_time ASC, cs.id DESC ";

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

$filename = 'hearings_export_' . date('Ymd_His') . '.csv';

header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

$out = fopen('php://output', 'w');

fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));

fputcsv($out, [
    'ID',
    'رقم القضية',
    'اسم القضية',
    'العميل',
    'المحكمة',
    'نوع الجلسة',
    'تاريخ الجلسة',
    'وقت الجلسة',
    'الموقع',
    'الحالة',
    'المحامي',
    'الفرع'
]);

foreach ($rows as $r) {
    fputcsv($out, [
        $r['id'],
        $r['case_no'],
        $r['title'],
        $r['client_name'],
        $r['court_name'],
        $r['session_type'],
        $r['session_date'],
        $r['session_time'],
        $r['location'],
        $r['status'],
        $r['lawyer_name'],
        $r['branch_name'] ?? '',
    ]);
}

fclose($out);
exit;