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

// Toggle status / featured / delete
if (isset($_GET['toggle_status'])) {
    $id = (int)$_GET['toggle_status'];
    $db->prepare("UPDATE lawyers SET status = 1 - status WHERE id=?")->execute([$id]);
    setAdminFlash('success','Lawyer status updated.'); header('Location: ' . SITE_URL . '/admin/lawyers.php'); exit;
}
if (isset($_GET['toggle_featured'])) {
    $id = (int)$_GET['toggle_featured'];
    $db->prepare("UPDATE lawyers SET is_featured = 1 - is_featured WHERE id=?")->execute([$id]);
    setAdminFlash('success','Featured status updated.'); header('Location: ' . SITE_URL . '/admin/lawyers.php'); exit;
}
if (isset($_GET['delete']) && (int)$_GET['delete']) {
    $db->prepare("DELETE FROM lawyers WHERE id=?")->execute([(int)$_GET['delete']]);
    setAdminFlash('success','Lawyer deleted.'); header('Location: ' . SITE_URL . '/admin/lawyers.php'); exit;
}

$search = sanitize($_GET['q'] ?? '');
$status = $_GET['status'] ?? '';
$verif  = $_GET['verif']  ?? '';
$page   = max(1,(int)($_GET['page'] ?? 1));
$pp     = 15;

$where = ['1=1']; $params = [];
if ($search) { $where[] = "(l.name LIKE ? OR l.email LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($status !== '') { $where[] = "l.status=?"; $params[] = (int)$status; }
if ($verif)  { $where[] = "l.verification_status=?"; $params[] = $verif; }

$wsql  = implode(' AND ', $where);
$total = $db->prepare("SELECT COUNT(*) FROM lawyers l WHERE $wsql"); $total->execute($params); $total=(int)$total->fetchColumn();
$pages = max(1, ceil($total/$pp));
$offset= ($page-1)*$pp;

$stmt = $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 $wsql ORDER BY l.created_at DESC LIMIT $pp OFFSET $offset");
$stmt->execute($params);
$lawyers = $stmt->fetchAll();

adminHead('Manage Lawyers');
adminSidebar('lawyers');
?>
<div class="adm-main">
<?php adminTopbar('Manage Lawyers'); ?>
<div class="adm-content">
<?php flashHtml(); ?>

<!-- Filter bar -->
<div style="background:white;border-radius:12px;padding:16px 20px;border:1px solid var(--border);margin-bottom:20px;">
    <form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;">
        <div><label class="lbl" style="font-size:.72rem;">Search</label>
        <input type="text" name="q" class="form-ctrl" style="width:200px;" placeholder="Name or email..." value="<?= htmlspecialchars($search) ?>"></div>
        <div><label class="lbl" style="font-size:.72rem;">Verification</label>
        <select name="verif" class="form-ctrl" style="width:140px;">
            <option value="">All</option>
            <?php foreach(['pending','approved','rejected'] as $v): ?>
            <option value="<?= $v ?>" <?= $verif===$v?'selected':'' ?>><?= ucfirst($v) ?></option>
            <?php endforeach; ?>
        </select></div>
        <div><label class="lbl" style="font-size:.72rem;">Status</label>
        <select name="status" class="form-ctrl" style="width:110px;">
            <option value="">All</option>
            <option value="1" <?= $status==='1'?'selected':'' ?>>Active</option>
            <option value="0" <?= $status==='0'?'selected':'' ?>>Inactive</option>
        </select></div>
        <button type="submit" class="btn-gold">Filter</button>
        <a href="<?= SITE_URL ?>/admin/add-lawyer.php"
   style="padding:10px 16px;
          background:var(--primary);
          color:white;
          border-radius:8px;
          text-decoration:none;
          font-size:.82rem;
          font-weight:600;">

    <i class="fas fa-plus me-1"></i>
    Add Lawyer

</a>
        <a href="<?= SITE_URL ?>/admin/lawyers.php" style="padding:9px 14px;background:var(--off-white);border-radius:8px;font-size:.82rem;color:#718096;text-decoration:none;border:1px solid var(--border);">Reset</a>
    </form>
</div>
<div style="margin-bottom:12px;font-size:.82rem;color:#718096;"><?= $total ?> lawyer<?= $total!=1?'s':'' ?> found</div>

<div class="adm-card">
<div style="overflow-x:auto;">
<table class="table tbl mb-0">
    <thead><tr><th>Lawyer</th><th>Experience</th><th>Location</th><th>Fee</th><th>Verification</th><th>Featured</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($lawyers as $l): ?>
    <tr>
        <td>
            <div style="display:flex;align-items:center;gap:10px;">
                <?php if ($l['profile_photo']): ?>

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

<?php else: ?>

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

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

</div>

<?php endif; ?>
                <div>
                    <div style="font-weight:700;font-size:.83rem;"><?= htmlspecialchars($l['name']) ?></div>
                    <div style="font-size:.7rem;color:#718096;"><?= $l['email'] ?></div>
                </div>
            </div>
        </td>
        <td style="font-size:.8rem;"><?= $l['experience_years'] ?></td>
        <td style="font-size:.78rem;color:#718096;"><?= ($l['city_name']??'').($l['state_name']?', '.$l['state_name']:'') ?: '—' ?></td>
        <td style="font-size:.82rem;font-weight:600;"><?= $l['experience_years']==='2-4' ? '<span style="color:var(--success);">Free</span>' : '₹'.number_format($l['consultation_fee'],0) ?></td>
        <td><span class="badge-pill badge-<?= $l['verification_status'] ?>"><?= ucfirst($l['verification_status']) ?></span></td>
        <td>
            <a href="?toggle_featured=<?= $l['id'] ?>&q=<?= urlencode($search) ?>&verif=<?= $verif ?>&status=<?= $status ?>"
               style="font-size:1.1rem;color:<?= $l['is_featured']?'var(--gold)':'#ccc' ?>;text-decoration:none;" title="Toggle Featured">
                <i class="fas fa-star"></i>
            </a>
        </td>
        <td>
            <a href="?toggle_status=<?= $l['id'] ?>&q=<?= urlencode($search) ?>&verif=<?= $verif ?>&status=<?= $status ?>"
               style="font-size:.72rem;padding:4px 10px;border-radius:50px;font-weight:700;text-decoration:none;background:<?= $l['status']?'rgba(40,167,69,.1)':'rgba(220,53,69,.1)' ?>;color:<?= $l['status']?'#1a7a34':'#c0392b' ?>;">
                <?= $l['status'] ? 'Active' : 'Inactive' ?>
            </a>
        </td>
<td style="white-space:nowrap;">

    <a href="<?= SITE_URL ?>/admin/verification.php?id=<?= $l['id'] ?>"
       class="btn-sm-edit">
       View
    </a>

    <a href="<?= SITE_URL ?>/admin/edit-lawyer.php?id=<?= $l['id'] ?>"
       class="btn-sm-edit"
       style="margin-left:5px;background:#0d6efd;color:white;">
       Edit
    </a>

    <a href="?toggle_status=<?= $l['id'] ?>"
       class="btn-sm-edit"
       style="margin-left:5px;
              background:<?= $l['status'] ? '#dc3545' : '#198754' ?>;
              color:white;">

       <?= $l['status'] ? 'Disable' : 'Enable' ?>

    </a>

    <a href="?delete=<?= $l['id'] ?>"
       onclick="return confirm('Delete this lawyer?')"
       class="btn-sm-del"
       style="margin-left:5px;">

       Delete

    </a>

</td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($lawyers)): ?>
    <tr><td colspan="8" style="text-align:center;padding:40px;color:#718096;">No lawyers found.</td></tr>
    <?php endif; ?>
    </tbody>
</table>
</div>
</div>

<?php if ($pages > 1): ?>
<nav style="margin-top:20px;"><ul class="pagination justify-content-center gap-1">
<?php for ($p=1;$p<=$pages;$p++): ?>
<li><a href="?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>"
   style="display:block;padding:8px 14px;border-radius:8px;<?= $p===$page?'background:var(--primary);color:white;':'border:1px solid var(--border);color:var(--primary);' ?>text-decoration:none;font-size:.82rem;"><?= $p ?></a></li>
<?php endfor; ?>
</ul></nav>
<?php endif; ?>

</div></div>
<?php adminFoot(); ?>