<?php
// ============================================================
// admin/lawyers.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();
$flash = null;

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action   = $_POST['action'] ?? '';
    $lawyerId = (int)($_POST['lawyer_id'] ?? 0);
    $reason   = trim($_POST['reason'] ?? '');

    if ($action === 'approve' && $lawyerId) {
        $pdo->prepare("UPDATE lawyer_profiles SET verification_status='approved', reviewed_by=?, reviewed_at=NOW()
                        WHERE user_id=?")->execute([$user['id'], $lawyerId]);
        $pdo->prepare("UPDATE users SET status='active' WHERE id=?")->execute([$lawyerId]);
        sendNotification($pdo, $lawyerId, 'تمت الموافقة على حسابك', 'تهانينا! تمت مراجعة وثائقك والموافقة على حسابك. يمكنك الآن تسجيل الدخول.', 'success');
        setFlash('success', 'تمت الموافقة على حساب المحامي بنجاح');

    } elseif ($action === 'reject' && $lawyerId && $reason) {
        $pdo->prepare("UPDATE lawyer_profiles SET verification_status='rejected', rejection_reason=?, reviewed_by=?, reviewed_at=NOW()
                        WHERE user_id=?")->execute([$reason, $user['id'], $lawyerId]);
        $pdo->prepare("UPDATE users SET status='rejected' WHERE id=?")->execute([$lawyerId]);
        sendNotification($pdo, $lawyerId, 'تم رفض طلبك', 'نأسف، تم رفض طلب تسجيلك. السبب: ' . $reason . '. يمكنك إعادة رفع الوثائق.', 'danger');
        setFlash('danger', 'تم رفض حساب المحامي');
    }
    header("Location: lawyers.php");
    exit;
}

$flash = getFlash();

// Filter
$filter = $_GET['filter'] ?? 'under_review';
$search = trim($_GET['q'] ?? '');

$where  = "WHERE 1=1";
$params = [];

if ($filter !== 'all') {
    $where .= " AND lp.verification_status = ?";
    $params[] = $filter;
}
if ($search) {
    $where .= " AND (u.full_name LIKE ? OR u.email LIKE ? OR lp.bar_number LIKE ?)";
    $s = "%$search%";
    $params[] = $s; $params[] = $s; $params[] = $s;
}

$stmt = $pdo->prepare("
    SELECT u.id, u.full_name, u.email, u.phone, u.created_at, u.status,
           lp.verification_status, lp.bar_number, lp.bar_region, lp.specialization,
           lp.professional_card_path, lp.accreditation_path, lp.id_card_path,
           lp.rejection_reason, lp.reviewed_at,
           r.full_name AS reviewer_name
    FROM lawyer_profiles lp
    JOIN users u ON u.id = lp.user_id
    LEFT JOIN users r ON r.id = lp.reviewed_by
    $where
    ORDER BY lp.verification_status ASC, u.created_at DESC
");
$stmt->execute($params);
$lawyers = $stmt->fetchAll();

// Counts
$counts = $pdo->query("
    SELECT verification_status, COUNT(*) AS cnt FROM lawyer_profiles GROUP BY verification_status
")->fetchAll(PDO::FETCH_KEY_PAIR);

// Selected for review
$reviewId = (int)($_GET['review'] ?? 0);
$reviewLawyer = null;
if ($reviewId) {
    $stmt2 = $pdo->prepare("
        SELECT u.*, lp.* FROM lawyer_profiles lp JOIN users u ON u.id = lp.user_id WHERE lp.user_id = ?
    ");
    $stmt2->execute([$reviewId]);
    $reviewLawyer = $stmt2->fetch();
}
?>
<!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"><a href="index.php">الرئيسية</a> <span>›</span> <span>المحامون</span></div>
      <div class="page-title">
        <div class="title-icon"><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"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg></div>
        إدارة ومراجعة المحامين
      </div>
    </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; ?>

    <!-- Filter Tabs -->
    <div style="display:flex; gap:10px; margin-bottom:20px; flex-wrap:wrap;">
      <?php
      $tabs = [
        'under_review'  => ['قيد المراجعة', 'warning'],
        'approved'      => ['مقبولون', 'success'],
        'rejected'      => ['مرفوضون', 'danger'],
        'pending_upload'=> ['لم يرفعوا الوثائق', 'secondary'],
        'all'           => ['الكل', 'info'],
      ];
      foreach ($tabs as $key => [$label, $cls]):
        $cnt = $counts[$key] ?? 0;
      ?>
      <a href="?filter=<?= $key ?><?= $search ? '&q='.urlencode($search) : '' ?>"
         class="btn <?= $filter === $key ? 'btn-primary' : 'btn-outline' ?> btn-sm">
        <?= $label ?>
        <?php if ($cnt > 0): ?><span class="badge badge-<?= $cls ?>" style="margin-right:6px"><?= $cnt ?></span><?php endif; ?>
      </a>
      <?php endforeach; ?>
    </div>

    <!-- Search -->
    <div class="filter-bar">
      <form method="GET" style="display:flex;gap:10px;flex:1;">
        <input type="hidden" name="filter" value="<?= clean($filter) ?>">
        <div class="search-box" style="flex:1;">
          <div class="search-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg></div>
          <input type="text" name="q" class="form-control" placeholder="بحث بالاسم أو البريد أو رقم النقابة..." value="<?= clean($search) ?>">
        </div>
        <button type="submit" class="btn btn-primary">بحث</button>
        <?php if ($search): ?><a href="?filter=<?= $filter ?>" class="btn btn-outline">مسح</a><?php endif; ?>
      </form>
    </div>

    <!-- Lawyers Table -->
    <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>
          قائمة المحامين (<?= count($lawyers) ?>)
        </div>
        <button onclick="exportTableCSV('lawyersTable','محامون')" class="btn btn-outline btn-sm">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg>
          تصدير CSV
        </button>
      </div>
      <div class="table-responsive">
        <table class="table" id="lawyersTable">
          <thead>
            <tr>
              <th>المحامي</th>
              <th>رقم النقابة</th>
              <th>مجلس القضاء</th>
              <th>التخصص</th>
              <th>الوثائق</th>
              <th>الحالة</th>
              <th>تاريخ التسجيل</th>
              <th>الإجراء</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($lawyers): foreach ($lawyers as $l): ?>
            <?php $lStatus = lawyerStatusLabel($l['verification_status']); ?>
            <tr>
              <td>
                <div style="font-weight:600;color:var(--navy-800)"><?= clean($l['full_name']) ?></div>
                <div style="font-size:.75rem;color:var(--slate-400)"><?= clean($l['email']) ?></div>
              </td>
              <td class="fs-sm"><?= clean($l['bar_number'] ?? '—') ?></td>
              <td class="fs-sm"><?= clean($l['bar_region'] ?? '—') ?></td>
              <td class="fs-sm"><?= clean($l['specialization'] ?? '—') ?></td>
              <td>
                <div style="display:flex;gap:6px;flex-wrap:wrap;">
                  <?php if ($l['professional_card_path']): ?>
                  <a href="../assets/uploads/lawyers/<?= clean($l['professional_card_path']) ?>" target="_blank"
                     class="badge badge-info" title="البطاقة المهنية">بطاقة مهنية</a>
                  <?php endif; ?>
                  <?php if ($l['accreditation_path']): ?>
                  <a href="../assets/uploads/lawyers/<?= clean($l['accreditation_path']) ?>" target="_blank"
                     class="badge badge-primary" title="الاعتماد">اعتماد</a>
                  <?php endif; ?>
                  <?php if ($l['id_card_path']): ?>
                  <a href="../assets/uploads/lawyers/<?= clean($l['id_card_path']) ?>" target="_blank"
                     class="badge badge-secondary" title="بطاقة الهوية">هوية</a>
                  <?php endif; ?>
                  <?php if (!$l['professional_card_path'] && !$l['accreditation_path']): ?>
                  <span class="badge badge-secondary">لا وثائق</span>
                  <?php endif; ?>
                </div>
              </td>
              <td><span class="badge <?= $lStatus['class'] ?>"><?= $lStatus['label'] ?></span></td>
              <td class="fs-sm text-muted"><?= formatDateAr($l['created_at']) ?></td>
              <td>
                <?php if ($l['verification_status'] === 'under_review'): ?>
                <a href="?filter=<?= $filter ?>&review=<?= $l['id'] ?>" class="btn btn-gold btn-sm">مراجعة</a>
                <?php elseif ($l['verification_status'] === 'approved'): ?>
                <span class="text-muted fs-sm">✓ مقبول</span>
                <?php elseif ($l['verification_status'] === 'rejected'): ?>
                <a href="?filter=<?= $filter ?>&review=<?= $l['id'] ?>" class="btn btn-outline btn-sm">عرض</a>
                <?php else: ?>
                <span class="text-muted fs-sm">بانتظار الوثائق</span>
                <?php endif; ?>
              </td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="8">
              <div class="empty-state" style="padding:30px">
                <div class="empty-icon">👨‍⚖️</div>
                <h3>لا يوجد محامون <?= $filter !== 'all' ? 'في هذه الحالة' : '' ?></h3>
              </div>
            </td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Review Modal -->
<?php if ($reviewLawyer): ?>
<div class="modal-overlay open" id="reviewModal">
  <div class="modal" style="max-width:640px;">
    <div class="modal-header">
      <span class="modal-title">مراجعة ملف المحامي: <?= clean($reviewLawyer['full_name']) ?></span>
      <a href="lawyers.php?filter=<?= $filter ?>" class="modal-close">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </a>
    </div>
    <div class="modal-body">
      <!-- Info -->
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:20px;background:var(--slate-100);padding:16px;border-radius:var(--radius-md);">
        <div><div class="fs-sm text-muted">الاسم الكامل</div><div class="fw-bold"><?= clean($reviewLawyer['full_name']) ?></div></div>
        <div><div class="fs-sm text-muted">البريد</div><div><?= clean($reviewLawyer['email']) ?></div></div>
        <div><div class="fs-sm text-muted">رقم النقابة</div><div><?= clean($reviewLawyer['bar_number'] ?? '—') ?></div></div>
        <div><div class="fs-sm text-muted">مجلس القضاء</div><div><?= clean($reviewLawyer['bar_region'] ?? '—') ?></div></div>
        <div><div class="fs-sm text-muted">التخصص</div><div><?= clean($reviewLawyer['specialization'] ?? '—') ?></div></div>
        <div><div class="fs-sm text-muted">الهاتف</div><div><?= clean($reviewLawyer['phone'] ?? '—') ?></div></div>
      </div>

      <!-- Documents -->
      <h4 style="font-size:.9rem;font-weight:700;margin-bottom:12px;color:var(--navy-800)">الوثائق المرفوعة</h4>
      <div style="display:flex;flex-direction:column;gap:10px;margin-bottom:20px;">
        <?php
        $docs = [
            'البطاقة المهنية' => $reviewLawyer['professional_card_path'],
            'شهادة الاعتماد'  => $reviewLawyer['accreditation_path'],
            'بطاقة الهوية'    => $reviewLawyer['id_card_path'],
        ];
        foreach ($docs as $label => $path): ?>
        <div class="doc-card">
          <div class="doc-icon">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
          </div>
          <div style="flex:1">
            <div class="doc-name"><?= $label ?></div>
            <div class="doc-size"><?= $path ? 'تم الرفع' : 'لم يتم الرفع' ?></div>
          </div>
          <?php if ($path): ?>
          <a href="../assets/uploads/lawyers/<?= clean($path) ?>" target="_blank" class="btn btn-outline btn-sm">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
            عرض
          </a>
          <?php else: ?>
          <span class="badge badge-danger">مفقود</span>
          <?php endif; ?>
        </div>
        <?php endforeach; ?>
      </div>

      <?php if ($reviewLawyer['verification_status'] === 'rejected' && $reviewLawyer['rejection_reason']): ?>
      <div class="alert alert-danger">سبب الرفض السابق: <?= clean($reviewLawyer['rejection_reason']) ?></div>
      <?php endif; ?>

      <?php if ($reviewLawyer['verification_status'] === 'under_review'): ?>
      <!-- Decision -->
      <div style="display:flex;gap:12px;">
        <form method="POST" style="flex:1;">
          <input type="hidden" name="lawyer_id" value="<?= $reviewLawyer['id'] ?>">
          <input type="hidden" name="action" value="approve">
          <button type="submit" class="btn btn-success w-100"
                  data-confirm="هل تريد الموافقة على هذا المحامي؟">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M20 6L9 17l-5-5"/></svg>
            موافقة
          </button>
        </form>
        <button onclick="openModal('rejectModal')" class="btn btn-danger" style="flex:1;">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          رفض
        </button>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Reject Modal -->
<div class="modal-overlay" id="rejectModal">
  <div class="modal" style="max-width:440px;">
    <div class="modal-header">
      <span class="modal-title">رفض الطلب</span>
      <button class="modal-close" onclick="closeModal('rejectModal')">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20" height="20"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
    </div>
    <form method="POST">
      <div class="modal-body">
        <input type="hidden" name="lawyer_id" value="<?= $reviewLawyer['id'] ?>">
        <input type="hidden" name="action" value="reject">
        <div class="form-group">
          <label class="form-label">سبب الرفض <span class="required">*</span></label>
          <textarea name="reason" class="form-control" rows="4" required
                    placeholder="مثال: الوثائق المرفوعة غير واضحة أو منتهية الصلاحية..."></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-danger">تأكيد الرفض</button>
        <button type="button" class="btn btn-outline" onclick="closeModal('rejectModal')">إلغاء</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<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>
