<?php
require_once __DIR__ . '/includes/admin_auth.php';
requireAdmin();
$db = getDB();

// Handle approve / reject
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $id     = (int)($_POST['lawyer_id'] ?? 0);
    $action = $_POST['action'];
    $reason = sanitize($_POST['rejection_reason'] ?? '');
    if ($action === 'approve') {
        $db->prepare("UPDATE lawyers SET verification_status='approved',is_verified=1 WHERE id=?")->execute([$id]);
        setAdminFlash('success', 'Lawyer approved successfully.');
    } elseif ($action === 'reject' && $reason) {
        $db->prepare("UPDATE lawyers SET verification_status='rejected',rejection_reason=? WHERE id=?")->execute([$reason,$id]);
        setAdminFlash('error', 'Lawyer rejected.');
    }
 header('Location: ' . SITE_URL . '/admin/verification.php');
exit;
}

// View single lawyer
$viewId = (int)($_GET['id'] ?? 0);
$viewLawyer = null;
if ($viewId) {
    $s = $db->prepare("SELECT l.*,s.name AS state_name,c.name AS city_name FROM lawyers l LEFT JOIN states s ON l.state_id=s.id LEFT JOIN cities c ON l.city_id=c.id WHERE l.id=?");
    $s->execute([$viewId]);
    $viewLawyer = $s->fetch();
    $expStmt = $db->prepare("SELECT lc.name FROM lawyer_expertise le JOIN legal_categories lc ON le.category_id=lc.id WHERE le.lawyer_id=?");
    $expStmt->execute([$viewId]);
    $viewExpertise = array_column($expStmt->fetchAll(), 'name');
}

$filter = sanitize($_GET['filter'] ?? 'pending');
$stmt   = $db->prepare("SELECT l.*,s.name AS state_name FROM lawyers l LEFT JOIN states s ON l.state_id=s.id WHERE l.verification_status=? ORDER BY l.created_at DESC");
$stmt->execute([$filter]);
$lawyers = $stmt->fetchAll();

$counts = [];
foreach (['pending','approved','rejected'] as $f) {
    $c = $db->prepare("SELECT COUNT(*) FROM lawyers WHERE verification_status=?");
    $c->execute([$f]);
    $counts[$f] = $c->fetchColumn();
}

adminHead('Lawyer Verification');
adminSidebar('verification');
?>
<div class="adm-main">
<?php adminTopbar('Lawyer Verification'); ?>
<div class="adm-content">
<?php flashHtml(); ?>

<!-- Tabs -->
<div style="display:flex;gap:8px;margin-bottom:22px;flex-wrap:wrap;">
<?php foreach (['pending'=>'⏳','approved'=>'✅','rejected'=>'❌'] as $f=>$em): ?>
<a href="?filter=<?= $f ?>" style="padding:8px 20px;border-radius:50px;font-size:.82rem;font-weight:700;text-decoration:none;border:1px solid var(--border);<?= $filter===$f?'background:var(--primary);color:white;border-color:var(--primary);':'background:white;color:#718096;' ?>">
    <?= $em ?> <?= ucfirst($f) ?> (<?= $counts[$f] ?>)
</a>
<?php endforeach; ?>
</div>

<?php if ($viewLawyer): ?>
<!-- Single lawyer review card -->
<div style="background:white;border-radius:14px;border:1px solid var(--border);box-shadow:var(--shadow);padding:28px;margin-bottom:24px;">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:10px;">
        <h5 style="margin:0;color:var(--primary);">Reviewing: <?= htmlspecialchars($viewLawyer['name']) ?></h5>
        <a href="<?= SITE_URL ?>/admin/verification.php?filter=<?= $filter ?>" 
   style="font-size:.82rem;color:var(--primary);font-weight:600;">

   ← Back to list

</a>
    </div>
    <div class="row g-4">
        <div class="col-md-6">
            <table style="width:100%;font-size:.85rem;">
                <?php
                $fields = [
                    'Name'          => $viewLawyer['name'],
                    'Email'         => $viewLawyer['email'],
                    'Mobile'        => $viewLawyer['mobile'],
                    'Experience'    => getExperienceLabel($viewLawyer['experience_years']),
                    'Consultation Fee' => $viewLawyer['experience_years']==='2-4' ? 'Free (mandatory)' : '₹'.number_format($viewLawyer['consultation_fee'],0),
                    'State'         => $viewLawyer['state_name'] ?? '—',
                    'City'          => $viewLawyer['city_name'] ?? '—',
                    'Languages'     => $viewLawyer['languages'] ?? '—',
                    'Practice Areas'=> implode(', ', $viewExpertise) ?: '—',
                    'Home Visit'    => $viewLawyer['home_visit'] ? 'Yes' : 'No',
                    'Pro Bono'      => $viewLawyer['pro_bono'] ? 'Yes' : 'No',
                    'Registered'    => date('d M Y, h:i A', strtotime($viewLawyer['created_at'])),
                ];
                foreach ($fields as $k=>$v): ?>
                <tr>
                    <td style="padding:7px 0;color:#718096;font-weight:600;width:38%;"><?= $k ?></td>
                    <td style="padding:7px 0;color:var(--primary);"><?= htmlspecialchars($v) ?></td>
                </tr>
                <?php endforeach; ?>
            </table>
        </div>
        <div class="col-md-6">
            <?php if ($viewLawyer['about']): ?>
            <div style="background:var(--off-white);border-radius:10px;padding:16px;margin-bottom:14px;">
                <div style="font-size:.75rem;font-weight:700;color:#718096;text-transform:uppercase;margin-bottom:6px;">About</div>
                <p style="font-size:.84rem;color:var(--primary);line-height:1.75;margin:0;"><?= htmlspecialchars(html_entity_decode($viewLawyer['about'])) ?></p>
            </div>
            <?php endif; ?>
            <?php if ($viewLawyer['profile_photo']): ?>
          <div style="margin-bottom:14px;">

    <div style="font-size:.75rem;
                font-weight:700;
                color:#718096;
                text-transform:uppercase;
                margin-bottom:8px;">

        Profile Photo

    </div>

    <?php if (!empty($viewLawyer['profile_photo'])): ?>

    <img src="<?= SITE_URL ?>/assets/uploads/profiles/<?= $viewLawyer['profile_photo'] ?>"
         style="width:90px;
                height:90px;
                border-radius:50%;
                border:3px solid var(--gold);
                object-fit:cover;">

    <?php else: ?>

    <div style="width:90px;
                height:90px;
                border-radius:50%;
                background:var(--primary);
                color:var(--gold);
                display:flex;
                align-items:center;
                justify-content:center;
                font-size:1.4rem;
                font-weight:700;">

        <?= strtoupper(substr($viewLawyer['name'],0,1)) ?>

    </div>

    <?php endif; ?>

</div>
            <?php endif; ?>
            <?php if ($viewLawyer['enrollment_card_front']): ?>
            <div style="margin-bottom:10px;">
                <div style="font-size:.75rem;font-weight:700;color:#718096;text-transform:uppercase;margin-bottom:6px;">Enrollment Card (Front)</div>
                <a href="/nyaya-guru/assets/uploads/<?= $viewLawyer['enrollment_card_front'] ?>" target="_blank" class="btn-sm-edit">View Document</a>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($viewLawyer['verification_status'] === 'pending'): ?>
    <div style="border-top:1px solid var(--border);margin-top:20px;padding-top:20px;display:flex;gap:16px;flex-wrap:wrap;">
        <form method="POST" style="display:inline;">
            <input type="hidden" name="lawyer_id" value="<?= $viewLawyer['id'] ?>">
            <input type="hidden" name="action" value="approve">
            <button type="submit" class="btn-gold" style="padding:10px 28px;" onclick="return confirm('Approve this lawyer?')">
                <i class="fas fa-check me-2"></i>Approve
            </button>
        </form>
        <form method="POST" style="display:flex;gap:10px;align-items:center;flex:1;flex-wrap:wrap;">
            <input type="hidden" name="lawyer_id" value="<?= $viewLawyer['id'] ?>">
            <input type="hidden" name="action" value="reject">
            <input type="text" name="rejection_reason" class="form-ctrl" style="flex:1;min-width:200px;" placeholder="Rejection reason (required)" required>
            <button type="submit" class="btn-sm-del" style="padding:9px 20px;" onclick="return confirm('Reject this lawyer?')">
                <i class="fas fa-times me-2"></i>Reject
            </button>
        </form>
    </div>
    <?php elseif ($viewLawyer['verification_status'] === 'rejected'): ?>
    <div style="border-top:1px solid var(--border);margin-top:20px;padding-top:20px;">
        <form method="POST" style="display:inline;">
            <input type="hidden" name="lawyer_id" value="<?= $viewLawyer['id'] ?>">
            <input type="hidden" name="action" value="approve">
            <button type="submit" class="btn-gold" onclick="return confirm('Re-approve this lawyer?')">
                <i class="fas fa-check me-2"></i>Re-Approve
            </button>
        </form>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Lawyers table -->
<div class="adm-card">
    <div class="adm-card-head"><h6><?= ucfirst($filter) ?> Lawyers (<?= count($lawyers) ?>)</h6></div>
    <?php if (empty($lawyers)): ?>
    <div style="text-align:center;padding:40px;color:#718096;font-size:.88rem;">No <?= $filter ?> lawyers.</div>
    <?php else: ?>
    <div style="overflow-x:auto;">
    <table class="table tbl mb-0">
        <thead><tr><th>Lawyer</th><th>Experience</th><th>Location</th><th>Registered</th><th>Status</th><th>Action</th></tr></thead>
        <tbody>
        <?php foreach ($lawyers as $l): ?>
        <tr>
            <td>
                <div style="font-weight:600;font-size:.85rem;"><?= htmlspecialchars($l['name']) ?></div>
                <div style="font-size:.72rem;color:#718096;"><?= $l['email'] ?> · <?= $l['mobile'] ?></div>
            </td>
            <td style="font-size:.82rem;"><?= $l['experience_years'] ?> yrs</td>
            <td style="font-size:.8rem;color:#718096;"><?= $l['state_name'] ?? '—' ?></td>
            <td style="font-size:.78rem;color:#718096;"><?= date('d M Y', strtotime($l['created_at'])) ?></td>
            <td><span class="badge-pill badge-<?= $l['verification_status'] ?>"><?= ucfirst($l['verification_status']) ?></span></td>
           <td>
    <a href="<?= SITE_URL ?>/admin/verification.php?id=<?= $l['id'] ?>&filter=<?= $filter ?>" 
       class="btn-sm-edit">
       Review
    </a>
</td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    <?php endif; ?>
</div>
</div></div>
<?php adminFoot(); ?>