<?php
declare(strict_types=1);

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

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

/* =========================
   Helpers
========================= */
function like_escape(string $s): string
{
    return str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $s);
}

function strim_safe(string $text, int $max = 60, string $suffix = '...'): string
{
    $text = trim($text);
    if ($text === '') return '';

    if (function_exists('mb_strimwidth')) {
        return mb_strimwidth($text, 0, $max, $suffix, 'UTF-8');
    }

    if (strlen($text) <= $max) return $text;
    return substr($text, 0, $max) . $suffix;
}

function case_status_badge(string $s): array
{
    $s = strtoupper(trim($s));
    return match ($s) {
        'NEW'    => ['جديدة', 'new'],
        'WORK'   => ['قيد العمل', 'work'],
        'COURT'  => ['في المحكمة', 'court'],
        'CLOSED' => ['مغلقة', 'closed'],
        default  => ['-', 'default'],
    };
}

function table_exists_local(PDO $pdo, string $table): bool
{
    $st = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_schema = DATABASE()
          AND table_name = ?
    ");
    $st->execute([$table]);
    return (int)$st->fetchColumn() > 0;
}

function column_exists_local(PDO $pdo, string $table, string $column): bool
{
    $st = $pdo->prepare("
        SELECT COUNT(*)
        FROM information_schema.columns
        WHERE table_schema = DATABASE()
          AND table_name = ?
          AND column_name = ?
    ");
    $st->execute([$table, $column]);
    return (int)$st->fetchColumn() > 0;
}

function pick_col(PDO $pdo, string $table, array $candidates, string $fallback = ''): string
{
    foreach ($candidates as $c) {
        if (column_exists_local($pdo, $table, $c)) return $c;
    }
    return $fallback;
}

/* =========================
   Session/User
========================= */
$branchId = (int)($_SESSION['branch_id'] ?? 1);
if ($branchId <= 0) $branchId = 1;

$role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
$isOwner = ($role === 'OWNER');
$canSwitchBranch = in_array($role, ['OWNER', 'ADMIN'], true);

/* =========================
   Branch name
========================= */
$currentBranchName = '';
if (table_exists_local($pdo, 'branches') && column_exists_local($pdo, 'branches', 'name_ar')) {
    try {
        $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id = ? LIMIT 1");
        $st->execute([$branchId]);
        $currentBranchName = trim((string)($st->fetchColumn() ?: ''));
    } catch (Throwable $e) {
        $currentBranchName = '';
    }
}

if ($currentBranchName === '') {
    $currentBranchName = match ($branchId) {
        2 => 'دبي',
        3 => 'الشارقة',
        4 => 'العين',
        default => 'أبوظبي',
    };
}

/* =========================
   Validate required table
========================= */
if (!table_exists_local($pdo, 'cases')) {
    http_response_code(500);
    exit('Table "cases" not found');
}

/* =========================
   Columns discovery
========================= */
$hasBranchCol   = column_exists_local($pdo, 'cases', 'branch_id');
$hasCreatedBy   = column_exists_local($pdo, 'cases', 'created_by');
$hasNextHearing = column_exists_local($pdo, 'cases', 'next_hearing_date');
$hasNotes       = column_exists_local($pdo, 'cases', 'notes');
$hasSecretCol   = column_exists_local($pdo, 'cases', 'is_secret');

$colCaseNo   = pick_col($pdo, 'cases', ['case_no', 'case_number'], 'case_no');
$colTitle    = pick_col($pdo, 'cases', ['title', 'case_title'], 'title');
$colCategory = pick_col($pdo, 'cases', ['category'], 'category');
$colClient   = pick_col($pdo, 'cases', ['client_name', 'client'], 'client_name');
$colLawyer   = pick_col($pdo, 'cases', ['lawyer_name', 'lawyer'], 'lawyer_name');
$colStatus   = pick_col($pdo, 'cases', ['status'], 'status');

/* =========================
   Client phone
========================= */
$casesClientPhoneCol = pick_col($pdo, 'cases', ['client_phone', 'client_mobile', 'client_tel', 'phone', 'mobile'], '');
$casesClientIdCol    = pick_col($pdo, 'cases', ['client_id'], '');

$clientsTable    = table_exists_local($pdo, 'clients') ? 'clients' : '';
$clientsIdCol    = ($clientsTable !== '') ? pick_col($pdo, 'clients', ['id', 'client_id'], 'id') : '';
$clientsPhoneCol = ($clientsTable !== '') ? pick_col($pdo, 'clients', ['phone', 'mobile', 'client_phone', 'client_mobile', 'tel'], '') : '';

$joinClient = '';
$clientPhoneSelect = "NULL AS client_phone";

if ($casesClientPhoneCol !== '') {
    $clientPhoneSelect = "c.`$casesClientPhoneCol` AS client_phone";
} elseif ($clientsTable !== '' && $casesClientIdCol !== '' && $clientsPhoneCol !== '') {
    $joinClient = " LEFT JOIN `$clientsTable` cl ON cl.`$clientsIdCol` = c.`$casesClientIdCol` ";
    $clientPhoneSelect = "cl.`$clientsPhoneCol` AS client_phone";
}

/* =========================
   Users join
========================= */
$joinUser = '';
$userSelect = "NULL AS created_by_name, NULL AS created_by_username";

if ($hasCreatedBy && table_exists_local($pdo, 'users')) {
    $joinUser = " LEFT JOIN users u ON u.id = c.created_by ";
    $userSelect = "u.name AS created_by_name, u.username AS created_by_username";
}

/* =========================
   Filters
========================= */
$q = trim((string)($_GET['q'] ?? ''));
$status = strtoupper(trim((string)($_GET['status'] ?? '')));
$allowedStatus = ['NEW', 'WORK', 'COURT', 'CLOSED'];
$current = in_array($status, $allowedStatus, true) ? $status : 'ALL';

$whereParts = [];
$params = [];

if ($hasBranchCol) {
    $whereParts[] = "COALESCE(NULLIF(c.branch_id,0), ?) = ?";
    $params[] = $branchId;
    $params[] = $branchId;
} else {
    $whereParts[] = "1=1";
}

if ($current !== 'ALL') {
    $whereParts[] = "UPPER(c.`$colStatus`) = ?";
    $params[] = $current;
}

if ($q !== '') {
    $like = '%' . like_escape($q) . '%';
    $whereParts[] = "(
        c.`$colCaseNo` LIKE ? ESCAPE '\\\\'
        OR c.`$colTitle` LIKE ? ESCAPE '\\\\'
        OR c.`$colCategory` LIKE ? ESCAPE '\\\\'
        OR c.`$colClient` LIKE ? ESCAPE '\\\\'
        OR c.`$colLawyer` LIKE ? ESCAPE '\\\\'
    )";
    array_push($params, $like, $like, $like, $like, $like);
}

$whereSql = implode(' AND ', $whereParts);

/* =========================
   Stats
========================= */
$stats = ['ALL' => 0, 'NEW' => 0, 'WORK' => 0, 'COURT' => 0, 'CLOSED' => 0];

try {
    $statsWhere = [];
    $statsParams = [];

    if ($hasBranchCol) {
        $statsWhere[] = "COALESCE(NULLIF(c.branch_id,0), ?) = ?";
        $statsParams[] = $branchId;
        $statsParams[] = $branchId;
    } else {
        $statsWhere[] = "1=1";
    }

    $stSql = "
        SELECT UPPER(c.`$colStatus`) st, COUNT(*) total
        FROM cases c
        WHERE " . implode(' AND ', $statsWhere) . "
        GROUP BY UPPER(c.`$colStatus`)
    ";

    $st = $pdo->prepare($stSql);
    $st->execute($statsParams);

    foreach ($st->fetchAll() as $r) {
        $s = (string)($r['st'] ?? '');
        $t = (int)($r['total'] ?? 0);
        if (isset($stats[$s])) $stats[$s] = $t;
        $stats['ALL'] += $t;
    }
} catch (Throwable $e) {
    $stats = ['ALL' => 0, 'NEW' => 0, 'WORK' => 0, 'COURT' => 0, 'CLOSED' => 0];
}

$tabUrl = function (string $st) use ($q): string {
    $qs = [];
    if ($st !== 'ALL') $qs['status'] = $st;
    if ($q !== '') $qs['q'] = $q;
    return 'cases.php' . (empty($qs) ? '' : ('?' . http_build_query($qs)));
};

/* =========================
   Fetch cases
========================= */
$selectNext   = $hasNextHearing ? "c.next_hearing_date" : "NULL AS next_hearing_date";
$selectNotes  = $hasNotes ? "c.notes" : "NULL AS notes";
$selectSecret = $hasSecretCol ? "COALESCE(c.is_secret,0) AS is_secret" : "0 AS is_secret";

$sql = "
    SELECT
      c.id,
      c.`$colCaseNo`   AS case_no,
      c.`$colTitle`    AS title,
      c.`$colCategory` AS category,
      c.`$colClient`   AS client_name,
      c.`$colLawyer`   AS responsible_employee,
      UPPER(c.`$colStatus`) AS status,
      $selectNext,
      $selectNotes,
      $selectSecret,
      $userSelect,
      $clientPhoneSelect
    FROM cases c
    $joinUser
    $joinClient
    WHERE $whereSql
    ORDER BY c.id DESC
    LIMIT 300
";

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

/* =========================
   Layout start
========================= */
render_layout_start('القضايا');
?>
<div class="cases-page hlg-page">
<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);
    --teal-soft:rgba(0,190,210,.10);
    --danger:#ef4444;
    --danger-soft:rgba(239,68,68,.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;
  }

  .cases-page{
    color:var(--text);
    width:100%;
    max-width:100%;
  }

  .cases-page *{
    box-sizing:border-box;
  }

  .cases-page .topbar-local{
    min-height:68px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:10px 12px;
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    position:sticky;
    top:12px;
    z-index:10;
    margin-bottom:18px;
    backdrop-filter:blur(12px);
  }

  .cases-page .top-left{
    display:flex;
    align-items:center;
    gap:10px;
    overflow:visible;
    flex-wrap:wrap;
  }

  .cases-page .muted{
    color:var(--muted);
    font-size:13px;
  }

  .cases-page .branch-switch{
    position:relative;
    display:inline-flex;
    align-items:center;
    z-index:3000;
  }

  .cases-page .branch-btn{
    height:42px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    background:rgba(255,255,255,.05);
    border:1px solid var(--line);
    border-radius:999px;
    padding:0 14px;
    cursor:pointer;
    font-family:inherit;
    font-weight:900;
    color:#fff;
    box-shadow:0 10px 22px rgba(0,0,0,.10);
    backdrop-filter:blur(8px);
  }

  .cases-page .branch-dot{
    width:10px;
    height:10px;
    border-radius:50%;
    background:var(--gold);
    box-shadow:0 0 0 4px rgba(212,175,55,.14);
  }

  .cases-page .branch-name{
    max-width:110px;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    font-size:14px;
    color:#fff;
  }

  .cases-page .branch-menu{
    position:absolute;
    top:calc(100% + 10px);
    right:0;
    min-width:190px;
    background:#0b1f26;
    border:1px solid var(--line);
    border-radius:14px;
    box-shadow:0 18px 40px rgba(0,0,0,.25);
    padding:8px;
    display:none;
    z-index:999999;
  }

  .cases-page .branch-switch.is-open .branch-menu{
    display:block;
  }

  .cases-page .branch-menu form{
    margin:0;
  }

  .cases-page .branch-choice{
    width:100%;
    text-align:right;
    padding:12px;
    border:0;
    background:transparent;
    border-radius:12px;
    cursor:pointer;
    font-family:inherit;
    font-weight:900;
    color:#fff;
  }

  .cases-page .branch-choice:hover{
    background:rgba(255,255,255,.06);
  }

  .cases-page .page-head{
    margin:18px 6px 14px;
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
  }

  .cases-page .pageTitle{
    font-size:30px;
    font-weight:900;
    color:#ffffff;
    margin:0;
    line-height:1.1;
  }

  .cases-page .pageSub{
    color:rgba(255,255,255,.72);
    font-size:14px;
    margin-top:6px;
  }

  .cases-page .btnPrimary{
    display:inline-flex;
    align-items:center;
    gap:10px;
    height:46px;
    padding:0 16px;
    border-radius:14px;
    border:1px solid rgba(212,175,55,.25);
    cursor:pointer;
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    color:#1d1600;
    font-weight:900;
    box-shadow:0 12px 25px rgba(212,175,55,.22);
    text-decoration:none;
    transition:.18s ease;
  }

  .cases-page .btnPrimary:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 32px rgba(212,175,55,.26);
  }

  .cases-page .tabs{
    display:flex;
    gap:10px;
    align-items:center;
    flex-wrap:wrap;
    padding:10px 6px 0;
  }

  .cases-page .tab{
    display:inline-flex;
    align-items:center;
    gap:8px;
    padding:10px 12px;
    border-radius:999px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
    font-weight:900;
    text-decoration:none;
    transition:.18s ease;
  }

  .cases-page .tab:hover{
    background:rgba(255,255,255,.08);
  }

  .cases-page .tab.active{
    border-color:rgba(212,175,55,.35);
    box-shadow:0 0 0 4px rgba(212,175,55,.10);
    background:rgba(212,175,55,.10);
    color:#ffd76a;
  }

  .cases-page .tab .count{
    font-size:12px;
    padding:3px 8px;
    border-radius:999px;
    background:rgba(255,255,255,.06);
    border:1px solid var(--line);
    color:#fff;
    font-weight:900;
  }

  .cases-page .cardBox{
    margin-top:12px;
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    overflow-x:auto;
    position:relative;
    scrollbar-width:none;
    -ms-overflow-style:none;
    backdrop-filter:blur(12px);
  }

  .cases-page .cardBox::-webkit-scrollbar{
    display:none;
  }

  .cases-page .tableHead{
    padding:12px 14px;
    border-bottom:1px solid var(--line);
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
  }

  .cases-page .miniSearch{
    display:flex;
    gap:10px;
    align-items:center;
    flex-wrap:wrap;
  }

  .cases-page .miniSearch input{
    height:40px;
    border-radius:999px;
    border:1px solid var(--line);
    padding:0 14px;
    outline:none;
    background:rgba(255,255,255,.04);
    min-width:260px;
    color:#fff;
  }

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

  .cases-page .miniSearch input:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 4px rgba(212,175,55,.12);
    background:rgba(255,255,255,.06);
  }

  .cases-page .miniSearch button{
    height:40px;
    border-radius:999px;
    border:1px solid var(--line);
    padding:0 14px;
    cursor:pointer;
    background:rgba(255,255,255,.05);
    color:#fff;
    font-weight:900;
  }

  .cases-page .btnIcon{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:40px;
    padding:0 14px;
    border-radius:999px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
    font-weight:900;
    text-decoration:none;
  }

  .cases-page .cases-search-box{
    display:flex;
    gap:12px;
    align-items:center;
    flex-wrap:wrap;
    margin-top:14px;
    margin-bottom:14px;
    padding:0 6px;
  }

  .cases-page .search-input-wrap{
    position:relative;
    flex:1;
    min-width:260px;
  }

  .cases-page .search-input-wrap input{
    width:100%;
    height:46px;
    border-radius:14px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    padding:0 44px 0 14px;
    font-size:14px;
    outline:none;
    transition:.2s ease;
    color:#fff;
  }

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

  .cases-page .search-input-wrap input:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 4px rgba(212,175,55,.12);
  }

  .cases-page .search-icon{
    position:absolute;
    right:14px;
    top:50%;
    transform:translateY(-50%);
    font-size:15px;
    opacity:.75;
    pointer-events:none;
  }

  .cases-page #caseFilter{
    height:46px;
    min-width:170px;
    border-radius:14px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    color:#fff;
    padding:0 14px;
    font-size:14px;
    outline:none;
    cursor:pointer;
  }

  .cases-page #caseFilter option{
    background:#0b1f26;
    color:#fff;
  }

  .cases-page #caseFilter:focus{
    border-color:rgba(212,175,55,.45);
    box-shadow:0 0 0 4px rgba(212,175,55,.12);
  }

  .cases-page .liveResultCount{
    font-size:13px;
    color:var(--muted);
    padding-inline:4px;
  }

  .cases-page table{
    width:100%;
    border-collapse:collapse;
    table-layout:fixed;
    min-width:1200px;
  }

  .cases-page th,
  .cases-page td{
    padding:14px 10px;
    border-bottom:1px solid var(--line);
    text-align:right;
    vertical-align:middle;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }

  .cases-page th{
    background:rgba(255,255,255,.04);
    color:rgba(255,255,255,.72);
    font-size:13px;
    font-weight:900;
  }

  .cases-page td{
    font-size:13px;
    color:#fff;
    background:transparent;
  }

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

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

  .cases-page .badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:6px 10px;
    border-radius:999px;
    border:1px solid var(--line);
    font-weight:900;
    font-size:12px;
    background:rgba(255,255,255,.05);
  }

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

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

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

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

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

  .cases-page .badge.secret{
    background:rgba(220,38,38,.12);
    border-color:rgba(220,38,38,.20);
    color:#f87171;
    margin-right:6px;
  }

  .cases-page th.actionsCol,
  .cases-page td.actionsCol{
    position:sticky;
    right:0;
    left:auto;
    background:#0c2027;
    z-index:6;
    box-shadow:-10px 0 18px rgba(0,0,0,.12);
    text-align:right;
    overflow:visible;
  }

  .cases-page th.actionsCol{
    background:#122830;
  }

  .cases-page .actionsWrap{
    width:100%;
    display:flex;
    justify-content:flex-start;
    align-items:center;
    gap:8px;
    direction:rtl;
    flex-wrap:nowrap;
    overflow:visible;
  }

  .cases-page .actionsWrap > *{
    flex-shrink:0;
  }

  .cases-page .actionsWrap form{
    display:inline-flex;
    margin:0;
  }

  .cases-page .act{
    width:38px;
    height:38px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:12px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    cursor:pointer;
    text-decoration:none;
    user-select:none;
    color:#fff;
    transition:.16s ease;
  }

  .cases-page .act:hover{
    background:rgba(255,255,255,.08);
    transform:translateY(-1px);
  }

  .cases-page .act-del{
    border-color:rgba(239,68,68,.25);
    background:rgba(239,68,68,.08);
  }

  .cases-page .empty{
    padding:26px 14px;
    text-align:center;
    color:var(--muted);
  }

  .cases-page .row-secret{
    background:rgba(127,29,29,.08);
  }

  .cases-page .row-secret td{
    background:rgba(127,29,29,.08);
  }

  .cases-page .row-secret:hover td{
    background:rgba(127,29,29,.14);
  }

  .cases-page .row-secret td:first-child{
    border-right:4px solid #dc2626;
  }

  .cases-page .row-secret .secret-cell-text{
    color:#fca5a5;
    font-weight:800;
  }

  .cases-page .row-secret .muted{
    color:#fca5a5;
  }

  .cases-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;
  }

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

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

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

  @media (max-width: 980px){
    .cases-page .miniSearch input{
      min-width:180px;
    }

    .cases-page .cases-search-box{
      flex-direction:column;
      align-items:stretch;
    }

    .cases-page #caseFilter{
      width:100%;
    }
  }

  @media (max-width: 700px){
    .cases-page .footer-inner{
      flex-direction:column;
      text-align:center;
    }

    .cases-page .pageTitle{
      font-size:24px;
    }
  }
  .cases-header{
    margin-top:40px;
}
.cases-page{
    margin-top: 0;
}

.page-head{
    margin-top: 5px;
}
.cases-page .cases-table,
.cases-page table{
  width:100% !important;
  border-collapse:collapse !important;
  background:rgba(255,255,255,.035) !important;
  border-radius:18px !important;
  overflow:hidden !important;
}

.cases-page th{
  background:rgba(255,255,255,.06) !important;
  color:rgba(255,255,255,.78) !important;
  font-weight:900 !important;
  padding:13px 12px !important;
}

.cases-page td{
  padding:14px 12px !important;
  border-bottom:1px solid rgba(255,255,255,.07) !important;
  color:#fff !important;
}

.cases-page tr:hover td{
  background:rgba(255,255,255,.045) !important;
}

.cases-page .btn,
.cases-page .btnLink,
.cases-page .case-btn,
.cases-page a[href*="case_add"]{
  border-radius:14px !important;
  background:linear-gradient(135deg,#ffd76a,#d4af37) !important;
  color:#10262d !important;
  font-weight:900 !important;
  box-shadow:0 12px 24px rgba(212,175,55,.18) !important;
}
/* =========================
   LEGEND DASHBOARD TABS
========================= */

.cases-page .tabs{
  display:flex;
  gap:12px;
  align-items:center;
  flex-wrap:wrap;
  padding:8px;
  border-radius:18px;

  background:rgba(255,255,255,.04);
  border:1px solid rgba(255,255,255,.08);

  backdrop-filter:blur(14px);
  box-shadow:0 20px 40px rgba(0,0,0,.25);
}

/* الزر */
.cases-page .tab{
  position:relative;
  display:flex;
  align-items:center;
  gap:8px;
  padding:12px 18px;
  border-radius:14px;

  font-weight:900;
  font-size:14px;

  color:rgba(255,255,255,.7);
  text-decoration:none;

  background:linear-gradient(145deg,rgba(255,255,255,.03),rgba(255,255,255,.01));
  border:1px solid rgba(255,255,255,.06);

  transition:all .25s ease;
  transform:translateZ(0);
  overflow:hidden;
}

/* glow خفيف */
.cases-page .tab::before{
  content:'';
  position:absolute;
  inset:0;
  border-radius:inherit;
  background:radial-gradient(circle at top, rgba(255,255,255,.15), transparent 60%);
  opacity:.3;
  pointer-events:none;
}

/* hover */
.cases-page .tab:hover{
  transform:translateY(-3px) scale(1.02);
  color:#fff;
  border-color:rgba(255,255,255,.12);

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

/* ACTIVE = أسطوري */
.cases-page .tab.active{
  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#1a1400;

  border:1px solid rgba(212,175,55,.5);

  box-shadow:
    0 15px 35px rgba(212,175,55,.35),
    0 0 25px rgba(212,175,55,.25),
    inset 0 2px 6px rgba(255,255,255,.35);
}

/* لمعة متحركة */
.cases-page .tab.active::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:shineMove 3.5s infinite;
}

@keyframes shineMove{
  0%{ left:-70%; }
  100%{ left:130%; }
}

/* عداد */
.cases-page .tab .count{
  font-size:12px;
  padding:4px 9px;
  border-radius:999px;

  background:rgba(255,255,255,.08);
  border:1px solid rgba(255,255,255,.15);
  color:#fff;

  font-weight:900;
}

/* عداد داخل active */
.cases-page .tab.active .count{
  background:rgba(0,0,0,.18);
  color:#1a1400;
  border:0;
}

/* ضغط */
.cases-page .tab:active{
  transform:scale(.94);
}

/* تأثير نبض خفيف للزر النشط */
.cases-page .tab.active{
  animation:activePulse 2.5s infinite;
}

@keyframes activePulse{
  0%,100%{
    box-shadow:
      0 15px 35px rgba(212,175,55,.35),
      0 0 20px rgba(212,175,55,.25),
      inset 0 2px 6px rgba(255,255,255,.35);
  }
  50%{
    box-shadow:
      0 18px 45px rgba(212,175,55,.45),
      0 0 35px rgba(212,175,55,.35),
      inset 0 2px 6px rgba(255,255,255,.4);
  }
}
/* =========================
   تحسين وضوح الخط
========================= */

/* النصوص العامة */
.cases-page{
  color:#ffffff !important;
  font-weight:500;
}

/* العناوين */
.pageTitle{
  color:#ffffff !important;
  font-weight:900 !important;
  letter-spacing:.3px;
}

/* النص الثانوي */
.pageSub,
.muted{
  color:rgba(255,255,255,.85) !important;
}

/* رؤوس الجدول */
.cases-page th{
  color:#ffffff !important;
  font-weight:800 !important;
  font-size:14px !important;
}

/* بيانات الجدول */
.cases-page td{
  color:#ffffff !important;
  font-weight:600 !important;
  font-size:14px !important;
}

/* تحسين القراءة داخل الجدول */
.cases-page tbody tr{
  line-height:1.9;
}

/* النص داخل التابات */
.cases-page .tab{
  font-weight:800 !important;
  font-size:14px !important;
}

/* تحسين النص داخل الأزرار */
.btnPrimary,
.layout-btn,
button{
  font-weight:900 !important;
  letter-spacing:.2px;
}

/* تحسين البادجات (الحالة) */
.badge{
  font-weight:900 !important;
  letter-spacing:.3px;
}

/* تحسين النص داخل البحث */
input,
select{
  color:#fff !important;
  font-weight:600;
}

/* placeholder */
input::placeholder{
  color:rgba(255,255,255,.65) !important;
}
.cases-page,
.cases-page td,
.cases-page th{
  text-shadow:0 0 1px rgba(255,255,255,.15);
}
/* =========================
   Professional Status Badges
========================= */

.cases-page .badge{
  min-width:92px;
  height:34px;
  padding:0 14px;
  border-radius:999px;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:6px;
  font-size:13px !important;
  font-weight:900 !important;
  letter-spacing:.2px;
  border:1px solid transparent;
  box-shadow:
    inset 0 1px 0 rgba(255,255,255,.18),
    0 8px 18px rgba(0,0,0,.18);
  position:relative;
  overflow:hidden;
}

/* لمعة خفيفة */
.cases-page .badge::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:45%;
  height:100%;
  background:linear-gradient(120deg,transparent,rgba(255,255,255,.35),transparent);
  transform:skewX(-20deg);
  animation:statusShine 4s infinite;
}

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

/* جديدة */
.cases-page .badge.new{
  background:linear-gradient(135deg,rgba(16,185,129,.28),rgba(5,150,105,.15));
  color:#34f5a2;
  border-color:rgba(52,245,162,.35);
}

/* قيد العمل */
.cases-page .badge.work{
  background:linear-gradient(135deg,rgba(251,191,36,.30),rgba(180,83,9,.16));
  color:#ffd76a;
  border-color:rgba(255,215,106,.35);
}

/* في المحكمة */
.cases-page .badge.court{
  background:linear-gradient(135deg,rgba(96,165,250,.30),rgba(37,99,235,.16));
  color:#93c5fd;
  border-color:rgba(147,197,253,.38);
}

/* مغلقة */
.cases-page .badge.closed{
  background:linear-gradient(135deg,rgba(148,163,184,.24),rgba(71,85,105,.16));
  color:#e2e8f0;
  border-color:rgba(226,232,240,.28);
}

/* سري / محجوب */
.cases-page .badge.secret{
  background:linear-gradient(135deg,rgba(239,68,68,.30),rgba(127,29,29,.18));
  color:#fecaca;
  border-color:rgba(248,113,113,.38);
}
/* =========================
   LEGEND CASE ADD BUTTON
========================= */

.cases-page .btnPrimary{
  position:relative;
  display:inline-flex;
  align-items:center;
  gap:10px;

  height:48px;
  padding:0 20px;

  border-radius:999px;
  border:1px solid rgba(212,175,55,.55);

  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#1a1400;

  font-weight:900;
  font-size:14px;
  letter-spacing:.3px;
  text-decoration:none;

  overflow:hidden;

  box-shadow:
    0 15px 32px rgba(212,175,55,.35),
    0 0 25px rgba(212,175,55,.25),
    inset 0 2px 6px rgba(255,255,255,.35);

  transition:all .25s ease;
}

/* ✨ لمعة متحركة */
.cases-page .btnPrimary::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:caseBtnShine 3.5s infinite;
}

@keyframes caseBtnShine{
  0%{ left:-70%; opacity:0 }
  40%{ opacity:.9 }
  100%{ left:130%; opacity:0 }
}

/* hover 🔥 */
.cases-page .btnPrimary:hover{
  transform:translateY(-3px) scale(1.04);

  box-shadow:
    0 22px 45px rgba(212,175,55,.45),
    0 0 35px rgba(212,175,55,.35),
    inset 0 2px 6px rgba(255,255,255,.45);
}

/* ضغط */
.cases-page .btnPrimary:active{
  transform:scale(.95);
}
.cases-page .badge{
  width:140px;              /* 👈 عرض ثابت */
  height:36px;              /* 👈 ارتفاع موحد */

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

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

  font-size:13px !important;
  font-weight:900 !important;

  text-align:center;
  white-space:nowrap;

  border:1px solid transparent;

  box-shadow:
    inset 0 1px 0 rgba(255,255,255,.18),
    0 8px 18px rgba(0,0,0,.18);

  position:relative;
  overflow:hidden;
}
.cases-page .badge{
  overflow:hidden;
  text-overflow:ellipsis;
}
/* توحيد حالة القضايا نهائياً */
.cases-page td.statusCell{
  text-align:center !important;
  overflow:visible !important;
}

.cases-page td.statusCell .badge{
  width:120px !important;
  min-width:120px !important;
  max-width:120px !important;
  height:34px !important;

  padding:0 8px !important;
  margin:0 auto !important;

  display:inline-flex !important;
  align-items:center !important;
  justify-content:center !important;
  gap:5px !important;

  border-radius:999px !important;
  font-size:12px !important;
  font-weight:900 !important;
  line-height:1 !important;

  white-space:nowrap !important;
  overflow:hidden !important;
  text-overflow:ellipsis !important;
  text-align:center !important;
}

/* ألوان الحالات */
.cases-page td.statusCell .badge.new{
  background:linear-gradient(135deg,#059669,#10b981) !important;
  color:#fff !important;
}

.cases-page td.statusCell .badge.work{
  background:linear-gradient(135deg,#92400e,#d97706) !important;
  color:#fff !important;
}

.cases-page td.statusCell .badge.court{
  background:linear-gradient(135deg,#1e40af,#3b82f6) !important;
  color:#fff !important;
}

.cases-page td.statusCell .badge.closed{
  background:linear-gradient(135deg,#475569,#94a3b8) !important;
  color:#fff !important;
}

.cases-page td.statusCell .badge.secret{
  background:linear-gradient(135deg,#991b1b,#ef4444) !important;
  color:#fff !important;
}
/* توحيد عمود الجلسة القادمة */
.cases-page td:nth-child(7),
.cases-page th:nth-child(7){
  width:140px !important;
  min-width:140px !important;
  max-width:140px !important;
  text-align:center !important;
}

/* محتوى التاريخ */
.cases-page td:nth-child(7){
  font-weight:800;
  letter-spacing:.3px;
}

/* إذا كانت فارغة (-) */
.cases-page td:nth-child(7) .muted{
  display:inline-block;
  width:100%;
  text-align:center;
}
/* شكل الجلسة القادمة */
.date-pill{
  display:inline-flex;
  align-items:center;
  justify-content:center;

  width:110px;
  height:32px;

  border-radius:999px;

  font-size:12px;
  font-weight:900;

  background:rgba(255,255,255,.06);
  border:1px solid rgba(255,255,255,.12);

  color:#fff;
}

/* فارغ */
.date-pill.empty{
  opacity:.5;
}
</style>

<div class="cases-page">
  <div class="page-head">
    <div>
      <h1 class="pageTitle">القضايا</h1>
      <div class="pageSub">إدارة جميع القضايا والملفات حسب الفرع المختار</div>
    </div>

    <div>
      <a class="btnPrimary" href="<?= h(u('case_add.php')) ?>">
        <span>+</span>
        <span>إضافة قضية جديدة</span>
      </a>
    </div>
  </div>

  <div class="tabs">
    <a href="<?= h($tabUrl('ALL')) ?>" class="tab <?= $current === 'ALL' ? 'active' : '' ?>">الكل <span class="count"><?= (int)$stats['ALL'] ?></span></a>
    <a href="<?= h($tabUrl('NEW')) ?>" class="tab <?= $current === 'NEW' ? 'active' : '' ?>">جديدة <span class="count"><?= (int)$stats['NEW'] ?></span></a>
    <a href="<?= h($tabUrl('WORK')) ?>" class="tab <?= $current === 'WORK' ? 'active' : '' ?>">قيد العمل <span class="count"><?= (int)$stats['WORK'] ?></span></a>
    <a href="<?= h($tabUrl('COURT')) ?>" class="tab <?= $current === 'COURT' ? 'active' : '' ?>">في المحكمة <span class="count"><?= (int)$stats['COURT'] ?></span></a>
    <a href="<?= h($tabUrl('CLOSED')) ?>" class="tab <?= $current === 'CLOSED' ? 'active' : '' ?>">مغلقة <span class="count"><?= (int)$stats['CLOSED'] ?></span></a>
  </div>

  <div class="cases-search-box">
    <div class="search-input-wrap">
      <span class="search-icon">🔎</span>
      <input
        type="text"
        id="caseSearch"
        placeholder="ابحث سريعًا برقم القضية أو العميل أو الموظف المسؤول أو النوع..."
        autocomplete="off"
      >
    </div>

    <select id="caseFilter">
      <option value="">كل الحالات</option>
      <option value="جديدة">جديدة</option>
      <option value="قيد العمل">قيد العمل</option>
      <option value="في المحكمة">في المحكمة</option>
      <option value="مغلقة">مغلقة</option>
    </select>

    <div class="liveResultCount">النتائج المعروضة: <span id="liveCount"><?= count($cases) ?></span></div>
  </div>

  <section class="cardBox">
    <div class="tableHead">
      <div class="muted">النتائج من قاعدة البيانات: <?= count($cases) ?></div>

      <form class="miniSearch" method="get" action="cases.php">
        <?php if ($current !== 'ALL'): ?>
          <input type="hidden" name="status" value="<?= h($current) ?>">
        <?php endif; ?>

        <input type="text" name="q" value="<?= h($q) ?>" placeholder="بحث من قاعدة البيانات بالاسم أو الرقم...">
        <button type="submit">بحث</button>
        <a href="<?= h(u('cases.php')) ?>" class="btnIcon">مسح</a>
      </form>
    </div>

    <?php if (!$cases): ?>
      <div class="empty">لا توجد قضايا في هذا الفرع حالياً.</div>
    <?php else: ?>
      <table id="casesTable">
        <thead>
<tr>
<th style="width:120px">رقم القضية</th>
<th style="width:180px">نوع القضية</th>
<th style="width:160px">العميل</th>
<th style="width:140px">رقم العميل</th>
<th style="width:160px">الموظف المسؤول</th>
<th style="width:120px">الحالة</th>
<th style="width:130px">الجلسة القادمة</th>
<th style="width:140px">أضيفت بواسطة</th>
<th style="width:240px">الملاحظات</th>
<th class="actionsCol" style="width:160px">إجراءات</th>
</tr>
</thead>
        <tbody>
        <?php foreach ($cases as $c): ?>
          <?php
            [$txt, $cls] = case_status_badge((string)($c['status'] ?? ''));
            $isSecretCase = !empty($c['is_secret']);
            $isBlockedSecret = ($isSecretCase && !$isOwner);
          ?>
          <tr
            class="<?= $isSecretCase ? 'row-secret' : '' ?>"
            data-status-label="<?= h($txt) ?>"
            data-status-code="<?= h((string)($c['status'] ?? '')) ?>"
          >
            <td>
              <?php if ($isBlockedSecret): ?>
                <span class="badge secret">محجوب</span>
              <?php else: ?>
                <?= h((string)($c['case_no'] ?? '')) ?>
              <?php endif; ?>
            </td>

            <td>
              <?php if ($isBlockedSecret): ?>
                <div class="muted">البيانات محجوبة</div>
              <?php else: ?>
                <div style="font-weight:900;display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
                  <span><?= h((string)($c['title'] ?? '')) ?></span>

                  <?php if ($isSecretCase): ?>
                    <?php if ($isOwner): ?>
                      <span style="font-size:14px;color:#dc2626;display:inline-flex;align-items:center;gap:4px;">🔒</span>
                    <?php else: ?>
                      <span class="badge secret">سرية</span>
                    <?php endif; ?>
                  <?php endif; ?>
                </div>
                <div class="muted"><?= h((string)($c['category'] ?? '')) ?></div>
              <?php endif; ?>
            </td>

            <td>
              <?php if ($isBlockedSecret): ?>
                <span class="muted">محجوب</span>
              <?php else: ?>
                <?= h((string)($c['client_name'] ?? '')) ?>
              <?php endif; ?>
            </td>

            <td>
              <?php if ($isBlockedSecret): ?>
                <span class="muted">محجوب</span>
              <?php else: ?>
                <?php
                  $ph = trim((string)($c['client_phone'] ?? ''));
                  echo $ph !== '' ? h($ph) : '<span class="muted">-</span>';
                ?>
              <?php endif; ?>
            </td>

            <td>
              <?php if ($isBlockedSecret): ?>
                <span class="muted">محجوب</span>
              <?php else: ?>
                <?= h((string)($c['responsible_employee'] ?? '')) ?>
              <?php endif; ?>
            </td>

            <td class="statusCell">
              <?php if ($isBlockedSecret): ?>
                <span class="badge secret">سري</span>
              <?php else: ?>
                <span class="badge <?= h(strtolower($cls)) ?>"><?= h($txt) ?></span>
              <?php endif; ?>
            </td>

            <td>
              <?php if ($isBlockedSecret): ?>
                <span class="muted">محجوب</span>
              <?php else: ?>
                <?php
                  $d = trim((string)($c['next_hearing_date'] ?? ''));
                  echo $d !== '' 
  ? '<span class="date-pill">'.h($d).'</span>' 
  : '<span class="date-pill empty">-</span>';
                ?>
              <?php endif; ?>
            </td>

            <td title="<?= h((string)($c['created_by_name'] ?? $c['created_by_username'] ?? '')) ?>">
              <?php if ($isBlockedSecret): ?>
                <span class="muted">محجوب</span>
              <?php else: ?>
                <?php
                  $cb = trim((string)($c['created_by_name'] ?? $c['created_by_username'] ?? ''));
                  echo $cb !== '' ? h($cb) : '<span class="muted">-</span>';
                ?>
              <?php endif; ?>
            </td>

            <td title="<?= h((string)($c['notes'] ?? '')) ?>">
              <?php if ($isBlockedSecret): ?>
                <span class="muted">محجوب</span>
              <?php else: ?>
                <?php
                  $note = trim((string)($c['notes'] ?? ''));
                  echo $note !== '' ? h(strim_safe($note, 60)) : '<span class="muted">-</span>';
                ?>
              <?php endif; ?>
            </td>

            <td class="actionsCol">
              <div class="actionsWrap">
                <?php if ($isBlockedSecret): ?>
                  <span class="act" title="قضية سرية" aria-label="قضية سرية" style="opacity:.45;cursor:not-allowed;">✏️</span>
                  <span class="act" title="مستندات سرية" aria-label="مستندات سرية" style="opacity:.45;cursor:not-allowed;">📁</span>
                  <span class="act act-del" title="غير متاح" aria-label="غير متاح" style="opacity:.45;cursor:not-allowed;">🗑️</span>
                <?php else: ?>
                  <a class="act" href="<?= h(u('case_edit.php?id=' . (int)$c['id'])) ?>" title="تعديل" aria-label="تعديل">✏️</a>
                  <a class="act" href="<?= h(u('case_files.php?case_id=' . (int)$c['id'])) ?>" title="مستندات" aria-label="مستندات">📁</a>
                  <form method="post" action="<?= h(u('case_delete.php')) ?>" onsubmit="return confirm('تأكيد حذف القضية؟');">
                    <input type="hidden" name="id" value="<?= (int)$c['id'] ?>">
                    <button class="act act-del" type="submit" title="حذف" aria-label="حذف">🗑️</button>
                  </form>
                <?php endif; ?>
              </div>
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </section>
<div class="footerNote">
  <div class="footer-inner">
    <span class="footer-copy">
      © <?= date('Y') ?> مجموعة حمدان القانونية – جميع الحقوق محفوظة
    </span>
    <span class="footer-system">HLG-ONE Legal System</span>
  </div>
</div>
<script>
(function(){
  const wrap = document.getElementById('branchSwitch');
  const btn  = document.getElementById('branchBtn');
  const menu = document.getElementById('branchMenu');

  if (wrap && btn && menu) {
    function openMenu(){
      wrap.classList.add('is-open');
      btn.setAttribute('aria-expanded', 'true');
    }

    function closeMenu(){
      wrap.classList.remove('is-open');
      btn.setAttribute('aria-expanded', 'false');
    }

    function toggleMenu(){
      wrap.classList.contains('is-open') ? closeMenu() : openMenu();
    }

    btn.addEventListener('click', function(e){
      e.preventDefault();
      e.stopPropagation();
      toggleMenu();
    });

    document.addEventListener('click', function(e){
      if (wrap.classList.contains('is-open') && !wrap.contains(e.target)) {
        closeMenu();
      }
    });

    document.addEventListener('keydown', function(e){
      if (e.key === 'Escape') closeMenu();
    });

    window.addEventListener('scroll', closeMenu, {passive:true});
  }

  const searchInput = document.getElementById('caseSearch');
  const filterInput = document.getElementById('caseFilter');
  const table = document.getElementById('casesTable');
  const liveCount = document.getElementById('liveCount');

  if (!searchInput || !filterInput || !table) {
    return;
  }

  const rows = Array.from(table.querySelectorAll('tbody tr'));

  function filterCases() {
    const search = (searchInput.value || '').trim().toLowerCase();
    const filter = (filterInput.value || '').trim();
    let visibleCount = 0;

    rows.forEach(function(row){
      const rowText = (row.innerText || row.textContent || '').toLowerCase();
      const rowStatus = (row.getAttribute('data-status-label') || '').trim();

      const matchSearch = search === '' || rowText.includes(search);
      const matchFilter = filter === '' || rowStatus === filter;

      const show = matchSearch && matchFilter;
      row.style.display = show ? '' : 'none';

      if (show) visibleCount++;
    });

    if (liveCount) {
      liveCount.textContent = String(visibleCount);
    }
  }

  searchInput.addEventListener('input', filterCases);
  filterInput.addEventListener('change', filterCases);

  filterCases();
})();
</script>

<?php render_layout_end(); ?>