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

// ── ثوابت قرارات المحضر ──────────────────────────────────────
$DECISION_TYPES = [
    'adjournment'   => ['label' => 'تأجيل',         'class' => 'warning'],
    'judgment'      => ['label' => 'حكم',            'class' => 'success'],
    'interlocutory' => ['label' => 'حكم تمهيدي',    'class' => 'info'],
    'dismissal'     => ['label' => 'شطب',            'class' => 'secondary'],
];

// ── معالجة AJAX: حذف ──────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $id = (int)($_POST['id'] ?? 0);
    if ($_POST['action'] === 'delete' && $id) {
        $pdo->prepare("DELETE FROM session_minutes WHERE id=?")->execute([$id]);
        auditLog($user['id'], 'delete_minutes', 'session_minutes', $id, 'حذف محضر جلسة');
        echo json_encode(['ok' => true]);
    } else {
        echo json_encode(['ok' => false]);
    }
    exit;
}

// ── الفلاتر ───────────────────────────────────────────────────
$search      = trim($_GET['q']        ?? '');
$decision    = $_GET['decision']      ?? '';
$finalized   = $_GET['finalized']     ?? '';
$date_from   = $_GET['date_from']     ?? '';
$date_to     = $_GET['date_to']       ?? '';

$where = []; $params = [];
if ($search)    { $where[] = "(c.case_number LIKE ? OR c.title LIKE ? OR s.judge_name LIKE ?)"; $p="%$search%"; $params=array_merge($params,[$p,$p,$p]); }
if ($decision)  { $where[] = "sm.decision_type = ?"; $params[] = $decision; }
if ($finalized !== '') { $where[] = "sm.finalized = ?"; $params[] = (int)$finalized; }
if ($date_from) { $where[] = "DATE(s.session_date) >= ?"; $params[] = $date_from; }
if ($date_to)   { $where[] = "DATE(s.session_date) <= ?"; $params[] = $date_to; }
$whereSQL = $where ? 'WHERE '.implode(' AND ',$where) : '';

$stmt = $pdo->prepare("
    SELECT sm.*, s.session_date, s.judge_name, s.room,
           c.case_number, c.title AS case_title, c.id AS case_id,
           u.full_name AS clerk_name
    FROM session_minutes sm
    JOIN sessions s  ON sm.session_id = s.id
    JOIN cases c     ON s.case_id = c.id
    JOIN users u     ON sm.created_by = u.id
    $whereSQL
    ORDER BY s.session_date DESC
");
$stmt->execute($params);
$minutes = $stmt->fetchAll();

// إحصائيات
$stats = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(finalized=1) AS finalized,
        SUM(finalized=0) AS draft,
        SUM(decision_type='judgment') AS judgments
    FROM session_minutes
")->fetch();

$notifCount = getUnreadNotifCount($user['id']);
renderHead('المحاضر');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('minutes','clerk'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('إدارة المحاضر', $notifCount); ?>
<div class="page-content">

  <!-- بطاقات الإحصائيات -->
  <div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
      <div class="panel p-3 text-center">
        <div style="font-size:28px;font-weight:800;color:var(--gold)"><?= $stats['total'] ?></div>
        <div style="font-size:12px;color:var(--text-muted)">إجمالي المحاضر</div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="panel p-3 text-center">
        <div style="font-size:28px;font-weight:800;color:#198754"><?= $stats['finalized'] ?></div>
        <div style="font-size:12px;color:var(--text-muted)">محاضر مختومة</div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="panel p-3 text-center">
        <div style="font-size:28px;font-weight:800;color:#ffc107"><?= $stats['draft'] ?></div>
        <div style="font-size:12px;color:var(--text-muted)">مسودات</div>
      </div>
    </div>
    <div class="col-6 col-md-3">
      <div class="panel p-3 text-center">
        <div style="font-size:28px;font-weight:800;color:var(--navy)"><?= $stats['judgments'] ?></div>
        <div style="font-size:12px;color:var(--text-muted)">محاضر أحكام</div>
      </div>
    </div>
  </div>

  <!-- شريط الأدوات -->
  <div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-3">
    <form method="GET" class="d-flex gap-2 flex-wrap align-items-center">
      <input type="text" name="q" class="form-control" placeholder="بحث برقم القضية / القاضي..." value="<?= htmlspecialchars($search) ?>" style="width:230px">
      <select name="decision" class="form-select" style="width:140px">
        <option value="">كل القرارات</option>
        <?php foreach ($DECISION_TYPES as $k=>$v): ?>
        <option value="<?= $k ?>" <?= $decision===$k?'selected':'' ?>><?= $v['label'] ?></option>
        <?php endforeach; ?>
      </select>
      <select name="finalized" class="form-select" style="width:130px">
        <option value="">كل الحالات</option>
        <option value="1" <?= $finalized==='1'?'selected':'' ?>>مختوم</option>
        <option value="0" <?= $finalized==='0'?'selected':'' ?>>مسودة</option>
      </select>
      <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>" style="width:145px" title="من تاريخ">
      <input type="date" name="date_to"   class="form-control" value="<?= htmlspecialchars($date_to) ?>"   style="width:145px" title="إلى تاريخ">
      <button class="btn btn-primary"><i class="bi bi-search"></i></button>
      <?php if ($search||$decision||$finalized!==''||$date_from||$date_to): ?>
      <a href="minutes.php" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
      <?php endif; ?>
    </form>
    <button class="btn btn-outline-gold btn-sm" onclick="exportTableExcel('minutesTable','قائمة_المحاضر')">
      <i class="bi bi-file-excel"></i> Excel
    </button>
  </div>

  <!-- الجدول -->
  <div class="panel">
    <?php if (empty($minutes)): ?>
      <div class="empty-state py-5 text-center">
        <i class="bi bi-journal-x" style="font-size:48px;color:var(--text-muted)"></i>
        <h5 class="mt-3">لا توجد محاضر</h5>
        <p class="text-muted">لم يتم العثور على محاضر بهذه المعايير</p>
        <a href="sessions.php" class="btn btn-gold mt-2"><i class="bi bi-calendar-check"></i> إدارة الجلسات</a>
      </div>
    <?php else: ?>
    <div class="table-responsive">
      <table class="table dt-table" id="minutesTable">
        <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 ($minutes as $i => $m):
            $dt = $DECISION_TYPES[$m['decision_type']] ?? ['label'=>$m['decision_type'],'class'=>'secondary'];
        ?>
        <tr>
          <td class="text-muted" style="font-size:12px"><?= $i+1 ?></td>
          <td>
            <a href="case-view.php?id=<?= $m['case_id'] ?>" class="text-navy fw-700 text-decoration-none">
              <?= htmlspecialchars($m['case_number']) ?>
            </a>
          </td>
          <td style="max-width:200px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis">
            <?= htmlspecialchars($m['case_title']) ?>
          </td>
          <td style="white-space:nowrap">
            <div style="font-weight:600"><?= date('d/m/Y', strtotime($m['session_date'])) ?></div>
            <div style="font-size:12px;color:var(--text-muted)"><?= date('H:i', strtotime($m['session_date'])) ?></div>
          </td>
          <td><?= htmlspecialchars($m['judge_name'] ?: '—') ?></td>
          <td><span class="badge bg-<?= $dt['class'] ?>"><?= $dt['label'] ?></span></td>
          <td>
            <?php if ($m['finalized']): ?>
              <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>مختوم</span>
            <?php else: ?>
              <span class="badge bg-warning text-dark"><i class="bi bi-pencil me-1"></i>مسودة</span>
            <?php endif; ?>
          </td>
          <td style="font-size:13px"><?= htmlspecialchars($m['clerk_name']) ?></td>
          <td>
            <div class="d-flex gap-1">
              <a href="session-minutes.php?session_id=<?= $m['session_id'] ?>" class="action-btn gold" title="تعديل المحضر"><i class="bi bi-journal-text"></i></a>
              <a href="case-view.php?id=<?= $m['case_id'] ?>" class="action-btn" title="عرض القضية"><i class="bi bi-eye"></i></a>
              <?php if (!$m['finalized']): ?>
              <button class="action-btn danger" title="حذف" onclick="deleteMinute(<?= $m['id'] ?>)"><i class="bi bi-trash"></i></button>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

</div></div>

<script>
function deleteMinute(id) {
  if (!confirm('هل تريد حذف هذا المحضر نهائياً؟')) return;
  fetch('minutes.php', {
    method: 'POST',
    headers: {'Content-Type':'application/x-www-form-urlencoded'},
    body: `action=delete&id=${id}`
  })
  .then(r => r.json())
  .then(d => { if (d.ok) location.reload(); });
}
</script>

<?php renderFoot(); ?>