<?php
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/rbac.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/sidebar_helper.php';

requireLogin(); requireRole(ROLE_CLERK);
$GLOBALS['BASE_URL_CSS'] = BASE_URL . '/public/assets/css/main.css';
$user = currentUser(); $pdo = db();

// Filters
$search   = $_GET['q']      ?? '';
$status   = $_GET['status'] ?? '';
$type     = $_GET['type']   ?? '';
$stage    = $_GET['stage']  ?? '';

$where = []; $params = [];
if ($search)  { $where[] = "(case_number LIKE ? OR title LIKE ? OR plaintiff LIKE ? OR defendant LIKE ?)"; $p = "%$search%"; $params = array_merge($params,[$p,$p,$p,$p]); }
if ($status)  { $where[] = "status = ?"; $params[] = $status; }
if ($type)    { $where[] = "case_type = ?"; $params[] = $type; }
if ($stage)   { $where[] = "stage = ?"; $params[] = $stage; }
$whereSQL = $where ? 'WHERE '.implode(' AND ',$where) : '';

$stmt = $pdo->prepare("SELECT c.*, u.full_name AS clerk_name FROM cases c LEFT JOIN users u ON c.clerk_id=u.id $whereSQL ORDER BY c.created_at DESC");
$stmt->execute($params);
$cases = $stmt->fetchAll();
$notifCount = getUnreadNotifCount($user['id']);

renderHead('القضايا');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('cases','clerk'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('إدارة القضايا', $notifCount); ?>
<div class="page-content">

  <!-- Toolbar -->
  <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-3">
    <div class="d-flex gap-2 flex-wrap">
      <form method="GET" class="d-flex gap-2 flex-wrap">
        <input type="text" name="q" class="form-control" placeholder="بحث برقم القضية / الأطراف..." value="<?= htmlspecialchars($search) ?>" style="width:240px">
        <select name="status" class="form-select" style="width:130px">
          <option value="">كل الحالات</option>
          <?php foreach (CASE_STATUS as $k=>$v): ?>
          <option value="<?= $k ?>" <?= $status===$k?'selected':'' ?>><?= $v['label'] ?></option>
          <?php endforeach; ?>
        </select>
        <select name="type" class="form-select" style="width:120px">
          <option value="">كل الأنواع</option>
          <?php foreach (CASE_TYPES as $k=>$v): ?>
          <option value="<?= $k ?>" <?= $type===$k?'selected':'' ?>><?= $v ?></option>
          <?php endforeach; ?>
        </select>
        <select name="stage" class="form-select" style="width:140px">
          <option value="">كل المراحل</option>
          <?php foreach (STAGES as $k=>$v): ?>
          <option value="<?= $k ?>" <?= $stage===$k?'selected':'' ?>><?= $v ?></option>
          <?php endforeach; ?>
        </select>
        <button class="btn btn-primary"><i class="bi bi-search"></i></button>
        <?php if ($search||$status||$type||$stage): ?><a href="cases.php" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a><?php endif; ?>
      </form>
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-outline-gold btn-sm" onclick="exportTableExcel('casesTable','قائمة_القضايا')"><i class="bi bi-file-excel"></i> Excel</button>
      <a href="case-new.php" class="btn btn-gold"><i class="bi bi-plus-circle"></i> قضية جديدة</a>
    </div>
  </div>

  <div class="panel">
    <?php if (empty($cases)): ?>
      <div class="empty-state py-5 text-center">
        <i class="bi bi-folder-x" style="font-size:48px;color:var(--text-muted)"></i>
        <h5 class="mt-3">لا توجد قضايا</h5>
        <p class="text-muted">لم يتم تسجيل أي قضية مطابقة بعد</p>
      </div>
    <?php else: ?>
    <div class="table-responsive">
      <table class="table dt-table" id="casesTable">
        <thead><tr>
          <th>رقم القضية</th><th>عنوان القضية</th><th>النوع</th>
          <th>المدعي</th><th>المدعى عليه</th><th>المرحلة</th>
          <th>الحالة</th><th>تاريخ الإيداع</th><th>الإجراءات</th>
        </tr></thead>
        <tbody>
        <?php foreach ($cases as $c):
          $st  = CASE_STATUS[$c['status']]  ?? ['label'=>$c['status'],'class'=>'secondary'];
          $stg = STAGES[$c['stage']]        ?? $c['stage'];
        ?>
        <tr>
          <td><a href="case-view.php?id=<?= $c['id'] ?>" class="text-navy fw-700 text-decoration-none"><?= htmlspecialchars($c['case_number']) ?></a></td>
          <td style="max-width:220px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis"><?= htmlspecialchars($c['title']) ?></td>
          <td><?= CASE_TYPES[$c['case_type']]??$c['case_type'] ?></td>
          <td><?= htmlspecialchars(mb_substr($c['plaintiff'],0,20,'UTF-8')) ?>...</td>
          <td><?= htmlspecialchars(mb_substr($c['defendant'],0,20,'UTF-8')) ?>...</td>
          <td><span class="badge bg-gold" style="color:var(--navy)"><?= $stg ?></span></td>
          <td><span class="badge bg-<?= $st['class'] ?>"><?= $st['label'] ?></span></td>
          <td><?= date('d/m/Y',strtotime($c['filing_date'])) ?></td>
          <td>
            <div class="d-flex gap-1">
              <a href="case-view.php?id=<?= $c['id'] ?>" class="action-btn" title="عرض"><i class="bi bi-eye"></i></a>
              <a href="case-edit.php?id=<?= $c['id'] ?>" class="action-btn gold" title="تعديل"><i class="bi bi-pencil"></i></a>
              <a href="session-new.php?case_id=<?= $c['id'] ?>" class="action-btn success" title="جلسة جديدة"><i class="bi bi-calendar-plus"></i></a>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>
</div></div>
<?php renderFoot(); ?>
