<?php
// ============================================================
// admin/index.php - لوحة تحكم المدير
// ============================================================
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';

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

$user = currentUser();

// Stats
$stats = [];
$stats['total_cases']    = $pdo->query("SELECT COUNT(*) FROM cases")->fetchColumn();
$stats['active_cases']   = $pdo->query("SELECT COUNT(*) FROM cases WHERE status='active'")->fetchColumn();
$stats['today_sessions'] = $pdo->query("SELECT COUNT(*) FROM sessions WHERE session_date = CURDATE()")->fetchColumn();
$stats['pending_lawyers']= $pdo->query("SELECT COUNT(*) FROM lawyer_profiles WHERE verification_status='under_review'")->fetchColumn();
$stats['total_lawyers']  = $pdo->query("SELECT COUNT(*) FROM users WHERE role='lawyer'")->fetchColumn();
$stats['total_clerks']   = $pdo->query("SELECT COUNT(*) FROM users WHERE role='clerk'")->fetchColumn();

// Recent cases
$recentCases = $pdo->query("
    SELECT c.*, u.full_name AS clerk_name
    FROM cases c
    JOIN users u ON u.id = c.assigned_clerk_id
    ORDER BY c.created_at DESC LIMIT 8
")->fetchAll();

// Pending lawyers
$pendingLawyers = $pdo->query("
    SELECT u.full_name, u.email, lp.verification_status, u.created_at, lp.user_id
    FROM lawyer_profiles lp JOIN users u ON u.id = lp.user_id
    WHERE lp.verification_status = 'under_review'
    LIMIT 5
")->fetchAll();

// Monthly cases chart data
$monthlyData = $pdo->query("
    SELECT DATE_FORMAT(created_at, '%Y-%m') AS month, COUNT(*) AS cnt
    FROM cases
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
    GROUP BY month ORDER BY month
")->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">
      <span class="text-muted fs-sm">اليوم: <?= formatDateAr(date('Y-m-d')) ?></span>
    </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['total_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(--amber-500); --icon-bg: var(--amber-100);">
        <div class="stat-icon"><svg viewBox="0 0 24 24" fill="none" stroke="#92400E" stroke-width="2"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg></div>
        <div>
          <div class="stat-value"><?= $stats['total_lawyers'] ?></div>
          <div class="stat-label">المحامون المسجلون</div>
          <?php if ($stats['pending_lawyers'] > 0): ?>
          <div class="stat-change up">⚠ <?= $stats['pending_lawyers'] ?> قيد المراجعة</div>
          <?php endif; ?>
        </div>
      </div>
    </div>

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

      <!-- 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.php" class="btn btn-outline btn-sm">عرض الكل</a>
        </div>
        <div class="table-responsive">
          <table class="table" id="casesTable">
            <thead>
              <tr>
                <th>رقم الملف</th>
                <th>عنوان القضية</th>
                <th>النوع</th>
                <th>المرحلة</th>
                <th>الحالة</th>
                <th>تاريخ الفتح</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($recentCases): foreach ($recentCases as $c): ?>
              <tr>
                <td><span class="case-num"><?= clean($c['case_number']) ?></span></td>
                <td><?= clean($c['title']) ?></td>
                <td><?= caseTypeLabel($c['case_type']) ?></td>
                <td><?php $s=caseStageLabel($c['stage']); ?><span class="badge <?= $s['class'] ?>"><?= $s['label'] ?></span></td>
                <td><?php $st=caseStatusLabel($c['status']); ?><span class="badge <?= $st['class'] ?>"><?= $st['label'] ?></span></td>
                <td class="fs-sm text-muted"><?= formatDateAr($c['created_at']) ?></td>
              </tr>
              <?php endforeach; else: ?>
              <tr><td colspan="6" class="text-center text-muted" style="padding:30px">لا توجد قضايا مسجلة بعد</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Pending Lawyers -->
      <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"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
              محامون قيد المراجعة
            </div>
            <a href="lawyers.php" class="btn btn-outline btn-sm">الكل</a>
          </div>
          <div class="card-body" style="padding:12px;">
            <?php if ($pendingLawyers): foreach ($pendingLawyers as $l): ?>
            <div style="display:flex; align-items:center; gap:12px; padding:10px 8px; border-bottom:1px solid var(--slate-200);">
              <div class="user-avatar" style="width:36px;height:36px;font-size:.85rem;"><?= mb_substr($l['full_name'], 0, 1) ?></div>
              <div style="flex:1;">
                <div style="font-size:.85rem;font-weight:600;color:var(--navy-800)"><?= clean($l['full_name']) ?></div>
                <div style="font-size:.73rem;color:var(--slate-400)"><?= clean($l['email']) ?></div>
              </div>
              <a href="lawyers.php?review=<?= $l['user_id'] ?>" class="btn btn-gold btn-sm">مراجعة</a>
            </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="create_clerk.php" class="btn btn-primary">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M16 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg>
              إنشاء حساب أمين ضبط
            </a>
            <a href="lawyers.php" class="btn btn-outline">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></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>
