<?php
// ============================================================
// clerk/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'];

// Stats for this clerk
$stats['my_cases']      = $pdo->prepare("SELECT COUNT(*) FROM cases WHERE assigned_clerk_id=?")->execute([$uid]) ? $pdo->query("SELECT COUNT(*) FROM cases WHERE assigned_clerk_id=$uid")->fetchColumn() : 0;
$stats['active_cases']  = $pdo->query("SELECT COUNT(*) FROM cases WHERE assigned_clerk_id=$uid AND status='active'")->fetchColumn();
$stats['today_sessions']= $pdo->query("SELECT COUNT(*) FROM sessions s JOIN cases c ON c.id=s.case_id WHERE c.assigned_clerk_id=$uid AND s.session_date=CURDATE()")->fetchColumn();
$stats['pending_sessions']= $pdo->query("SELECT COUNT(*) FROM sessions s JOIN cases c ON c.id=s.case_id WHERE c.assigned_clerk_id=$uid AND s.status='scheduled'")->fetchColumn();

// Today's sessions
$todaySessions = $pdo->prepare("
    SELECT s.*, c.case_number, c.title AS case_title, c.plaintiff, c.defendant
    FROM sessions s JOIN cases c ON c.id = s.case_id
    WHERE c.assigned_clerk_id = ? AND s.session_date = CURDATE()
    ORDER BY s.session_time ASC
");
$todaySessions->execute([$uid]);
$todaySessions = $todaySessions->fetchAll();

// Recent cases
$recentCases = $pdo->prepare("
    SELECT c.*,
           pl.full_name AS plaintiff_lawyer_name,
           dl.full_name AS defendant_lawyer_name
    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 c.assigned_clerk_id = ?
    ORDER BY c.updated_at DESC LIMIT 8
");
$recentCases->execute([$uid]);
$recentCases = $recentCases->fetchAll();

// Upcoming sessions (next 7 days)
$upcomingSessions = $pdo->prepare("
    SELECT s.*, c.case_number, c.title AS case_title
    FROM sessions s JOIN cases c ON c.id = s.case_id
    WHERE c.assigned_clerk_id = ? AND s.session_date > CURDATE()
      AND s.session_date <= DATE_ADD(CURDATE(), INTERVAL 7 DAY)
      AND s.status = 'scheduled'
    ORDER BY s.session_date, s.session_time
    LIMIT 6
");
$upcomingSessions->execute([$uid]);
$upcomingSessions = $upcomingSessions->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"><span>الرئيسية</span></div>
      <div class="page-title">
        <div class="title-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg></div>
        لوحة تحكم أمين الضبط
      </div>
    </div>
    <div class="header-actions">
      <a href="cases/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>

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

    <!-- Stats -->
    <div class="stats-grid">
      <div class="stat-card" style="--accent-color:var(--navy-500);--icon-bg:#E0E7FF;">
        <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="#3730A3" 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 class="stat-value"><?= $stats['my_cases'] ?></div>
          <div class="stat-label">إجمالي قضاياي</div>
        </div>
      </div>
      <div class="stat-card" style="--accent-color:var(--green-500);--icon-bg:var(--green-100);">
        <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="#15803D" stroke-width="2"><path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg></div>
        <div>
          <div class="stat-value"><?= $stats['active_cases'] ?></div>
          <div class="stat-label">القضايا النشطة</div>
        </div>
      </div>
      <div class="stat-card" style="--accent-color:var(--gold-500);--icon-bg:var(--gold-100);">
        <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="#92400E" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg></div>
        <div>
          <div class="stat-value"><?= $stats['today_sessions'] ?></div>
          <div class="stat-label">جلسات اليوم</div>
        </div>
      </div>
      <div class="stat-card" style="--accent-color:var(--blue-500);--icon-bg:var(--blue-100);">
        <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="#1D4ED8" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg></div>
        <div>
          <div class="stat-value"><?= $stats['pending_sessions'] ?></div>
          <div class="stat-label">جلسات مجدولة</div>
        </div>
      </div>
    </div>

    <!-- Main Grid -->
    <div style="display:grid;grid-template-columns:1fr 340px;gap:24px;">

      <!-- Today's Sessions -->
      <div>
        <div class="card" style="margin-bottom:24px;">
          <div class="card-header">
            <div class="card-title">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
              جلسات اليوم — <?= formatDateAr(date('Y-m-d')) ?>
            </div>
            <a href="sessions/index.php" class="btn btn-outline btn-sm">جميع الجلسات</a>
          </div>
          <?php if ($todaySessions): ?>
          <div class="table-responsive">
            <table class="table">
              <thead><tr><th>القضية</th><th>الوقت</th><th>القاعة</th><th>الحالة</th><th></th></tr></thead>
              <tbody>
                <?php foreach ($todaySessions as $s): ?>
                <?php $ss = sessionStatusLabel($s['status']); ?>
                <tr>
                  <td>
                    <div class="case-num"><?= clean($s['case_number']) ?></div>
                    <div class="fs-sm text-muted"><?= clean($s['case_title']) ?></div>
                  </td>
                  <td class="fw-bold text-gold"><?= substr($s['session_time'], 0, 5) ?></td>
                  <td class="fs-sm"><?= clean($s['room'] ?? '—') ?></td>
                  <td><span class="badge <?= $ss['class'] ?>"><?= $ss['label'] ?></span></td>
                  <td>
                    <a href="sessions/view.php?id=<?= $s['id'] ?>" class="btn btn-primary btn-sm">إدارة</a>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
          <?php else: ?>
          <div class="empty-state" style="padding:30px">
            <div class="empty-icon">📅</div>
            <h3>لا توجد جلسات اليوم</h3>
          </div>
          <?php endif; ?>
        </div>

        <!-- Recent Cases -->
        <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>
              القضايا الأخيرة
            </div>
            <a href="cases/index.php" class="btn btn-outline btn-sm">عرض الكل</a>
          </div>
          <div class="table-responsive">
            <table class="table">
              <thead><tr><th>رقم الملف</th><th>القضية</th><th>النوع</th><th>المرحلة</th><th>الحالة</th><th></th></tr></thead>
              <tbody>
                <?php if ($recentCases): foreach ($recentCases as $c): ?>
                <?php $cs=caseStatusLabel($c['status']); $cst=caseStageLabel($c['stage']); ?>
                <tr>
                  <td><span class="case-num"><?= clean($c['case_number']) ?></span></td>
                  <td>
                    <div class="fw-bold fs-sm"><?= clean($c['title']) ?></div>
                    <div class="fs-sm text-muted"><?= clean($c['plaintiff']) ?> ضد <?= clean($c['defendant']) ?></div>
                  </td>
                  <td class="fs-sm"><?= caseTypeLabel($c['case_type']) ?></td>
                  <td><span class="badge <?= $cst['class'] ?>"><?= $cst['label'] ?></span></td>
                  <td><span class="badge <?= $cs['class'] ?>"><?= $cs['label'] ?></span></td>
                  <td><a href="cases/view.php?id=<?= $c['id'] ?>" class="btn btn-outline btn-sm">عرض</a></td>
                </tr>
                <?php endforeach; else: ?>
                <tr><td colspan="6" class="text-center text-muted" style="padding:24px">لا توجد قضايا</td></tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Sidebar: Upcoming Sessions & Quick Actions -->
      <div style="display:flex;flex-direction:column;gap:20px;">
        <div class="card">
          <div class="card-header">
            <div class="card-title">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
              الجلسات القادمة (7 أيام)
            </div>
          </div>
          <div style="padding:12px;">
            <?php if ($upcomingSessions): foreach ($upcomingSessions as $s): ?>
            <div style="padding:10px;border-bottom:1px solid var(--slate-200);">
              <div style="display:flex;justify-content:space-between;align-items:center;">
                <span class="case-num fs-sm"><?= clean($s['case_number']) ?></span>
                <span style="background:var(--gold-100);color:var(--gold-500);font-size:.72rem;font-weight:700;padding:2px 8px;border-radius:20px;">
                  <?= formatDateAr($s['session_date']) ?>
                </span>
              </div>
              <div class="fs-sm text-muted mt-1"><?= clean($s['case_title']) ?></div>
              <div class="fs-sm fw-bold text-navy mt-1"><?= substr($s['session_time'],0,5) ?> — <?= clean($s['room'] ?? 'القاعة الرئيسية') ?></div>
            </div>
            <?php endforeach; else: ?>
            <div class="empty-state" style="padding:20px">
              <div class="empty-icon">📋</div>
              <p>لا توجد جلسات قادمة</p>
            </div>
            <?php endif; ?>
          </div>
        </div>

        <!-- Quick Actions -->
        <div class="card">
          <div class="card-header"><div class="card-title">إجراءات سريعة</div></div>
          <div class="card-body" style="display:flex;flex-direction:column;gap:10px;">
            <a href="cases/new.php" class="btn btn-primary">
              <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>
            <a href="sessions/new.php" class="btn btn-outline">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/></svg>
              جدولة جلسة جديدة
            </a>
            <a href="reports.php" class="btn btn-outline">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>
              التقارير
            </a>
          </div>
        </div>
      </div>
    </div>
  </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>
<script src="../public/assets/js/i18n.js"></script>
<script>if(typeof initI18n==="function") document.addEventListener("DOMContentLoaded", initI18n);</script>
</body>
</html>
