<?php
// ============================================================
// clerk/cases/index.php - قائمة القضايا
// ============================================================
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/functions.php';

define('BASE', '../../');
requireRole('clerk', '../../index.php');

$user = currentUser();
$uid  = $user['id'];
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 15;

$search  = trim($_GET['q'] ?? '');
$type    = $_GET['type'] ?? '';
$status  = $_GET['status'] ?? '';
$stage   = $_GET['stage'] ?? '';

$where = "WHERE c.assigned_clerk_id = $uid";
$params = [];

if ($search) {
    $where .= " AND (c.case_number LIKE ? OR c.title LIKE ? OR c.plaintiff LIKE ? OR c.defendant LIKE ?)";
    $s = "%$search%";
    $params[] = $s; $params[] = $s; $params[] = $s; $params[] = $s;
}
if ($type)   { $where .= " AND c.case_type=?";  $params[] = $type; }
if ($status) { $where .= " AND c.status=?";     $params[] = $status; }
if ($stage)  { $where .= " AND c.stage=?";      $params[] = $stage; }

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM cases c $where");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$totalPages = (int)ceil($total / $perPage);
$offset = ($page - 1) * $perPage;

$stmt = $pdo->prepare("
    SELECT c.*,
           pl.full_name AS plaintiff_lawyer,
           dl.full_name AS defendant_lawyer,
           (SELECT COUNT(*) FROM sessions s WHERE s.case_id = c.id) AS session_count,
           (SELECT session_date FROM sessions s WHERE s.case_id = c.id AND s.status='scheduled' ORDER BY session_date ASC LIMIT 1) AS next_session
    FROM cases c
    LEFT JOIN users pl ON pl.id = c.plaintiff_lawyer_id
    LEFT JOIN users dl ON dl.id = c.defendant_lawyer_id
    $where
    ORDER BY c.updated_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$cases = $stmt->fetchAll();

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>القضايا — أمين الضبط</title>
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&family=Amiri:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="../../assets/css/style.css">
<script>const BASE_URL = '../../';</script>
</head>
<body>
<?php require_once __DIR__ . '/../../includes/sidebar.php'; ?>

<div class="main-content">
  <div class="page-header">
    <div>
      <div class="breadcrumb"><a href="../index.php">الرئيسية</a> <span>›</span> <span>القضايا</span></div>
      <div class="page-title">
        <div class="title-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg></div>
        إدارة القضايا
      </div>
    </div>
    <a href="new.php" class="btn btn-gold">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
      قضية جديدة
    </a>
  </div>

  <div class="page-body fade-in">
    <?php if ($flash): ?>
    <div class="alert alert-<?= $flash['type'] ?>" data-auto-dismiss><?= clean($flash['message']) ?></div>
    <?php endif; ?>

    <!-- Filters -->
    <form method="GET" class="filter-bar">
      <div class="search-box" style="flex:1;min-width:200px;">
        <div class="search-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg></div>
        <input type="text" name="q" class="form-control" placeholder="رقم الملف، عنوان القضية، المدعي أو المدعى عليه..." value="<?= clean($search) ?>">
      </div>
      <select name="type" class="form-control" style="width:auto;">
        <option value="">جميع الأنواع</option>
        <option value="civil" <?= $type==='civil'?'selected':'' ?>>مدنية</option>
        <option value="criminal" <?= $type==='criminal'?'selected':'' ?>>جزائية</option>
        <option value="commercial" <?= $type==='commercial'?'selected':'' ?>>تجارية</option>
        <option value="administrative" <?= $type==='administrative'?'selected':'' ?>>إدارية</option>
        <option value="family" <?= $type==='family'?'selected':'' ?>>شؤون أسرة</option>
      </select>
      <select name="status" class="form-control" style="width:auto;">
        <option value="">جميع الحالات</option>
        <option value="active" <?= $status==='active'?'selected':'' ?>>نشطة</option>
        <option value="closed" <?= $status==='closed'?'selected':'' ?>>مغلقة</option>
        <option value="suspended" <?= $status==='suspended'?'selected':'' ?>>موقوفة</option>
      </select>
      <select name="stage" class="form-control" style="width:auto;">
        <option value="">جميع المراحل</option>
        <option value="first_instance" <?= $stage==='first_instance'?'selected':'' ?>>الدرجة الأولى</option>
        <option value="appeal" <?= $stage==='appeal'?'selected':'' ?>>الاستئناف</option>
        <option value="cassation" <?= $stage==='cassation'?'selected':'' ?>>النقض</option>
        <option value="final" <?= $stage==='final'?'selected':'' ?>>نهائية</option>
      </select>
      <button type="submit" class="btn btn-primary">تصفية</button>
      <?php if ($search || $type || $status || $stage): ?>
      <a href="index.php" class="btn btn-outline">إعادة تعيين</a>
      <?php endif; ?>
    </form>

    <div class="card">
      <div class="card-header">
        <div class="card-title">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>
          القضايا (<?= $total ?> إجمالاً)
        </div>
        <div style="display:flex;gap:8px;">
          <button onclick="exportTableCSV('casesTable','قضايا')" class="btn btn-outline btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>
            تصدير
          </button>
          <a href="../../api/export.php?type=cases&clerk_id=<?= $uid ?>" class="btn btn-outline btn-sm" target="_blank">PDF</a>
        </div>
      </div>
      <div class="table-responsive">
        <table class="table" id="casesTable">
          <thead>
            <tr>
              <th>رقم الملف</th>
              <th>عنوان القضية</th>
              <th>النوع</th>
              <th>المدعي</th>
              <th>المدعى عليه</th>
              <th>المرحلة</th>
              <th>الحالة</th>
              <th>الجلسة القادمة</th>
              <th>الجلسات</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <?php if ($cases): foreach ($cases as $c): ?>
            <?php $cs=caseStatusLabel($c['status']); $cst=caseStageLabel($c['stage']); ?>
            <tr>
              <td><span class="case-num"><?= clean($c['case_number']) ?></span></td>
              <td style="max-width:200px;white-space:normal;">
                <div class="fw-bold fs-sm"><?= clean($c['title']) ?></div>
                <div class="fs-sm text-muted"><?= clean($c['court_name'] ?? '') ?></div>
              </td>
              <td class="fs-sm"><?= caseTypeLabel($c['case_type']) ?></td>
              <td class="fs-sm"><?= clean($c['plaintiff'] ?? '—') ?></td>
              <td class="fs-sm"><?= clean($c['defendant'] ?? '—') ?></td>
              <td><span class="badge <?= $cst['class'] ?>"><?= $cst['label'] ?></span></td>
              <td><span class="badge <?= $cs['class'] ?>"><?= $cs['label'] ?></span></td>
              <td class="fs-sm">
                <?php if ($c['next_session']): ?>
                <span style="color:var(--gold-500);font-weight:600"><?= formatDateAr($c['next_session']) ?></span>
                <?php else: ?>
                <span class="text-muted">—</span>
                <?php endif; ?>
              </td>
              <td class="text-center">
                <span class="badge badge-secondary"><?= $c['session_count'] ?></span>
              </td>
              <td>
                <div style="display:flex;gap:6px;">
                  <a href="view.php?id=<?= $c['id'] ?>" class="btn btn-primary btn-sm">عرض</a>
                  <a href="../sessions/new.php?case_id=<?= $c['id'] ?>" class="btn btn-outline btn-sm" data-tip="جدولة جلسة">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                  </a>
                </div>
              </td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="10">
              <div class="empty-state" style="padding:40px">
                <div class="empty-icon">📁</div>
                <h3>لا توجد قضايا<?= ($search||$type||$status) ? ' تطابق معايير البحث' : '' ?></h3>
                <?php if (!$search && !$type && !$status): ?>
                <div class="mt-2"><a href="new.php" class="btn btn-gold">فتح أول قضية</a></div>
                <?php endif; ?>
              </div>
            </td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Pagination -->
    <?php if ($totalPages > 1): ?>
    <div class="pagination">
      <?php for ($p = 1; $p <= $totalPages; $p++): ?>
      <a href="?page=<?= $p ?>&q=<?= urlencode($search) ?>&type=<?= $type ?>&status=<?= $status ?>&stage=<?= $stage ?>"
         class="page-btn <?= $p == $page ? 'active' : '' ?>"><?= $p ?></a>
      <?php endfor; ?>
    </div>
    <?php endif; ?>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/feather-icons/4.29.1/feather.min.js"></script>
<script src="../../assets/js/app.js"></script>
</body>
</html>
