<?php
declare(strict_types=1);

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

date_default_timezone_set('Asia/Dubai');

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/layout.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);

/* =========================
   بيانات الصفحة
========================= */
$currentUser     = (string)($_SESSION['name'] ?? 'مستخدم');
$currentBranchId = (int)($_SESSION['branch_id'] ?? 1);
$currentBranch   = function_exists('branch_name_ar') ? branch_name_ar($currentBranchId) : 'أبوظبي';
$today           = date('Y-m-d');
$role            = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));

/* =========================
   Helpers
========================= */
if (!function_exists('h')) {
    function h($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

function hearing_status_label(string $status): string
{
    return match (strtoupper(trim($status))) {
        'SCHEDULED' => 'مجدولة',
        'DONE' => 'تمت',
        'POSTPONED' => 'مؤجلة',
        'CANCELLED' => 'ألغيت',
        'PENDING_RESULT',
        'PENDING',
        'WAITING_RESULT' => 'بانتظار النتيجة',
        default => 'غير معروف',
    };
}
function hearing_status_class(string $status): string
{
    return match (strtoupper(trim($status))) {
        'SCHEDULED' => 'badge-scheduled',
        'DONE' => 'badge-completed',
        'POSTPONED' => 'badge-postponed',
        'CANCELLED' => 'badge-cancelled',
        'PENDING_RESULT',
        'PENDING',
        'WAITING_RESULT' => 'badge-pending',
        default => 'badge-default',
    };
}

/* =========================
   Filters
========================= */
$q         = trim((string)($_GET['q'] ?? ''));
$fStatus   = trim((string)($_GET['status'] ?? ''));
$fBranch   = trim((string)($_GET['branch'] ?? ''));
$fCourt    = trim((string)($_GET['court'] ?? ''));
$fDateFrom = trim((string)($_GET['date_from'] ?? ''));
$fDateTo   = trim((string)($_GET['date_to'] ?? ''));

/* =========================
   Base query
========================= */
$sql = "
    SELECT
        cs.id,
        cs.case_id,
        c.case_no AS case_number,
        c.title AS case_title,
        CASE
    WHEN cs.client_name IS NOT NULL AND cs.client_name != ''
        THEN cs.client_name
    ELSE c.client_name
END AS client_name,
        cs.court_name,
        cs.session_type AS hearing_type,
        cs.session_date AS hearing_date,
        cs.session_time AS hearing_time,
        COALESCE(b2.name_ar, b.name_ar, '—') AS branch_name,
        cs.status,
        cs.notes AS result_status,
        cs.added_by_user_id,
        u.name AS added_by_name,
        ru.name AS responsible_name
    FROM case_sessions cs
    LEFT JOIN cases c ON c.id = cs.case_id
    LEFT JOIN branches b ON b.id = c.branch_id
    LEFT JOIN branches b2 ON b2.id = cs.branch_id
    LEFT JOIN users u ON u.id = cs.added_by_user_id
    LEFT JOIN users ru ON ru.id = cs.responsible_user_id
    WHERE 1=1
";
$params = [];
/* فلترة الجلسات حسب الفرع الحالي دائماً */
$sql .= " AND COALESCE(cs.branch_id, c.branch_id) = ? ";
$params[] = $currentBranchId;


if ($q !== '') {
    $sql .= " AND (
        c.case_no LIKE ?
        OR c.title LIKE ?
        OR c.client_name LIKE ?
        OR cs.client_name LIKE ?
        OR cs.court_name LIKE ?
        OR cs.session_type LIKE ?
        OR ru.name LIKE ?
        OR u.name LIKE ?
    ) ";

    $like = '%' . $q . '%';

    array_push(
        $params,
        $like,
        $like,
        $like,
        $like,
        $like,
        $like,
        $like,
        $like
    );
}
if ($fStatus !== '') {
    $mapStatus = [
        'scheduled' => 'SCHEDULED',
        'completed' => 'DONE',
        'postponed' => 'POSTPONED',
        'cancelled' => 'CANCELLED',
    ];
    if (isset($mapStatus[$fStatus])) {
        $sql .= " AND cs.status = ? ";
        $params[] = $mapStatus[$fStatus];
    }
}

if ($fBranch !== '') {
    $sql .= " AND COALESCE(b2.name_ar, b.name_ar) = ? ";
    $params[] = $fBranch;
}
if ($fCourt !== '') {
    $sql .= " AND cs.court_name LIKE ? ";
    $params[] = '%' . $fCourt . '%';
}

if ($fDateFrom !== '') {
    $sql .= " AND cs.session_date >= ? ";
    $params[] = $fDateFrom;
}

if ($fDateTo !== '') {
    $sql .= " AND cs.session_date <= ? ";
    $params[] = $fDateTo;
}

$sql .= " 
    ORDER BY
        CASE
            WHEN cs.session_date >= CURDATE() THEN 0
            ELSE 1
        END ASC,
        CASE
            WHEN cs.session_date >= CURDATE() THEN cs.session_date
        END ASC,
        CASE
            WHEN cs.session_date >= CURDATE() THEN cs.session_time
        END ASC,
        CASE
            WHEN cs.session_date < CURDATE() THEN cs.session_date
        END DESC,
        cs.id DESC
";
$st = $pdo->prepare($sql);
$st->execute($params);
$hearings = $st->fetchAll();

/* =========================
   Stats
========================= */
$totalHearings   = count($hearings);
$todayHearings   = count(array_filter($hearings, fn($x) => (string)($x['hearing_date'] ?? '') === $today));
$waitingHearings = count(array_filter($hearings, fn($x) =>
    in_array(strtoupper(trim((string)($x['status'] ?? ''))), ['PENDING_RESULT', 'PENDING', 'WAITING_RESULT'], true)
));
$postponedCount  = count(array_filter($hearings, fn($x) => strtoupper((string)($x['status'] ?? '')) === 'POSTPONED'));

$filtered = $hearings;

$flashSuccess = (string)($_SESSION['flash_success'] ?? '');
unset($_SESSION['flash_success']);

render_layout_start('الجلسات');
?>
<style>
  :root{
    --bg-main:#07171d;
    --bg-card:rgba(255,255,255,.05);
    --bg-card-2:rgba(255,255,255,.04);
    --line:rgba(255,255,255,.08);
    --line-soft:rgba(255,255,255,.05);
    --text:#ffffff;
    --muted:rgba(255,255,255,.68);
    --gold:#d4af37;
    --gold-2:#ffd76a;
    --gold-soft:rgba(212,175,55,.14);
    --danger:#f87171;
    --danger-soft:rgba(248,113,113,.12);
    --success:#34d399;
    --success-soft:rgba(52,211,153,.12);
    --blue:#60a5fa;
    --blue-soft:rgba(96,165,250,.12);
    --warning:#fbbf24;
    --warning-soft:rgba(251,191,36,.12);
    --shadow:0 18px 40px rgba(0,0,0,.16);
  }

  body{
    background:
      radial-gradient(circle at 20% 20%, rgba(10,77,87,.85), transparent 40%),
      radial-gradient(circle at 80% 80%, rgba(13,106,122,.55), transparent 40%),
      #021d23;
  }

  .hearings-page{
    color:var(--text);
    width:100%;
    max-width:100%;
    min-width:0;
    overflow-x:hidden;
  }

  .hearings-page,
  .hearings-page *{
    box-sizing:border-box;
  }

  .hearings-page > *{
    max-width:100%;
    min-width:0;
  }

  .hearings-page .local-head{
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap:16px;
    flex-wrap:wrap;
    margin-bottom:20px;
    width:100%;
    min-width:0;
  }

  .hearings-page .local-head-right,
  .hearings-page .local-head-left,
  .hearings-page .stats,
  .hearings-page .filters-card,
  .hearings-page .table-card,
  .hearings-page .filters-grid,
  .hearings-page .field,
  .hearings-page .table-wrap,
  .hearings-page .section-title,
  .hearings-page .stat-card,
  .hearings-page form{
    min-width:0;
    max-width:100%;
    width:100%;
  }

  .hearings-page .local-head-right{
    flex:1 1 320px;
  }

  .hearings-page .local-head-right h1{
    margin:0 0 6px;
    color:#fff;
    font-size:30px;
    font-weight:800;
  }

  .hearings-page .local-head-right p{
    margin:0;
    color:var(--muted);
    font-size:14px;
    line-height:1.8;
  }

  .hearings-page .local-head-left{
    width:auto;
    flex:0 1 auto;
    display:flex;
    align-items:center;
    gap:12px;
    flex-wrap:wrap;
    justify-content:flex-start;
  }

  .hearings-page .branch-chip,
  .hearings-page .user-chip{
    background:rgba(255,255,255,.08);
    border:1px solid rgba(255,255,255,.12);
    color:#fff;
    border-radius:999px;
    padding:10px 16px;
    font-weight:700;
    max-width:100%;
    white-space:nowrap;
    backdrop-filter:blur(8px);
  }

  .hearings-page .btn-primary-local,
  .hearings-page .btn-light-local{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    border-radius:14px;
    padding:12px 18px;
    font-size:14px;
    font-weight:700;
    text-decoration:none;
    transition:.2s ease;
    cursor:pointer;
    max-width:100%;
    white-space:nowrap;
  }

  .hearings-page .btn-primary-local{
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1d1600;
    border:1px solid rgba(212,175,55,.25);
    box-shadow:0 12px 24px rgba(212,175,55,.18);
  }

  .hearings-page .btn-primary-local:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 28px rgba(212,175,55,.22);
  }

  .hearings-page .btn-light-local{
    background:rgba(255,255,255,.05);
    color:#fff;
    border:1px solid var(--line);
  }

  .hearings-page .stats{
    display:grid;
    grid-template-columns:repeat(auto-fit, minmax(220px, 1fr));
    gap:16px;
    margin-bottom:20px;
  }

  .hearings-page .stat-card,
  .hearings-page .filters-card,
  .hearings-page .table-card{
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:20px;
    box-shadow:var(--shadow);
    overflow:hidden;
    backdrop-filter:blur(12px);
  }

  .hearings-page .stat-card{
    padding:20px;
  }

  .hearings-page .stat-label{
    color:var(--muted);
    font-size:14px;
    margin-bottom:10px;
  }

  .hearings-page .stat-value{
    color:#fff;
    font-size:34px;
    font-weight:800;
    line-height:1;
    margin-bottom:10px;
  }

  .hearings-page .stat-note{
    color:var(--muted);
    font-size:13px;
    line-height:1.7;
  }

  .hearings-page .filters-card{
    padding:18px;
    margin-bottom:18px;
  }

  .hearings-page .section-title{
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:14px;
  }

  .hearings-page .section-title > div{
    min-width:0;
    max-width:100%;
  }

  .hearings-page .section-title h3{
    margin:0;
    color:#fff;
    font-size:22px;
    font-weight:800;
  }

  .hearings-page .section-title p{
    margin:0;
    color:var(--muted);
    font-size:13px;
    line-height:1.8;
  }

  .hearings-page .filters-grid{
    display:grid;
    grid-template-columns:repeat(12, minmax(0, 1fr));
    gap:12px;
    align-items:end;
  }

  .hearings-page .field{
    display:flex;
    flex-direction:column;
    gap:8px;
    grid-column:span 2;
  }

  .hearings-page .field.field-search{
    grid-column:span 4;
  }

  .hearings-page .field label{
    color:var(--muted);
    font-size:13px;
    font-weight:700;
  }

  .hearings-page .input,
  .hearings-page .select,
  .hearings-page input[type="text"],
  .hearings-page input[type="date"],
  .hearings-page select{
    width:100%;
    min-width:0;
    max-width:100%;
    height:50px;
    background:rgba(255,255,255,.05);
    color:#fff;
    border:1px solid var(--line);
    border-radius:14px;
    padding:0 14px;
    outline:none;
    appearance:none;
    -webkit-appearance:none;
    -moz-appearance:none;
  }

  .hearings-page input::placeholder{
    color:rgba(255,255,255,.45);
  }

  .hearings-page select option{
    background:#0b1f26;
    color:#fff;
  }

  .hearings-page .input:focus,
  .hearings-page .select:focus,
  .hearings-page input[type="text"]:focus,
  .hearings-page input[type="date"]:focus,
  .hearings-page select:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 4px rgba(212,175,55,.12);
  }

  .hearings-page .filters-actions{
    display:flex;
    justify-content:flex-start;
    gap:10px;
    flex-wrap:wrap;
    margin-top:14px;
    width:100%;
  }

  .hearings-page .table-wrap{
    width:100%;
    max-width:100%;
    overflow-x:auto;
    overflow-y:hidden;
    -webkit-overflow-scrolling:touch;
  }

  .hearings-page table{
    width:100%;
    min-width:900px;
    border-collapse:separate;
    border-spacing:0;
  }

  .hearings-page thead th{
    background:rgba(255,255,255,.04);
    color:rgba(255,255,255,.72);
    font-size:13px;
    font-weight:800;
    text-align:right;
    padding:16px 14px;
    border-bottom:1px solid var(--line);
    white-space:nowrap;
  }

  .hearings-page tbody td{
    color:#fff;
    padding:16px 14px;
    border-bottom:1px solid var(--line-soft);
    font-size:14px;
    vertical-align:middle;
  }

  .hearings-page tbody tr{
    transition:.18s ease;
  }

  .hearings-page tbody tr:hover{
    background:rgba(255,255,255,.03);
  }

  .hearings-page .case-title{
    font-weight:800;
    font-size:15px;
    margin-bottom:4px;
    color:#fff;
  }

  .hearings-page .muted{
    color:var(--muted);
    font-size:13px;
    line-height:1.7;
  }

  .hearings-page .badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-width:92px;
    padding:8px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:800;
    white-space:nowrap;
    border:1px solid transparent;
  }

  .hearings-page .badge-scheduled{
    background:var(--blue-soft);
    color:var(--blue);
    border-color:rgba(96,165,250,.20);
  }

  .hearings-page .badge-completed{
    background:var(--success-soft);
    color:var(--success);
    border-color:rgba(52,211,153,.20);
  }

  .hearings-page .badge-postponed{
    background:var(--warning-soft);
    color:var(--warning);
    border-color:rgba(251,191,36,.20);
  }

  .hearings-page .badge-cancelled{
    background:var(--danger-soft);
    color:var(--danger);
    border-color:rgba(248,113,113,.20);
  }

  .hearings-page .badge-default{
    background:rgba(148,163,184,.14);
    color:#cbd5e1;
    border-color:rgba(148,163,184,.18);
  }

  .hearings-page .row-actions{
    display:flex;
    flex-wrap:wrap;
    gap:8px;
  }

  .hearings-page .action-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:9px 12px;
    border-radius:12px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
    font-size:13px;
    font-weight:700;
    text-decoration:none;
    white-space:nowrap;
    transition:.18s ease;
  }

  .hearings-page .action-btn:hover{
    background:rgba(255,255,255,.08);
    transform:translateY(-1px);
  }

  .hearings-page .empty{
    padding:34px 18px;
    text-align:center;
    color:var(--muted);
    font-size:15px;
  }

  .hearings-page .flash-success{
    margin-bottom:16px;
    padding:12px 14px;
    border-radius:14px;
    background:rgba(52,211,153,.14);
    color:#fff;
    border:1px solid rgba(52,211,153,.24);
  }

  .hearings-page .footerNote{
    margin-top:18px;
    padding:14px 18px;
    border-radius:16px;
    background:rgba(255,255,255,.04);
    border:1px solid rgba(255,255,255,.08);
    backdrop-filter:blur(8px);
    color:rgba(255,255,255,.75);
    font-size:13px;
  }

  .hearings-page .footer-inner{
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    gap:10px;
  }

  .hearings-page .footer-copy{
    color:#ffd76a !important;
    font-weight:700;
    letter-spacing:.3px;
  }

  .hearings-page .footer-system{
    font-weight:800;
    color:#d4af37;
    letter-spacing:.5px;
  }

  @media (max-width: 1200px){
    .hearings-page .field{
      grid-column:span 4;
    }

    .hearings-page .field.field-search{
      grid-column:span 6;
    }

    .hearings-page table{
      min-width:820px;
    }
  }

  @media (max-width: 980px){
    .hearings-page .local-head-right h1{
      font-size:26px;
    }

    .hearings-page .field,
    .hearings-page .field.field-search{
      grid-column:span 6;
    }

    .hearings-page table{
      min-width:760px;
    }
  }

  @media (max-width: 640px){
    .hearings-page .stats{
      grid-template-columns:1fr;
    }

    .hearings-page .filters-grid{
      grid-template-columns:1fr;
    }

    .hearings-page .field,
    .hearings-page .field.field-search{
      grid-column:span 1;
    }

    .hearings-page .local-head-right h1{
      font-size:18px;
    }

    .hearings-page .section-title h3{
      font-size:18px;
    }

    .hearings-page table{
      min-width:720px;
    }

    .hearings-page .footer-inner{
      flex-direction:column;
      text-align:center;
    }
  }
  .topbar-local{
    display:flex;
    justify-content:space-between;
    align-items:center;
}

.top-left{
    margin-right:auto;
}
/* =========================
   HEARING STATUS - LEGEND UI
========================= */

.hearings-page .badge{
  position:relative;
  min-width:96px;
  height:36px;
  padding:0 15px;
  border-radius:999px;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  overflow:hidden;
  font-size:13px !important;
  font-weight:900 !important;
  letter-spacing:.25px;
  border:1px solid transparent;
  box-shadow:
    0 10px 22px rgba(0,0,0,.22),
    inset 0 1px 0 rgba(255,255,255,.20);
}

.hearings-page .badge::after{
  content:"";
  position:absolute;
  top:0;
  left:-75%;
  width:48%;
  height:100%;
  background:linear-gradient(120deg,transparent,rgba(255,255,255,.55),transparent);
  transform:skewX(-20deg);
  animation:hearingBadgeShine 4s infinite;
}

@keyframes hearingBadgeShine{
  0%{left:-75%;opacity:0;}
  35%{opacity:.8;}
  70%{left:130%;opacity:0;}
  100%{left:130%;opacity:0;}
}

/* مجدولة */
.hearings-page .badge-scheduled{
  background:linear-gradient(135deg,#2563eb,#60a5fa);
  color:#eff6ff;
  border-color:rgba(96,165,250,.45);
  box-shadow:
    0 12px 28px rgba(96,165,250,.32),
    0 0 18px rgba(96,165,250,.25);
}

/* تمت */
.hearings-page .badge-completed{
  background:linear-gradient(135deg,#059669,#34d399);
  color:#ecfdf5;
  border-color:rgba(52,211,153,.45);
  box-shadow:
    0 12px 28px rgba(52,211,153,.32),
    0 0 18px rgba(52,211,153,.25);
}

/* مؤجلة */
.hearings-page .badge-postponed{
  background:linear-gradient(135deg,#d97706,#fbbf24);
  color:#1a1400;
  border-color:rgba(251,191,36,.45);
  box-shadow:
    0 12px 28px rgba(251,191,36,.32),
    0 0 18px rgba(251,191,36,.25);
}

/* ألغيت */
.hearings-page .badge-cancelled{
  background:linear-gradient(135deg,#dc2626,#f87171);
  color:#fff5f5;
  border-color:rgba(248,113,113,.45);
  box-shadow:
    0 12px 28px rgba(248,113,113,.32),
    0 0 18px rgba(248,113,113,.25);
}

.hearings-page .badge-default{
  background:linear-gradient(135deg,#64748b,#94a3b8);
  color:#f8fafc;
  border-color:rgba(148,163,184,.45);
}

.hearings-page .badge:hover{
  transform:translateY(-2px) scale(1.04);
}
/* =========================
   LEGEND STATS CARDS
========================= */

.hearings-page .stat-card{
  position:relative;
  overflow:hidden;
  border-radius:22px;
  padding:22px;

  background:
    linear-gradient(145deg,rgba(255,255,255,.08),rgba(255,255,255,.03)),
    radial-gradient(circle at top, rgba(255,255,255,.12), transparent 60%);

  border:1px solid rgba(255,255,255,.10);

  backdrop-filter:blur(14px);
  -webkit-backdrop-filter:blur(14px);

  box-shadow:
    0 20px 45px rgba(0,0,0,.25),
    inset 0 1px 0 rgba(255,255,255,.15);

  transition:all .35s cubic-bezier(.22,.61,.36,1);
}

/* glow حسب كل كرت */
.hearings-page .stat-card:nth-child(1){
  box-shadow:0 20px 45px rgba(59,130,246,.25);
}

.hearings-page .stat-card:nth-child(2){
  box-shadow:0 20px 45px rgba(34,197,94,.25);
}

.hearings-page .stat-card:nth-child(3){
  box-shadow:0 20px 45px rgba(251,191,36,.25);
}

.hearings-page .stat-card:nth-child(4){
  box-shadow:0 20px 45px rgba(248,113,113,.25);
}

/* hover */
.hearings-page .stat-card:hover{
  transform:translateY(-6px) scale(1.02);

  box-shadow:
    0 35px 70px rgba(0,0,0,.35),
    0 0 30px rgba(212,175,55,.25);
}

/* لمعة متحركة */
.hearings-page .stat-card::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:45%;
  height:100%;
  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.55),
    transparent
  );
  transform:skewX(-20deg);
  animation:statShine 5s infinite;
}

@keyframes statShine{
  0%{ left:-70%; opacity:0 }
  40%{ opacity:.7 }
  100%{ left:130%; opacity:0 }
}
/* =========================
   GOLD BORDER PRO
========================= */

.hearings-page .stat-card{
  border:1px solid rgba(212,175,55,.45) !important;

  box-shadow:
    0 20px 45px rgba(0,0,0,.25),
    0 0 0 1px rgba(212,175,55,.25), /* خط ذهبي خفيف */
    0 0 25px rgba(212,175,55,.18),  /* توهج ذهبي */
    inset 0 1px 0 rgba(255,255,255,.15);
}
.btn-primary-local{
  position:relative;
  overflow:hidden;
}

.btn-primary-local::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;
  background:linear-gradient(120deg,transparent,rgba(255,255,255,.6),transparent);
  transform:skewX(-20deg);
  animation:btnShine 4s infinite;
}

@keyframes btnShine{
  0%{left:-70%}
  100%{left:140%}
}
.hearings-page .badge-pending{
  background:linear-gradient(135deg,#b45309,#ffd76a);
  color:#1a1400;
  border-color:rgba(212,175,55,.45);
  box-shadow:
    0 12px 28px rgba(212,175,55,.32),
    0 0 18px rgba(212,175,55,.25);
}
/* الحالة العامة */
.hearings-page .badge{
  color:#fff !important;
}

/* بانتظار النتيجة */
.hearings-page .badge-pending{
  background:linear-gradient(135deg,#7c2d12,#ea580c) !important;
  color:#fff !important;
  border-color:rgba(234,88,12,.55) !important;
  box-shadow:0 0 18px rgba(234,88,12,.45) !important;
}

/* مؤجلة */
.hearings-page .badge-postponed{
  background:linear-gradient(135deg,#92400e,#d97706) !important;
  color:#fff !important;
  border-color:rgba(217,119,6,.55) !important;
  box-shadow:0 0 18px rgba(217,119,6,.40) !important;
}

/* تمت */
.hearings-page .badge-completed{
  background:linear-gradient(135deg,#047857,#10b981) !important;
  color:#fff !important;
  border-color:rgba(16,185,129,.55) !important;
  box-shadow:0 0 18px rgba(16,185,129,.40) !important;
}

/* مجدولة */
.hearings-page .badge-scheduled{
  background:linear-gradient(135deg,#1e40af,#3b82f6) !important;
  color:#fff !important;
  border-color:rgba(59,130,246,.55) !important;
  box-shadow:0 0 18px rgba(59,130,246,.40) !important;
}

/* ملغاة */
.hearings-page .badge-cancelled{
  background:linear-gradient(135deg,#991b1b,#ef4444) !important;
  color:#fff !important;
  border-color:rgba(239,68,68,.55) !important;
  box-shadow:0 0 18px rgba(239,68,68,.40) !important;
}
.hearings-page .badge{
  min-width:140px;
  height:38px;

  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:6px;

  padding:0 14px;
  border-radius:999px;

  font-size:13px;
  font-weight:800;

  text-align:center;
}
.hearings-page .action-btn-edit{
  background:linear-gradient(135deg,#0f766e,#14b8a6);
  border-color:rgba(20,184,166,.45);
  color:#fff;
  box-shadow:0 0 18px rgba(20,184,166,.25);
}

.hearings-page .action-btn-edit:hover{
  transform:translateY(-2px);
  box-shadow:0 0 24px rgba(20,184,166,.40);
}

.hearings-page .action-btn-delete{
  background:linear-gradient(135deg,#991b1b,#ef4444);
  border-color:rgba(239,68,68,.45);
  color:#fff;
  box-shadow:0 0 18px rgba(239,68,68,.25);
}

.hearings-page .action-btn-delete:hover{
  transform:translateY(-2px);
  box-shadow:0 0 24px rgba(239,68,68,.40);
}
</style>
<div class="hearings-page">
  <div class="local-head">
   

  <div class="local-head-left">
  <div class="branch-chip">الفرع: <?= h($currentBranch) ?></div>
  <div class="user-chip"><?= h($currentUser) ?></div>

  <!-- زر إضافة جلسة -->
  <a href="hearing_add.php" class="btn-primary-local">
    ➕ إضافة جلسة
  </a>

  <a href="../cases.php" class="btn-light-local">
    📂 القضايا
  </a>
</div>

  <?php if ($flashSuccess !== ''): ?>
    <div class="flash-success"><?= h($flashSuccess) ?></div>
  <?php endif; ?>

  <section class="stats">
    <div class="stat-card">
      <div class="stat-label">إجمالي الجلسات</div>
      <div class="stat-value"><?= (int)$totalHearings ?></div>
      <div class="stat-note">جميع الجلسات المسجلة في النظام</div>
    </div>

    <div class="stat-card">
      <div class="stat-label">جلسات اليوم</div>
      <div class="stat-value"><?= (int)$todayHearings ?></div>
      <div class="stat-note">جلسات بتاريخ <?= h($today) ?></div>
    </div>

    <div class="stat-card">
      <div class="stat-label">بانتظار النتيجة</div>
      <div class="stat-value"><?= (int)$waitingHearings ?></div>
      <div class="stat-note">تحتاج تحديث نتيجة الجلسة</div>
    </div>

    <div class="stat-card">
      <div class="stat-label">جلسات مؤجلة</div>
      <div class="stat-value"><?= (int)$postponedCount ?></div>
      <div class="stat-note">تستلزم إعادة جدولة ومتابعة</div>
    </div>
  </section>

  <section class="filters-card">
    <div class="section-title">
      <div>
        <h3>فلتر الجلسات</h3>
        <p>ابحث بسرعة حسب القضية أو العميل أو المحكمة أو التاريخ</p>
      </div>
    </div>

    <form method="get" action="">
      <div class="filters-grid">
        <div class="field field-search">
          <label for="q">بحث عام</label>
          <input class="input" type="text" id="q" name="q" value="<?= h($q) ?>" placeholder="رقم القضية أو العميل أو المحكمة">
        </div>

        <div class="field">
          <label for="status">الحالة</label>
          <select class="select" id="status" name="status">
            <option value="">الكل</option>
            <option value="scheduled" <?= $fStatus === 'scheduled' ? 'selected' : '' ?>>مجدولة</option>
            <option value="completed" <?= $fStatus === 'completed' ? 'selected' : '' ?>>تمت</option>
            <option value="postponed" <?= $fStatus === 'postponed' ? 'selected' : '' ?>>مؤجلة</option>
            <option value="cancelled" <?= $fStatus === 'cancelled' ? 'selected' : '' ?>>ألغيت</option>
          </select>
        </div>

        <div class="field">
          <label for="branch">الفرع</label>
          <select class="select" id="branch" name="branch">
            <option value="">الكل</option>
            <option value="أبوظبي" <?= $fBranch === 'أبوظبي' ? 'selected' : '' ?>>أبوظبي</option>
            <option value="دبي" <?= $fBranch === 'دبي' ? 'selected' : '' ?>>دبي</option>
            <option value="العين" <?= $fBranch === 'العين' ? 'selected' : '' ?>>العين</option>
          </select>
        </div>

        <div class="field">
          <label for="court">المحكمة</label>
          <input class="input" type="text" id="court" name="court" value="<?= h($fCourt) ?>" placeholder="مثال: أبوظبي أو دبي">
        </div>

        <div class="field">
          <label for="date_from">من تاريخ</label>
          <input class="input" type="date" id="date_from" name="date_from" value="<?= h($fDateFrom) ?>">
        </div>

        <div class="field">
          <label for="date_to">إلى تاريخ</label>
          <input class="input" type="date" id="date_to" name="date_to" value="<?= h($fDateTo) ?>">
        </div>
      </div>

      <div class="filters-actions">
        <a href="hearings.php" class="btn-light-local">إعادة تعيين</a>
        <button type="submit" class="btn-primary-local">تطبيق الفلتر</button>
      </div>
    </form>
  </section>

  <section class="table-card">
    <div class="section-title" style="padding:18px 18px 0;">
      <div>
        <h3>قائمة الجلسات</h3>
        <p>عدد النتائج الحالية: <?= count($filtered) ?></p>
      </div>
    </div>

    <div class="table-wrap">
      <?php if (!$filtered): ?>
        <div class="empty">لا توجد جلسات حالياً في النظام.</div>
      <?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>
  <th>الإجراءات</th>
</tr>
          </thead>
          <tbody>
            <?php foreach ($filtered as $row): ?>
              <tr>
                <td>
                  <div class="case-title"><?= h((string)($row['case_title'] ?? '')) ?></div>
                  <div class="muted">رقم القضية: <?= h((string)($row['case_number'] ?? '')) ?></div>
                </td>
                <td><?= h((string)($row['client_name'] ?? '')) ?></td>
                <td><?= h((string)($row['court_name'] ?? '')) ?></td>
                <td><?= h((string)($row['hearing_type'] ?? '')) ?></td>
                <td><?= h((string)($row['hearing_date'] ?? '')) ?></td>
                <td><?= h((string)($row['hearing_time'] ?? '')) ?></td>
                <td><?= h((string)($row['responsible_name'] ?? '—')) ?></td>
                <td><?= h((string)($row['branch_name'] ?? '')) ?></td>
               <td>
  <span class="badge <?= h(hearing_status_class((string)($row['status'] ?? ''))) ?>">
    
    <span class="badge-icon">
      <?= match(strtoupper($row['status'])) {
          'DONE' => '✔',
          'POSTPONED' => '⏳',
          'CANCELLED' => '✖',
          'PENDING_RESULT' => '📌',
          default => '📅'
      } ?>
    </span>

    <?= h(hearing_status_label((string)($row['status'] ?? ''))) ?>
    
  </span>
</td>
<td><?= h((string)($row['added_by_name'] ?? '—')) ?></td>
<td>
  <div class="row-actions">

    <a class="action-btn"
       href="../case_edit.php?id=<?= (int)($row['case_id'] ?? 0) ?>#sessionsBox">
      📂 فتح القضية
    </a>

    <a class="action-btn action-btn-edit"
       href="session_edit.php?id=<?= (int)($row['id'] ?? 0) ?>">
      ✏️ تعديل
    </a>

    <a class="action-btn action-btn-delete"
       onclick="return confirm('هل أنت متأكد من حذف هذه الجلسة؟')"
       href="session_delete.php?id=<?= (int)($row['id'] ?? 0) ?>">
      🗑 حذف
    </a>

</div>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>
  </section>
</div>

<?php render_layout_end(); ?>