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

$msg = $err = '';

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

    if ($action === 'approve') {
        $pdo->prepare("UPDATE lawyer_profiles SET review_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]);
        createNotification($lawyerId,'doc_approved','تم قبول حسابك','تهانينا! تم قبول وثائقك والموافقة على حسابك. يمكنك الآن استخدام المنصة كاملاً.');
        $msg = 'تم قبول حساب المحامي بنجاح';
        auditLog($user['id'],'approve_lawyer','users',$lawyerId,'قبول محامي');
    } elseif ($action === 'reject') {
        $pdo->prepare("UPDATE lawyer_profiles SET review_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]);
        createNotification($lawyerId,'doc_rejected','تم رفض وثائقك',"عذراً، تم رفض وثائقك. السبب: $reason. يمكنك إعادة رفع الوثائق.");
        $msg = 'تم رفض حساب المحامي مع إشعاره';
        auditLog($user['id'],'reject_lawyer','users',$lawyerId,'رفض محامي: '.$reason);
    }
}

// Get all lawyers
$filterStatus = $_GET['status'] ?? '';
$whereSQL = $filterStatus ? "AND lp.review_status=?" : "";
$params = $filterStatus ? [$filterStatus] : [];
$stmt = $pdo->prepare("SELECT u.*,lp.bar_number,lp.bar_association,lp.specialization,lp.review_status,lp.rejection_reason,lp.professional_card,lp.accreditation_doc,lp.submission_count,lp.reviewed_at FROM users u JOIN lawyer_profiles lp ON u.id=lp.user_id WHERE u.role='lawyer' $whereSQL ORDER BY u.created_at DESC");
$stmt->execute($params);
$lawyers = $stmt->fetchAll();
$notifCount = getUnreadNotifCount($user['id']);
renderHead('مراجعة المحامين');
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('lawyers','admin'); ?></div>
<div class="sidebar-overlay" id="sidebarOverlay"></div>
<div class="main-wrap">
<?php renderTopbar('مراجعة طلبات المحامين', $notifCount); ?>
<div class="page-content">

  <?php if ($msg): ?><div class="alert alert-success alert-dismissible mb-3"><i class="bi bi-check-circle-fill me-2"></i><?= htmlspecialchars($msg) ?> <button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

  <!-- Filter tabs -->
  <div class="d-flex gap-2 mb-3 flex-wrap">
    <?php foreach ([''=>'الكل','pending'=>'في الانتظار','under_review'=>'قيد المراجعة','approved'=>'مقبول','rejected'=>'مرفوض'] as $k=>$v):
      $active = ($filterStatus===$k) ? 'btn-navy' : 'btn-outline-secondary';
    ?>
    <a href="?status=<?= $k ?>" class="btn btn-sm <?= $active ?>"><?= $v ?> <?php
      $cnt = $pdo->prepare("SELECT COUNT(*) FROM lawyer_profiles WHERE review_status " . ($k ? "='$k'" : "IS NOT NULL"));
      $cnt->execute(); echo "({$cnt->fetchColumn()})";
    ?></a>
    <?php endforeach; ?>
  </div>

  <div class="panel">
    <div class="table-responsive">
      <table class="table dt-table">
        <thead><tr><th>المحامي</th><th>رقم البطاقة</th><th>الهيئة</th><th>التخصص</th><th>الوثائق</th><th>الحالة</th><th>تاريخ التسجيل</th><th>الإجراءات</th></tr></thead>
        <tbody>
        <?php foreach ($lawyers as $lw):
          $rStat=['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><div style="font-size:11px;color:var(--text-muted)"><?= htmlspecialchars($lw['phone']??'') ?></div></td>
          <td><?= htmlspecialchars($lw['bar_number']??'—') ?></td>
          <td><?= htmlspecialchars($lw['bar_association']??'—') ?></td>
          <td><?= htmlspecialchars($lw['specialization']??'—') ?></td>
          <td>
            <?php if ($lw['professional_card']): ?><a href="../../public/assets/uploads/<?= htmlspecialchars($lw['professional_card']) ?>" target="_blank" class="btn btn-sm btn-outline-secondary mb-1"><i class="bi bi-file-earmark"></i> البطاقة</a><?php else: ?><span class="text-muted" style="font-size:12px">لم ترفع</span><?php endif; ?>
            <?php if ($lw['accreditation_doc']): ?><a href="../../public/assets/uploads/<?= htmlspecialchars($lw['accreditation_doc']) ?>" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="bi bi-file-earmark"></i> الاعتماد</a><?php endif; ?>
          </td>
          <td><span class="badge bg-<?= $rStat[1] ?>"><?= $rStat[0] ?></span></td>
          <td><?= date('d/m/Y',strtotime($lw['created_at'])) ?></td>
          <td>
            <?php if ($lw['review_status'] !== 'approved'): ?>
            <div class="d-flex gap-1">
              <button class="action-btn success" title="قبول" onclick="approveModal(<?= $lw['id'] ?>, '<?= htmlspecialchars(addslashes($lw['full_name'])) ?>')"><i class="bi bi-check-circle"></i></button>
              <button class="action-btn danger" title="رفض" onclick="rejectModal(<?= $lw['id'] ?>, '<?= htmlspecialchars(addslashes($lw['full_name'])) ?>')"><i class="bi bi-x-circle"></i></button>
            </div>
            <?php else: ?>
            <span class="badge bg-success">مكتمل</span>
            <?php endif; ?>
            <?php if ($lw['rejection_reason']): ?>
            <div style="font-size:11px;color:var(--danger);margin-top:4px" title="<?= htmlspecialchars($lw['rejection_reason']) ?>"><i class="bi bi-info-circle"></i> سبب الرفض</div>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div></div>

<!-- Approve Modal -->
<div class="modal fade" id="approveModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title font-amiri">قبول حساب المحامي</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST">
      <div class="modal-body">
        <input type="hidden" name="lawyer_id" id="approveLawyerId">
        <input type="hidden" name="action" value="approve">
        <div class="alert alert-gold"><i class="bi bi-info-circle me-2"></i>هل تريد قبول حساب المحامي <strong id="approveName"></strong>؟ سيتم إشعاره تلقائياً.</div>
      </div>
      <div class="modal-footer border-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button><button type="submit" class="btn btn-gold"><i class="bi bi-check-circle"></i> قبول</button></div>
    </form>
  </div></div>
</div>

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1">
  <div class="modal-dialog"><div class="modal-content">
    <div class="modal-header border-0 pb-0"><h5 class="modal-title font-amiri">رفض حساب المحامي</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <form method="POST">
      <div class="modal-body">
        <input type="hidden" name="lawyer_id" id="rejectLawyerId">
        <input type="hidden" name="action" value="reject">
        <p>سيتم رفض حساب المحامي <strong id="rejectName"></strong> وإشعاره بسبب الرفض.</p>
        <label class="form-label">سبب الرفض <span class="text-danger">*</span></label>
        <textarea name="rejection_reason" class="form-control" rows="3" placeholder="اذكر سبب الرفض بوضوح..." required></textarea>
      </div>
      <div class="modal-footer border-0"><button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button><button type="submit" class="btn btn-danger"><i class="bi bi-x-circle"></i> رفض</button></div>
    </form>
  </div></div>
</div>

<script>
function approveModal(id, name) {
  document.getElementById('approveLawyerId').value = id;
  document.getElementById('approveName').textContent = name;
  new bootstrap.Modal(document.getElementById('approveModal')).show();
}
function rejectModal(id, name) {
  document.getElementById('rejectLawyerId').value = id;
  document.getElementById('rejectName').textContent = name;
  new bootstrap.Modal(document.getElementById('rejectModal')).show();
}
</script>
<?php renderFoot(); ?>
