<?php
declare(strict_types=1);

/* ===== كاشف الأخطاء ===== */
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

set_error_handler(function ($severity, $message, $file, $line) {
    echo "<div style='background:#111;color:#fff;padding:20px;font-family:monospace'>";
    echo "<h3>PHP ERROR</h3>";
    echo "Message: " . htmlspecialchars((string)$message) . "<br>";
    echo "File: " . htmlspecialchars((string)$file) . "<br>";
    echo "Line: " . (int)$line;
    echo "</div>";
    exit;
});

set_exception_handler(function ($e) {
    echo "<div style='background:#111;color:#fff;padding:20px;font-family:monospace'>";
    echo "<h3>UNCAUGHT EXCEPTION</h3>";
    echo "Message: " . htmlspecialchars((string)$e->getMessage()) . "<br>";
    echo "File: " . htmlspecialchars((string)$e->getFile()) . "<br>";
    echo "Line: " . (int)$e->getLine() . "<br><br>";
    echo "<pre>" . htmlspecialchars((string)$e->getTraceAsString()) . "</pre>";
    echo "</div>";
    exit;
});

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

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

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

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

if (!function_exists('status_label_ar')) {
    function status_label_ar(?string $status): string
    {
        $status = trim((string)$status);

        return match ($status) {
            'draft', 'مسودة' => 'مسودة',
            'pending_review', 'under_review', 'قيد المراجعة' => 'قيد المراجعة',
            'active', 'ساري' => 'ساري',
            'signed', 'موقع', 'تم التوقيع' => 'موقع',
            'sent_for_sign', 'مرسل للتوقيع' => 'مرسل للتوقيع',
            'expired', 'منتهي' => 'منتهي',
            'cancelled', 'canceled', 'ملغي' => 'ملغي',
            default => $status !== '' ? $status : '-',
        };
    }
}

if (!function_exists('status_badge_class')) {
    function status_badge_class(?string $status): string
    {
        $status = trim((string)$status);

        return match ($status) {
            'draft', 'مسودة' => 'contracts-badge-draft',
            'pending_review', 'under_review', 'قيد المراجعة' => 'contracts-badge-review',
            'active', 'ساري' => 'contracts-badge-active',
            'signed', 'موقع', 'تم التوقيع' => 'contracts-badge-signed',
            'sent_for_sign', 'مرسل للتوقيع' => 'contracts-badge-sent',
            'expired', 'منتهي' => 'contracts-badge-expired',
            'cancelled', 'canceled', 'ملغي' => 'contracts-badge-cancel',
            default => 'contracts-badge-cancel',
        };
    }
}

if (!function_exists('table_columns')) {
    function table_columns(PDO $pdo, string $table): array
    {
        $st = $pdo->prepare("
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = ?
        ");
        $st->execute([$table]);
        return $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
    }
}

$q = trim((string)($_GET['q'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));

$employeeCols = table_columns($pdo, 'employees');
$typeCols     = table_columns($pdo, 'contract_types');
$contractCols = table_columns($pdo, 'contracts');

$employeeNameCol = in_array('full_name', $employeeCols, true) ? 'full_name' : 'name';
$typeNameCol     = in_array('contract_name', $typeCols, true) ? 'contract_name' : 'name';

/* ===== عنوان العقد ===== */
if (in_array('contract_name', $contractCols, true) && in_array('title', $contractCols, true)) {
    $contractTitleExpr = "COALESCE(NULLIF(c.contract_name, ''), NULLIF(c.title, ''), '-')";
    $searchTitleExpr   = "COALESCE(NULLIF(c.contract_name, ''), NULLIF(c.title, ''))";
} elseif (in_array('contract_name', $contractCols, true)) {
    $contractTitleExpr = "COALESCE(NULLIF(c.contract_name, ''), '-')";
    $searchTitleExpr   = "c.contract_name";
} elseif (in_array('title', $contractCols, true)) {
    $contractTitleExpr = "COALESCE(NULLIF(c.title, ''), '-')";
    $searchTitleExpr   = "c.title";
} else {
    $contractTitleExpr = "'-'";
    $searchTitleExpr   = "CAST(c.id AS CHAR)";
}

/* ===== رقم العقد ===== */
if (in_array('contract_no', $contractCols, true) && in_array('transaction_id', $contractCols, true)) {
    $contractNumberExpr = "COALESCE(NULLIF(c.contract_no, ''), NULLIF(c.transaction_id, ''), '-')";
    $searchNumberExpr   = "COALESCE(NULLIF(c.contract_no, ''), NULLIF(c.transaction_id, ''), CAST(c.id AS CHAR))";
} elseif (in_array('contract_no', $contractCols, true)) {
    $contractNumberExpr = "COALESCE(NULLIF(c.contract_no, ''), '-')";
    $searchNumberExpr   = "COALESCE(NULLIF(c.contract_no, ''), CAST(c.id AS CHAR))";
} elseif (in_array('transaction_id', $contractCols, true)) {
    $contractNumberExpr = "COALESCE(NULLIF(c.transaction_id, ''), '-')";
    $searchNumberExpr   = "COALESCE(NULLIF(c.transaction_id, ''), CAST(c.id AS CHAR))";
} else {
    $contractNumberExpr = "CAST(c.id AS CHAR)";
    $searchNumberExpr   = "CAST(c.id AS CHAR)";
}

/* ===== تعبيرات البحث الموحدة Collation ===== */
$searchTitleLikeExpr  = "CONVERT({$searchTitleExpr} USING utf8mb4) COLLATE utf8mb4_general_ci";
$searchClientLikeExpr = "CONVERT(cl.name USING utf8mb4) COLLATE utf8mb4_general_ci";
$searchLawyerLikeExpr = "CONVERT(e.`{$employeeNameCol}` USING utf8mb4) COLLATE utf8mb4_general_ci";
$searchNumberLikeExpr = "CONVERT({$searchNumberExpr} USING utf8mb4) COLLATE utf8mb4_general_ci";

$sql = "
    SELECT
        c.id,
        {$contractTitleExpr} AS contract_title,
        {$contractNumberExpr} AS contract_number,
        c.end_date,
        c.status,
        cl.name AS client_name,
        e.`{$employeeNameCol}` AS lawyer_name,
        ct.`{$typeNameCol}` AS contract_type_name
    FROM contracts c
    LEFT JOIN clients cl ON cl.id = c.client_id
    LEFT JOIN employees e ON e.id = c.lawyer_id
    LEFT JOIN contract_types ct ON ct.id = c.contract_type_id
    WHERE 1=1
";

$params = [];

if ($q !== '') {
    $sql .= " AND (
        {$searchTitleLikeExpr} LIKE :q1
        OR {$searchClientLikeExpr} LIKE :q2
        OR {$searchLawyerLikeExpr} LIKE :q3
        OR {$searchNumberLikeExpr} LIKE :q4
    ) ";

    $params[':q1'] = "%{$q}%";
    $params[':q2'] = "%{$q}%";
    $params[':q3'] = "%{$q}%";
    $params[':q4'] = "%{$q}%";
}

if ($status !== '') {
    $statusMap = match ($status) {
        'مسودة' => ['مسودة', 'draft'],
        'قيد المراجعة' => ['قيد المراجعة', 'pending_review', 'under_review'],
        'ساري' => ['ساري', 'active'],
        'موقع' => ['موقع', 'تم التوقيع', 'signed'],
        'مرسل للتوقيع' => ['مرسل للتوقيع', 'sent_for_sign'],
        'منتهي' => ['منتهي', 'expired'],
        'ملغي' => ['ملغي', 'cancelled', 'canceled'],
        default => [$status],
    };

    $placeholders = [];
    foreach ($statusMap as $i => $statusValue) {
        $ph = ':status' . $i;
        $placeholders[] = $ph;
        $params[$ph] = $statusValue;
    }

    $sql .= " AND c.status IN (" . implode(', ', $placeholders) . ") ";
}

$sql .= " ORDER BY c.id DESC ";

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

/* ===== الإحصائيات ===== */
$countAll = (int)$pdo->query("SELECT COUNT(*) FROM contracts")->fetchColumn();

$countDraft = (int)$pdo->query("
    SELECT COUNT(*)
    FROM contracts
    WHERE status IN ('مسودة', 'draft')
")->fetchColumn();

$countReview = (int)$pdo->query("
    SELECT COUNT(*)
    FROM contracts
    WHERE status IN ('قيد المراجعة', 'pending_review', 'under_review')
")->fetchColumn();

$countActive = (int)$pdo->query("
    SELECT COUNT(*)
    FROM contracts
    WHERE status IN ('ساري', 'active')
")->fetchColumn();

$countExpired = (int)$pdo->query("
    SELECT COUNT(*)
    FROM contracts
    WHERE status IN ('منتهي', 'expired')
")->fetchColumn();

render_layout_start('إدارة العقود');
?>

<style>
.contracts-shell{
  width:100%;
  max-width:100%;
}

.contracts-card{
  border:1px solid rgba(255,255,255,.08);
  background:linear-gradient(180deg, rgba(7,22,33,.96), rgba(6,18,27,.92));
  border-radius:22px;
  padding:18px;
  overflow:hidden;
  width:100%;
  box-shadow:0 20px 50px rgba(0,0,0,.22);
}

.contracts-head{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:14px;
  margin-bottom:16px;
  flex-wrap:wrap;
}

.contracts-title-wrap{
  display:flex;
  flex-direction:column;
  gap:6px;
}

.contracts-title{
  margin:0;
  font-size:28px;
  font-weight:900;
  color:#fff;
  line-height:1.1;
}

.contracts-subtitle{
  color:rgba(255,255,255,.62);
  font-size:14px;
}

.contracts-add-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:150px;
  height:46px;
  padding:0 18px;
  border-radius:14px;
  background:linear-gradient(135deg,#0b7a8f,#0f9db5);
  color:#fff !important;
  text-decoration:none;
  font-weight:800;
  border:1px solid rgba(255,255,255,.14);
  box-shadow:0 10px 24px rgba(15,157,181,.18);
  transition:.2s ease;
}

.contracts-add-btn:hover{
  transform:translateY(-2px);
  box-shadow:0 14px 28px rgba(15,157,181,.24);
}

.contracts-stats{
  display:grid;
  grid-template-columns:repeat(5,minmax(120px,1fr));
  gap:12px;
  margin-bottom:16px;
}

.stat-box{
  background:rgba(255,255,255,.04);
  border:1px solid rgba(255,255,255,.07);
  border-radius:16px;
  padding:14px 12px;
  text-align:center;
}

.stat-label{
  color:rgba(255,255,255,.62);
  font-size:13px;
  margin-bottom:8px;
}

.stat-value{
  color:#fff;
  font-size:24px;
  font-weight:900;
  line-height:1;
}

.contracts-tools{
  display:grid;
  grid-template-columns:130px 210px 1fr;
  gap:10px;
  margin-bottom:16px;
}

.contracts-table-wrap{
  width:100%;
  overflow-x:auto;
  overflow-y:hidden;
  border-radius:18px;
  border:1px solid rgba(255,255,255,.07);
  background:rgba(255,255,255,.02);
  scrollbar-width:none;
}

.contracts-table-wrap::-webkit-scrollbar{
  width:0;
  height:0;
  display:none;
}

.contracts-table{
  width:100%;
  min-width:1150px;
  border-collapse:separate;
  border-spacing:0;
  color:#fff;
}

.contracts-table thead th{
  position:sticky;
  top:0;
  z-index:2;
  background:linear-gradient(180deg, rgba(28,43,56,.98), rgba(22,35,46,.98));
  color:#fff;
  font-size:15px;
  font-weight:800;
  padding:15px 10px;
  text-align:center;
  border-bottom:1px solid rgba(255,255,255,.08);
  white-space:nowrap;
}

.contracts-table tbody td{
  padding:15px 10px;
  text-align:center;
  border-bottom:1px solid rgba(255,255,255,.05);
  color:rgba(255,255,255,.9);
  vertical-align:middle;
}

.contracts-table tbody tr{
  transition:.18s ease;
}

.contracts-table tbody tr:hover{
  background:rgba(255,255,255,.035);
}

.contract-number{
  font-weight:800;
  color:#fff;
}

.contract-title-cell{
  min-width:260px;
  text-align:right;
  padding-right:16px;
  line-height:1.7;
  font-weight:600;
}

.contracts-badge{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  padding:7px 13px;
  border-radius:999px;
  font-size:12px;
  font-weight:800;
  border:1px solid rgba(255,255,255,.08);
  white-space:nowrap;
}

.contracts-badge-draft{background:rgba(255,255,255,.08);color:#e6edf3;}
.contracts-badge-review{background:rgba(212,175,55,.14);color:#f7d46b;}
.contracts-badge-active{background:rgba(46,204,113,.14);color:#8df0b1;}
.contracts-badge-signed{background:rgba(16,185,129,.16);color:#86efac;}
.contracts-badge-sent{background:rgba(59,130,246,.16);color:#93c5fd;}
.contracts-badge-expired{background:rgba(239,68,68,.14);color:#ff9d9d;}
.contracts-badge-cancel{background:rgba(148,163,184,.14);color:#d5dde7;}

.contracts-actions{
  display:flex;
  gap:8px;
  justify-content:center;
  align-items:center;
}

.action-btn{
  display:flex;
  align-items:center;
  justify-content:center;
  width:36px;
  height:36px;
  border-radius:11px;
  text-decoration:none;
  font-size:16px;
  background:rgba(255,255,255,.045);
  border:1px solid rgba(255,255,255,.08);
  transition:.2s;
  color:#fff;
}

.action-btn:hover{
  transform:translateY(-2px);
  background:rgba(255,255,255,.12);
}

.action-btn.view{color:#7dd3fc;}
.action-btn.edit{color:#facc15;}
.action-btn.delete{color:#f87171;}

.contracts-empty-row td{
  padding:0 !important;
}

.contracts-empty{
  padding:40px 20px;
  text-align:center;
}

.contracts-empty-icon{
  font-size:34px;
  margin-bottom:10px;
}

.contracts-empty-title{
  color:#fff;
  font-size:20px;
  font-weight:800;
  margin-bottom:8px;
}

.contracts-empty-text{
  color:rgba(255,255,255,.65);
  font-size:14px;
}

.nowrap{white-space:nowrap;}

@media (max-width:1100px){
  .contracts-stats{
    grid-template-columns:repeat(2,minmax(140px,1fr));
  }
}

@media (max-width:900px){
  .contracts-title{
    font-size:32px;
  }

  .contracts-tools{
    grid-template-columns:1fr;
  }

  .contracts-stats{
    grid-template-columns:1fr 1fr;
  }

  .contracts-head{
    flex-direction:column;
    align-items:flex-start;
  }

  .contracts-add-btn{
    width:100%;
  }
}

@media (max-width:560px){
  .contracts-stats{
    grid-template-columns:1fr;
  }
}
/* =========================
   CONTRACT STATUS - LEGEND UI
========================= */

.contracts-badge{
  position:relative;
  display:inline-flex;
  align-items:center;
  justify-content:center;

  min-width:110px;
  height:36px;
  padding:0 16px;

  border-radius:999px;
  font-size:12px;
  font-weight:900;
  letter-spacing:.3px;

  border:1px solid transparent;
  overflow:hidden;

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

  box-shadow:
    0 10px 24px rgba(0,0,0,.22),
    inset 0 1px 0 rgba(255,255,255,.2);

  transition:.25s ease;
}

/* لمعة متحركة */
.contracts-badge::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;
  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.55),
    transparent
  );
  transform:skewX(-20deg);
  animation:contractBadgeShine 4s infinite;
}

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

/* ================= الحالات ================= */

/* مسودة */
.contracts-badge-draft{
  background:linear-gradient(135deg,#64748b,#94a3b8);
  color:#f1f5f9;
  border-color:rgba(148,163,184,.45);
}

/* قيد المراجعة */
.contracts-badge-review{
  background:linear-gradient(135deg,#d4af37,#ffd76a);
  color:#1a1400;
  border-color:rgba(212,175,55,.45);

  box-shadow:
    0 12px 28px rgba(212,175,55,.35),
    0 0 20px rgba(212,175,55,.25);
}

/* ساري */
.contracts-badge-active{
  background:linear-gradient(135deg,#059669,#34d399);
  color:#ecfdf5;
  border-color:rgba(52,211,153,.45);

  box-shadow:
    0 12px 28px rgba(52,211,153,.35),
    0 0 20px rgba(52,211,153,.25);
}

/* موقع */
.contracts-badge-signed{
  background:linear-gradient(135deg,#10b981,#6ee7b7);
  color:#052e2b;
  border-color:rgba(110,231,183,.45);
}

/* مرسل للتوقيع */
.contracts-badge-sent{
  background:linear-gradient(135deg,#3b82f6,#60a5fa);
  color:#ecf3ff;
  border-color:rgba(96,165,250,.45);

  box-shadow:
    0 12px 28px rgba(96,165,250,.35),
    0 0 20px rgba(96,165,250,.25);
}

/* منتهي */
.contracts-badge-expired{
  background:linear-gradient(135deg,#dc2626,#f87171);
  color:#fff5f5;
  border-color:rgba(248,113,113,.45);

  box-shadow:
    0 12px 28px rgba(248,113,113,.35),
    0 0 20px rgba(248,113,113,.25);
}

/* ملغي */
.contracts-badge-cancel{
  background:linear-gradient(135deg,#334155,#64748b);
  color:#e2e8f0;
  border-color:rgba(100,116,139,.45);
}

/* hover */
.contracts-badge:hover{
  transform:translateY(-2px) scale(1.05);
}
/* =========================
   CONTRACTS STATS - LEGEND UI
========================= */

.contracts-stats .stat-box{
  position:relative;
  overflow:hidden;
  border-radius:18px;
  padding:16px 14px;
  text-align:center;

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

  border:1px solid rgba(212,175,55,.35); /* ذهبي */

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

  box-shadow:
    0 18px 40px rgba(0,0,0,.25),
    0 0 20px rgba(212,175,55,.18),
    inset 0 1px 0 rgba(255,255,255,.15);

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

/* لمعة متحركة */
.contracts-stats .stat-box::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:contractStatShine 5s infinite;
}

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

/* hover */
.contracts-stats .stat-box:hover{
  transform:translateY(-6px) scale(1.03);

  box-shadow:
    0 30px 60px rgba(0,0,0,.35),
    0 0 35px rgba(212,175,55,.35);
}
.contracts-add-btn{
  position:relative;
  overflow:hidden;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;
  min-width:160px;
  height:48px;
  padding:0 22px;
  border-radius:999px;
  border:1px solid rgba(212,175,55,.55);
  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#1a1400 !important;
  text-decoration:none;
  font-weight:900;
  font-size:14px;
  letter-spacing:.3px;
  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;
}

.contracts-add-btn::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;
  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.65),
    transparent
  );
  transform:skewX(-20deg);
  animation:contractsAddBtnShine 3.5s infinite;
  pointer-events:none;
}

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

.contracts-add-btn: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);
}

.contracts-add-btn:active{
  transform:scale(.96);
}
</style>

<div class="contracts-shell">
  <div class="contracts-card">

    <div class="contracts-head">
      <div class="contracts-title-wrap">
        <h1 class="contracts-title">إدارة العقود</h1>
        <div class="contracts-subtitle">جميع العقود تظهر هنا مباشرة، وأي عقد جديد سيظهر أعلى الجدول تلقائيًا</div>
      </div>

      <a class="contracts-add-btn" href="add_contract.php">+ إضافة عقد</a>
    </div>

    <div class="contracts-stats">
      <div class="stat-box">
        <div class="stat-label">إجمالي العقود</div>
        <div class="stat-value"><?= h($countAll) ?></div>
      </div>
      <div class="stat-box">
        <div class="stat-label">مسودة</div>
        <div class="stat-value"><?= h($countDraft) ?></div>
      </div>
      <div class="stat-box">
        <div class="stat-label">قيد المراجعة</div>
        <div class="stat-value"><?= h($countReview) ?></div>
      </div>
      <div class="stat-box">
        <div class="stat-label">ساري</div>
        <div class="stat-value"><?= h($countActive) ?></div>
      </div>
      <div class="stat-box">
        <div class="stat-label">منتهي</div>
        <div class="stat-value"><?= h($countExpired) ?></div>
      </div>
    </div>

    <form method="get" class="contracts-tools">
      <button class="btn" type="submit">بحث</button>

      <select class="input" name="status">
        <option value="">كل الحالات</option>
        <option value="مسودة" <?= $status === 'مسودة' ? 'selected' : '' ?>>مسودة</option>
        <option value="قيد المراجعة" <?= $status === 'قيد المراجعة' ? 'selected' : '' ?>>قيد المراجعة</option>
        <option value="ساري" <?= $status === 'ساري' ? 'selected' : '' ?>>ساري</option>
        <option value="موقع" <?= $status === 'موقع' ? 'selected' : '' ?>>موقع</option>
        <option value="مرسل للتوقيع" <?= $status === 'مرسل للتوقيع' ? 'selected' : '' ?>>مرسل للتوقيع</option>
        <option value="منتهي" <?= $status === 'منتهي' ? 'selected' : '' ?>>منتهي</option>
        <option value="ملغي" <?= $status === 'ملغي' ? 'selected' : '' ?>>ملغي</option>
      </select>

      <input
        class="input"
        type="text"
        name="q"
        placeholder="بحث برقم العقد أو اسم العقد أو العميل أو المحامي..."
        value="<?= h($q) ?>"
      >
    </form>

    <div class="contracts-table-wrap">
      <table class="contracts-table">
        <thead>
          <tr>
            <th>رقم العقد</th>
            <th>عنوان العقد</th>
            <th>النوع</th>
            <th>العميل</th>
            <th>المحامي</th>
            <th>تاريخ الانتهاء</th>
            <th>الحالة</th>
            <th>الإجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr class="contracts-empty-row">
              <td colspan="8">
                <div class="contracts-empty">
                  <div class="contracts-empty-icon">📄</div>
                  <div class="contracts-empty-title">لا توجد عقود حالياً</div>
                  <div class="contracts-empty-text">يمكنك الضغط على زر إضافة عقد وسيظهر هنا مباشرة</div>
                </div>
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($rows as $r): ?>
              <?php
              $statusValue = trim((string)($r['status'] ?? ''));
              $statusLabel = status_label_ar($statusValue);
              $statusClass = status_badge_class($statusValue);

              $endDate = trim((string)($r['end_date'] ?? ''));
              if ($endDate === '' || $endDate === '0000-00-00') {
                  $endDate = '-';
              }
              ?>
              <tr>
                <td class="contract-number nowrap"><?= h($r['contract_number'] ?? '-') ?></td>
                <td class="contract-title-cell"><?= h($r['contract_title'] ?? '-') ?></td>
                <td><?= h($r['contract_type_name'] ?? '-') ?></td>
                <td><?= h($r['client_name'] ?? '-') ?></td>
                <td><?= h($r['lawyer_name'] ?? '-') ?></td>
                <td class="nowrap"><?= h($endDate) ?></td>
                <td><span class="contracts-badge <?= h($statusClass) ?>"><?= h($statusLabel) ?></span></td>
                <td>
                  <div class="contracts-actions">
                    <a class="action-btn view" href="view_contract.php?id=<?= (int)($r['id'] ?? 0) ?>" title="عرض">👁</a>
                    <a class="action-btn edit" href="edit_contract.php?id=<?= (int)($r['id'] ?? 0) ?>" title="تعديل">✏</a>
                    <a class="action-btn delete" href="delete_contract.php?id=<?= (int)($r['id'] ?? 0) ?>" title="حذف" onclick="return confirm('هل تريد حذف العقد؟')">🗑</a>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

  </div>
</div>

<?php render_layout_end(); ?>