<?php
// ============================================================
// modules/admin/profile-requests.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 = '';

// ─── POST: الموافقة أو الرفض ────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $reqId  = (int)($_POST['request_id'] ?? 0);
    $action = $_POST['action'] ?? '';
    $reason = trim($_POST['rejection_reason'] ?? '');

    $req = $pdo->prepare("SELECT pcr.*, u.full_name, u.email FROM profile_change_requests pcr JOIN users u ON u.id=pcr.user_id WHERE pcr.id=? AND pcr.status='pending'");
    $req->execute([$reqId]);
    $req = $req->fetch();

    if (!$req) {
        $err = 'الطلب غير موجود أو تمت معالجته مسبقاً.';
    } elseif ($action === 'approve') {

        // تطبيق التغييرات على جدول lawyer_profiles
        $fieldsMap = [
            'new_bar_number'        => 'bar_number',
            'new_bar_association'   => 'bar_association',
            'new_bar_association_id'=> 'bar_association_id',
            'new_specialization'    => 'specialization',
            'new_professional_card' => 'professional_card',
            'new_accreditation_doc' => 'accreditation_doc',
            'new_id_card'           => 'id_card',
        ];

        $profileUpdates = [];
        foreach ($fieldsMap as $reqCol => $profileCol) {
            if (!empty($req[$reqCol])) {
                $profileUpdates[$profileCol] = $req[$reqCol];
            }
        }

        if ($profileUpdates) {
            $set  = implode(',', array_map(fn($k) => "$k=?", array_keys($profileUpdates)));
            $vals = array_values($profileUpdates);
            $vals[] = $req['user_id'];
            $pdo->prepare("UPDATE lawyer_profiles SET $set WHERE user_id=?")->execute($vals);
        }

        // تحديث حالة الطلب
        $pdo->prepare("UPDATE profile_change_requests SET status='approved', reviewed_by=?, reviewed_at=NOW() WHERE id=?")
            ->execute([$user['id'], $reqId]);

        // إشعار المحامي
        createNotification($req['user_id'], 'profile_change_approved', 'تمت الموافقة على تعديل ملفك',
            'تمت مراجعة طلب تعديل معلوماتك المهنية والموافقة عليه. تحقق من ملفك الشخصي لرؤية التغييرات.',
            BASE_URL . '/modules/lawyer/profile.php');

        auditLog($user['id'], 'approve_profile_change', 'profile_change_requests', $reqId,
            "قبول تعديل ملف المحامي: {$req['full_name']}");

        $msg = "تمت الموافقة على طلب تعديل المحامي {$req['full_name']} وتطبيق التغييرات.";

    } elseif ($action === 'reject') {

        if (empty($reason)) {
            $err = 'يجب ذكر سبب الرفض.';
        } else {
            $pdo->prepare("UPDATE profile_change_requests SET status='rejected', rejection_reason=?, reviewed_by=?, reviewed_at=NOW() WHERE id=?")
                ->execute([$reason, $user['id'], $reqId]);

            createNotification($req['user_id'], 'profile_change_rejected', 'تم رفض طلب تعديل ملفك',
                "تم رفض طلب تعديل معلوماتك المهنية. السبب: {$reason}",
                BASE_URL . '/modules/lawyer/profile.php');

            auditLog($user['id'], 'reject_profile_change', 'profile_change_requests', $reqId,
                "رفض تعديل ملف المحامي: {$req['full_name']}. السبب: $reason");

            $msg = "تم رفض الطلب وإشعار المحامي {$req['full_name']}.";
        }
    }
}

// ─── جلب الطلبات ────────────────────────────────────────────
$filterStatus = $_GET['status'] ?? 'pending';
$whereSQL = $filterStatus ? "AND pcr.status=?" : "";
$params   = $filterStatus ? [$filterStatus] : [];

$stmt = $pdo->prepare("
    SELECT pcr.*, u.full_name, u.email, u.phone,
           lp.bar_number AS current_bar_number,
           lp.bar_association AS current_bar_association,
           lp.specialization AS current_specialization,
           lp.professional_card AS current_professional_card,
           lp.accreditation_doc AS current_accreditation_doc,
           lp.id_card AS current_id_card,
           lp.review_status,
           rev.full_name AS reviewer_name
    FROM profile_change_requests pcr
    JOIN users u ON u.id = pcr.user_id
    LEFT JOIN lawyer_profiles lp ON lp.user_id = pcr.user_id
    LEFT JOIN users rev ON rev.id = pcr.reviewed_by
    WHERE 1=1 $whereSQL
    ORDER BY pcr.created_at DESC
");
$stmt->execute($params);
$requests = $stmt->fetchAll();

// عداد الطلبات
$counts = [];
foreach (['pending', 'approved', 'rejected'] as $s) {
    $c = $pdo->prepare("SELECT COUNT(*) FROM profile_change_requests WHERE status=?");
    $c->execute([$s]);
    $counts[$s] = $c->fetchColumn();
}

$notifCount = getUnreadNotifCount($user['id']);
renderHead('طلبات تعديل الملفات الشخصية');

// أسماء الحقول بالعربية
$fieldLabels = [
    'new_bar_number'        => 'رقم البطاقة المهنية',
    'new_bar_association'   => 'هيئة المحامين',
    'new_specialization'    => 'التخصص',
    'new_professional_card' => 'البطاقة المهنية (وثيقة)',
    'new_accreditation_doc' => 'وثيقة الاعتماد',
    'new_id_card'           => 'بطاقة الهوية',
];
$currentMap = [
    'new_bar_number'        => 'current_bar_number',
    'new_bar_association'   => 'current_bar_association',
    'new_specialization'    => 'current_specialization',
    'new_professional_card' => 'current_professional_card',
    'new_accreditation_doc' => 'current_accreditation_doc',
    'new_id_card'           => 'current_id_card',
];
$docFields = ['new_professional_card', 'new_accreditation_doc', 'new_id_card'];
?>
<div class="sidebar" id="sidebar"><?php buildSidebar('profile-requests', '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; ?>

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

<!-- فلاتر الحالة -->
<div class="d-flex gap-2 mb-3 flex-wrap">
  <?php foreach (['pending' => ['في الانتظار','warning'], 'approved' => ['مقبولة','success'], 'rejected' => ['مرفوضة','danger']] as $s => [$lbl, $cls]): ?>
  <a href="?status=<?= $s ?>" class="btn btn-sm <?= ($filterStatus === $s) ? "btn-{$cls}" : 'btn-outline-secondary' ?>">
    <?= $lbl ?> <span class="badge bg-white text-<?= $cls ?> ms-1"><?= $counts[$s] ?></span>
  </a>
  <?php endforeach; ?>
  <a href="?status=" class="btn btn-sm <?= ($filterStatus === '') ? 'btn-navy' : 'btn-outline-secondary' ?>">
    الكل <span class="badge bg-white text-navy ms-1"><?= array_sum($counts) ?></span>
  </a>
</div>

<?php if (empty($requests)): ?>
<div class="panel">
  <div class="panel-body text-center py-5 text-muted">
    <i class="bi bi-inbox" style="font-size:48px;opacity:.3"></i>
    <p class="mt-3">لا توجد طلبات <?= $filterStatus === 'pending' ? 'معلقة' : '' ?> حالياً</p>
  </div>
</div>
<?php else: ?>
<div class="row g-3">
<?php foreach ($requests as $req):
  $changedFields = array_filter(array_intersect_key((array)$req, $fieldLabels));
?>
<div class="col-12">
  <div class="panel">
    <div class="panel-body d-flex align-items-center justify-content-between flex-wrap gap-2 pb-3"
         style="border-bottom:1px solid var(--border)">
      <div class="d-flex align-items-center gap-3">
        <div style="width:44px;height:44px;border-radius:50%;background:linear-gradient(135deg,var(--navy),var(--gold));display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:800;color:var(--white);flex-shrink:0">
          <?= mb_substr($req['full_name'], 0, 1, 'UTF-8') ?>
        </div>
        <div>
          <strong class="font-amiri"><?= htmlspecialchars($req['full_name']) ?></strong>
          <div style="font-size:12px;color:var(--text-muted)"><?= htmlspecialchars($req['email']) ?></div>
        </div>
      </div>
      <div class="d-flex align-items-center gap-2">
        <span class="text-muted" style="font-size:12px"><?= date('d/m/Y H:i', strtotime($req['created_at'])) ?></span>
        <?php
        $statusBadge = ['pending' => ['في الانتظار','warning'], 'approved' => ['مقبول','success'], 'rejected' => ['مرفوض','danger']][$req['status']] ?? [$req['status'],'secondary'];
        ?>
        <span class="badge bg-<?= $statusBadge[1] ?>"><?= $statusBadge[0] ?></span>
      </div>
    </div>

    <div class="panel-body">
      <!-- جدول المقارنة: القيمة الحالية vs المطلوبة -->
      <div class="table-responsive mb-3">
        <table class="table table-sm" style="font-size:13px">
          <thead style="background:var(--surface-alt)">
            <tr>
              <th style="width:180px">الحقل</th>
              <th>القيمة الحالية</th>
              <th>القيمة المطلوبة</th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($fieldLabels as $reqCol => $label):
            if (empty($req[$reqCol])) continue;
            $currentVal  = $req[$currentMap[$reqCol]] ?? null;
            $isDoc       = in_array($reqCol, $docFields);
          ?>
          <tr>
            <td class="fw-600"><?= $label ?></td>
            <td class="text-muted">
              <?php if ($isDoc && $currentVal): ?>
              <a href="<?= BASE_URL ?>/public/assets/uploads/<?= htmlspecialchars($currentVal) ?>"
                 target="_blank" class="btn btn-xs btn-outline-secondary" style="font-size:11px">
                <i class="bi bi-eye"></i> عرض الحالية
              </a>
              <?php elseif ($currentVal): ?>
              <?= htmlspecialchars($currentVal) ?>
              <?php else: ?>
              <em class="text-muted">—</em>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($isDoc): ?>
              <a href="<?= BASE_URL ?>/public/assets/uploads/<?= htmlspecialchars($req[$reqCol]) ?>"
                 target="_blank" class="btn btn-sm btn-gold" style="font-size:12px">
                <i class="bi bi-file-earmark-text me-1"></i> عرض المرفوعة
              </a>
              <?php else: ?>
              <strong style="color:var(--navy)"><?= htmlspecialchars($req[$reqCol]) ?></strong>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <?php if ($req['status'] === 'rejected' && $req['rejection_reason']): ?>
      <div class="alert alert-danger py-2 mb-3" style="font-size:13px">
        <i class="bi bi-x-circle me-2"></i>
        <strong>سبب الرفض:</strong> <?= htmlspecialchars($req['rejection_reason']) ?>
        <?php if ($req['reviewer_name']): ?>
        — <span class="text-muted"><?= htmlspecialchars($req['reviewer_name']) ?> في <?= date('d/m/Y', strtotime($req['reviewed_at'])) ?></span>
        <?php endif; ?>
      </div>
      <?php endif; ?>

      <?php if ($req['status'] === 'approved'): ?>
      <div class="alert alert-success py-2 mb-0" style="font-size:13px">
        <i class="bi bi-check-circle me-2"></i>
        تمت الموافقة بواسطة <?= htmlspecialchars($req['reviewer_name'] ?? 'المدير') ?>
        في <?= date('d/m/Y', strtotime($req['reviewed_at'])) ?>
      </div>
      <?php endif; ?>

      <!-- أزرار الموافقة / الرفض -->
      <?php if ($req['status'] === 'pending'): ?>
      <div class="d-flex gap-2 flex-wrap">
        <button class="btn btn-gold btn-sm" onclick="approveReq(<?= $req['id'] ?>, '<?= htmlspecialchars(addslashes($req['full_name'])) ?>')">
          <i class="bi bi-check-circle me-1"></i> قبول التغييرات
        </button>
        <button class="btn btn-danger btn-sm" onclick="rejectReq(<?= $req['id'] ?>, '<?= htmlspecialchars(addslashes($req['full_name'])) ?>')">
          <i class="bi bi-x-circle me-1"></i> رفض
        </button>
      </div>
      <?php endif; ?>

    </div>
  </div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>

</div><!-- /page-content -->
</div><!-- /main-wrap -->

<!-- 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="request_id" id="approveReqId">
        <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>؟
          <br><small>ستُطبَّق التغييرات فوراً على ملفه وسيتم إشعاره.</small>
        </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 me-1"></i> قبول</button>
      </div>
    </form>
  </div></div>
</div>

<!-- 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="request_id" id="rejectReqId">
        <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 me-1"></i> رفض</button>
      </div>
    </form>
  </div></div>
</div>

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