<?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_ADMIN);
$GLOBALS['BASE_URL_CSS'] = BASE_URL . '/public/assets/css/main.css';
$user = currentUser(); $pdo = db();

$totalUsers   = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$pendingLawyers=(int)$pdo->query("SELECT COUNT(*) FROM lawyer_profiles WHERE review_status IN ('pending','under_review')")->fetchColumn();
$totalCases   = (int)$pdo->query("SELECT COUNT(*) FROM cases")->fetchColumn();
$totalSessions= (int)$pdo->query("SELECT COUNT(*) FROM sessions")->fetchColumn();

$pendingList = $pdo->query("SELECT u.*,lp.bar_number,lp.bar_association,lp.review_status,lp.submission_count FROM users u JOIN lawyer_profiles lp ON u.id=lp.user_id WHERE lp.review_status IN ('pending','under_review') ORDER BY u.created_at DESC LIMIT 5")->fetchAll();
$recentAudit = $pdo->query("SELECT al.*,u.full_name FROM audit_log al LEFT JOIN users u ON al.user_id=u.id ORDER BY al.created_at DESC LIMIT 10")->fetchAll();

$notifCount = getUnreadNotifCount($user['id']);
renderHead('لوحة تحكم المدير');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('dashboard','admin'); ?></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 text-navy">مرحباً، <?= htmlspecialchars($user['name']) ?></h4><p class="text-muted mb-0" style="font-size:13px">إدارة النظام والمستخدمين</p></div>
    <a href="lawyers.php" class="btn btn-gold position-relative">
      <i class="bi bi-person-check"></i> مراجعة المحامين
      <?php if ($pendingLawyers > 0): ?><span class="position-absolute top-0 start-0 translate-middle badge rounded-pill bg-danger"><?= $pendingLawyers ?></span><?php endif; ?>
    </a>
  </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-people"></i></div><div class="stat-body"><div class="stat-value"><?= $totalUsers ?></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-person-exclamation"></i></div><div class="stat-body"><div class="stat-value"><?= $pendingLawyers ?></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-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-calendar3"></i></div><div class="stat-body"><div class="stat-value"><?= $totalSessions ?></div><div class="stat-label">إجمالي الجلسات</div></div></div></div>
  </div>

  <div class="row g-3">
    <!-- Pending lawyers -->
    <div class="col-lg-7">
      <div class="panel">
        <div class="panel-header">
          <div class="panel-title"><i class="bi bi-person-check"></i> طلبات المحامين المعلقة</div>
          <a href="lawyers.php" class="btn btn-sm btn-outline-gold">عرض الكل</a>
        </div>
        <?php if (empty($pendingList)): ?>
        <div class="empty-state py-4"><i class="bi bi-person-check"></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 ($pendingList as $lw):
            $sts=['pending'=>['في الانتظار','warning'],'under_review'=>['قيد المراجعة','info'],'approved'=>['مقبول','success'],'rejected'=>['مرفوض','danger']][$lw['review_status']]??[$lw['review_status'],'secondary'];
          ?>
          <tr>
            <td><strong><?= htmlspecialchars($lw['full_name']) ?></strong><div style="font-size:11px;color:var(--text-muted)"><?= htmlspecialchars($lw['email']) ?></div></td>
            <td><?= htmlspecialchars($lw['bar_number']??'—') ?></td>
            <td style="font-size:12px"><?= htmlspecialchars($lw['bar_association']??'—') ?></td>
            <td><span class="badge bg-<?= $sts[1] ?>"><?= $sts[0] ?></span></td>
            <td><a href="lawyers.php?review=<?= $lw['id'] ?>" class="btn btn-sm btn-gold"><i class="bi bi-eye"></i> مراجعة</a></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table></div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Audit log -->
    <div class="col-lg-5">
      <div class="panel">
        <div class="panel-header"><div class="panel-title"><i class="bi bi-shield-check"></i> سجل النشاط الأخير</div></div>
        <div style="padding:8px 0;max-height:400px;overflow-y:auto">
          <?php foreach ($recentAudit as $log): ?>
          <div class="d-flex align-items-center gap-3 px-4 py-2 border-bottom">
            <div style="width:8px;height:8px;border-radius:50%;background:var(--gold);flex-shrink:0"></div>
            <div style="flex:1;min-width:0">
              <div style="font-size:12px;font-weight:600"><?= htmlspecialchars($log['description']??$log['action']) ?></div>
              <div style="font-size:11px;color:var(--text-muted)"><?= htmlspecialchars($log['full_name']??'نظام') ?> &bull; <?= date('d/m H:i',strtotime($log['created_at'])) ?></div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      </div>
    </div>
  </div>
</div></div>
<?php renderFoot(); ?>
