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

$totalCases     = (int)$pdo->query("SELECT COUNT(*) FROM cases")->fetchColumn();
$openCases      = (int)$pdo->query("SELECT COUNT(*) FROM cases WHERE status='open'")->fetchColumn();
$todaySessions  = (int)$pdo->query("SELECT COUNT(*) FROM sessions WHERE DATE(session_date)=CURDATE()")->fetchColumn();
$pendingMinutes = (int)$pdo->query("SELECT COUNT(*) FROM sessions s LEFT JOIN session_minutes sm ON s.id=sm.session_id WHERE s.status='completed' AND sm.id IS NULL")->fetchColumn();

$upcoming = $pdo->query("SELECT s.*, c.case_number, c.title AS case_title, c.plaintiff, c.defendant FROM sessions s JOIN cases c ON s.case_id=c.id WHERE s.session_date>=NOW() AND s.session_date<=DATE_ADD(NOW(),INTERVAL 7 DAY) AND s.status='scheduled' ORDER BY s.session_date ASC LIMIT 8")->fetchAll();
$recentCases = $pdo->query("SELECT * FROM cases ORDER BY created_at DESC LIMIT 6")->fetchAll();
$notifCount = getUnreadNotifCount($user['id']);

renderHead('لوحة التحكم');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('dashboard','clerk'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('لوحة التحكم — أمين الضبط', $notifCount); ?>
<div class="page-content">

  <div class="d-flex align-items-center justify-content-between mb-4 flex-wrap gap-3">
    <div>
      <h4 class="font-amiri fw-700 mb-1" style="color:var(--navy)">مرحباً، <?= htmlspecialchars($user['name']) ?> 👋</h4>
      <p class="text-muted mb-0" style="font-size:13px"><?= date('d/m/Y') ?></p>
    </div>
    <div class="d-flex gap-2 flex-wrap">
      <a href="case-new.php" class="btn btn-gold"><i class="bi bi-plus-circle"></i> قضية جديدة</a>
      <a href="session-new.php" class="btn btn-primary"><i class="bi bi-calendar-plus"></i> جلسة جديدة</a>
    </div>
  </div>

  <div class="row g-3 mb-4">
    <div class="col-6 col-xl-3"><div class="stat-card">
      <div class="stat-icon navy"><i class="bi bi-folder2-open"></i></div>
      <div class="stat-body"><div class="stat-value"><?= $totalCases ?></div><div class="stat-label">إجمالي القضايا</div></div>
    </div></div>
    <div class="col-6 col-xl-3"><div class="stat-card">
      <div class="stat-icon green"><i class="bi bi-folder-check"></i></div>
      <div class="stat-body"><div class="stat-value"><?= $openCases ?></div><div class="stat-label">قضايا مفتوحة</div></div>
    </div></div>
    <div class="col-6 col-xl-3"><div class="stat-card">
      <div class="stat-icon gold"><i class="bi bi-calendar-event"></i></div>
      <div class="stat-body"><div class="stat-value"><?= $todaySessions ?></div><div class="stat-label">جلسات اليوم</div></div>
    </div></div>
    <div class="col-6 col-xl-3"><div class="stat-card">
      <div class="stat-icon red"><i class="bi bi-journal-x"></i></div>
      <div class="stat-body"><div class="stat-value"><?= $pendingMinutes ?></div><div class="stat-label">محاضر غير مكتملة</div></div>
    </div></div>
  </div>

  <div class="row g-3">
    <div class="col-lg-7">
      <div class="panel">
        <div class="panel-header">
          <div class="panel-title"><i class="bi bi-calendar3"></i> الجلسات القادمة (7 أيام)</div>
          <a href="sessions.php" class="btn btn-sm btn-outline-gold">عرض الكل</a>
        </div>
        <?php if (empty($upcoming)): ?>
        <div class="empty-state py-4"><i class="bi bi-calendar-x"></i><h5>لا توجد جلسات قادمة</h5></div>
        <?php else: ?>
        <div class="table-responsive"><table class="table">
          <thead><tr><th>رقم القضية</th><th>الأطراف</th><th>التاريخ والوقت</th><th>القاعة</th><th></th></tr></thead>
          <tbody>
          <?php foreach ($upcoming as $s): ?>
          <tr>
            <td><a href="case-view.php?id=<?= $s['case_id'] ?>" class="text-navy fw-700 text-decoration-none"><?= htmlspecialchars($s['case_number']) ?></a></td>
            <td style="max-width:180px"><div style="font-size:13px;font-weight:600;overflow:hidden;white-space:nowrap;text-overflow:ellipsis"><?= htmlspecialchars($s['plaintiff']) ?></div><div style="font-size:11px;color:var(--text-muted)">ضد: <?= htmlspecialchars($s['defendant']) ?></div></td>
            <td><div class="fw-600" style="font-size:13px"><?= date('d/m/Y',strtotime($s['session_date'])) ?></div><div style="font-size:11px;color:var(--gold)"><?= date('H:i',strtotime($s['session_date'])) ?></div></td>
            <td><?= htmlspecialchars($s['room']??'—') ?></td>
            <td><a href="session-minutes.php?session_id=<?= $s['id'] ?>" class="action-btn gold" title="كتابة محضر"><i class="bi bi-journal-plus"></i></a></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table></div>
        <?php endif; ?>
      </div>
    </div>
    <div class="col-lg-5">
      <div class="panel">
        <div class="panel-header">
          <div class="panel-title"><i class="bi bi-folder2"></i> أحدث القضايا</div>
          <a href="cases.php" class="btn btn-sm btn-outline-gold">عرض الكل</a>
        </div>
        <?php foreach ($recentCases as $c):
          $st = CASE_STATUS[$c['status']] ?? ['label'=>$c['status'],'class'=>'secondary'];
        ?>
        <div class="d-flex align-items-center gap-3 px-4 py-3" style="border-bottom:1px solid var(--border)">
          <div style="width:40px;height:40px;border-radius:10px;background:var(--cream);display:flex;align-items:center;justify-content:center;flex-shrink:0"><i class="bi bi-folder2-open text-gold"></i></div>
          <div style="flex:1;min-width:0">
            <div class="fw-600" style="font-size:13px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis">
              <a href="case-view.php?id=<?= $c['id'] ?>" class="text-decoration-none text-navy"><?= htmlspecialchars($c['title']) ?></a>
            </div>
            <div style="font-size:11px;color:var(--text-muted)"><?= htmlspecialchars($c['case_number']) ?> &bull; <?= CASE_TYPES[$c['case_type']]??$c['case_type'] ?></div>
          </div>
          <span class="badge bg-<?= $st['class'] ?>"><?= $st['label'] ?></span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</div>
</div>
<?php renderFoot(); ?>
