<?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;
}

function h($v): string {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

$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);

$todayOnly = isset($_GET['today']) && $_GET['today'] === '1';
$today = date('Y-m-d');

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

$sql = "
    SELECT
        cs.id,
        cs.case_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.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 ($todayOnly) {
    $sql .= " AND cs.session_date = ? ";
    $params[] = $today;
}

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();

$title = $todayOnly ? 'جلسات اليوم' : 'قائمة الجلسات';
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <title><?= h($title) ?></title>
  <style>
    body{font-family:Tahoma,Arial,sans-serif;margin:20px;color:#111}
    h1{margin:0 0 6px}
    .sub{margin-bottom:20px;color:#555}
    table{width:100%;border-collapse:collapse}
    th,td{border:1px solid #ccc;padding:10px;text-align:right;font-size:13px}
    th{background:#f3f3f3}
    @media print {
      .no-print{display:none}
      body{margin:0}
    }
  </style>
</head>
<body>
  <div class="no-print" style="margin-bottom:16px;">
    <button onclick="window.print()">طباعة</button>
  </div>

  <h1><?= h($title) ?></h1>
  <div class="sub">
    <?= $todayOnly ? 'بتاريخ ' . h($today) : 'جميع الجلسات المسجلة' ?>
  </div>

  <?php if (!$rows): ?>
    <p>لا توجد بيانات للطباعة.</p>
  <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>رقم القضية</th>
          <th>اسم القضية</th>
          <th>العميل</th>
          <th>المحكمة</th>
          <th>نوع الجلسة</th>
          <th>التاريخ</th>
          <th>الوقت</th>
          <th>المحامي</th>
          <th>الفرع</th>
          <th>الحالة</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td><?= h((string)$r['case_no']) ?></td>
            <td><?= h((string)$r['title']) ?></td>
            <td><?= h((string)$r['client_name']) ?></td>
            <td><?= h((string)$r['court_name']) ?></td>
            <td><?= h((string)$r['session_type']) ?></td>
            <td><?= h((string)$r['session_date']) ?></td>
            <td><?= h((string)$r['session_time']) ?></td>
            <td><?= h((string)$r['lawyer_name']) ?></td>
            <td><?= h((string)($r['branch_name'] ?? '-')) ?></td>
            <td><?= h((string)$r['status']) ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</body>
</html>