<?php
// nyaya-guru/admin/includes/admin_auth.php
if (!defined('BASE_PATH')) define('BASE_PATH', dirname(__DIR__, 2));
require_once BASE_PATH . '/includes/config.php';

/* ── Admin auth ──────────────────────────────── */
function isAdminLoggedIn(): bool {
    return !empty($_SESSION['admin_id']);
}
function requireAdmin(): void {

    if (!isAdminLoggedIn()) {

        header('Location: ' . SITE_URL . '/admin/login.php');
        exit;

    }

}
function getCurrentAdmin(): array|false {
    if (!isAdminLoggedIn()) return false;
    $db = getDB();
    $s  = $db->prepare("SELECT * FROM admins WHERE id=? AND status=1 LIMIT 1");
    $s->execute([$_SESSION['admin_id']]);
    return $s->fetch();
}

/* ── Shared HTML helpers ─────────────────────── */
function adminHead(string $title): void { ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= htmlspecialchars($title) ?> — Mee Vakeel Admin</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;800&family=DM+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{--primary:#0A2342;--gold:#D4AF37;--gold-dark:#b8960c;--off-white:#f8f9fc;--border:#e2e8f0;--shadow:0 4px 24px rgba(10,35,66,.10);--font-body:'DM Sans',sans-serif;--font-heading:'Playfair Display',serif;}
*{box-sizing:border-box;}
body{font-family:var(--font-body);background:var(--off-white);margin:0;}
.adm-sidebar{width:240px;min-height:100vh;background:#061628;position:fixed;top:0;left:0;z-index:300;overflow-y:auto;display:flex;flex-direction:column;}
.adm-main{margin-left:240px;min-height:100vh;}
.adm-topbar{background:white;padding:13px 28px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:200;box-shadow:0 2px 8px rgba(0,0,0,.05);}
.adm-content{padding:26px 28px;}
.nav-logo{padding:20px 18px;border-bottom:1px solid rgba(255,255,255,.07);}
.nav-section{padding:14px 10px 4px;font-size:.65rem;color:rgba(255,255,255,.28);font-weight:700;letter-spacing:.12em;text-transform:uppercase;}
.nav-link-item{display:flex;align-items:center;gap:11px;padding:10px 16px;color:rgba(255,255,255,.62);font-size:.84rem;font-weight:500;border-radius:8px;margin:1px 8px;text-decoration:none;transition:all .25s;}
.nav-link-item:hover,.nav-link-item.active{background:rgba(212,175,55,.14);color:var(--gold);}
.nav-link-item i{width:17px;text-align:center;font-size:.85rem;}
.adm-card{background:white;border-radius:14px;border:1px solid var(--border);box-shadow:var(--shadow);overflow:hidden;}
.adm-card-head{padding:16px 22px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
.adm-card-head h6{margin:0;font-size:.9rem;font-weight:700;color:var(--primary);}
.adm-card-body{padding:0;}
.stat-box{background:white;border-radius:14px;padding:20px;border:1px solid var(--border);box-shadow:var(--shadow);display:flex;align-items:center;gap:14px;}
.stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.2rem;min-width:48px;}
.stat-num{font-size:1.6rem;font-weight:800;color:var(--primary);font-family:var(--font-heading);}
.stat-lbl{font-size:.75rem;color:#718096;font-weight:500;}
.tbl th{background:var(--off-white);color:#718096;font-size:.73rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;padding:11px 14px;border-bottom:2px solid var(--border);}
.tbl td{padding:12px 14px;vertical-align:middle;font-size:.85rem;border-bottom:1px solid var(--border);}
.tbl tr:last-child td{border-bottom:none;}
.tbl tr:hover td{background:rgba(10,35,66,.02);}
.badge-pill{padding:4px 12px;border-radius:50px;font-size:.7rem;font-weight:700;}
.badge-pending{background:rgba(255,193,7,.14);color:#b8860b;}
.badge-approved{background:rgba(40,167,69,.12);color:#1a7a34;}
.badge-rejected{background:rgba(220,53,69,.10);color:#c0392b;}
.badge-active{background:rgba(40,167,69,.12);color:#1a7a34;}
.badge-inactive{background:rgba(108,117,125,.1);color:#6c757d;}
.badge-completed{background:rgba(10,35,66,.08);color:var(--primary);}
.badge-confirmed{background:rgba(40,167,69,.12);color:#1a7a34;}
.badge-cancelled{background:rgba(220,53,69,.10);color:#c0392b;}
.btn-gold{background:linear-gradient(135deg,var(--gold),var(--gold-dark));color:var(--primary);font-weight:700;border:none;border-radius:8px;padding:8px 18px;font-size:.83rem;cursor:pointer;}
.btn-sm-del{background:rgba(220,53,69,.1);color:#c0392b;border:1px solid rgba(220,53,69,.2);border-radius:6px;padding:4px 10px;font-size:.72rem;font-weight:700;cursor:pointer;text-decoration:none;}
.btn-sm-edit{background:rgba(10,35,66,.07);color:var(--primary);border:1px solid var(--border);border-radius:6px;padding:4px 10px;font-size:.72rem;font-weight:700;cursor:pointer;text-decoration:none;}
.form-ctrl{border:1.5px solid var(--border);border-radius:9px;padding:10px 14px;font-size:.88rem;width:100%;font-family:var(--font-body);transition:border .2s;}
.form-ctrl:focus{outline:none;border-color:var(--primary);}
label.lbl{font-weight:600;font-size:.82rem;color:#2d3748;margin-bottom:5px;display:block;}
@media(max-width:768px){.adm-sidebar{transform:translateX(-100%);}.adm-main{margin-left:0;}}
</style>
<?php }

function adminSidebar(string $active = ''): void {
    $admin = getCurrentAdmin();
   $nav = [

    'Dashboard' => [
        ['dashboard', 'fas fa-tachometer-alt', 'Dashboard', SITE_URL . '/admin/index.php']
    ],

    'Lawyers' => [
        ['lawyers',      'fas fa-user-tie',      'All Lawyers',      SITE_URL . '/admin/lawyers.php'],
        ['verification', 'fas fa-check-circle',  'Verification',     SITE_URL . '/admin/verification.php'],
        ['featured',     'fas fa-star',          'Featured Control', SITE_URL . '/admin/featured.php'],
    ],

    'Clients' => [
        ['users', 'fas fa-users', 'Manage Users', SITE_URL . '/admin/users.php']
    ],

    'Consultations' => [
        ['consultations', 'fas fa-calendar-check', 'Consultations', SITE_URL . '/admin/consultations.php'],
        ['payments',      'fas fa-rupee-sign',     'Payments',      SITE_URL . '/admin/payments.php'],
    ],

    'Content' => [
        ['categories', 'fas fa-tags',           'Legal Categories', SITE_URL . '/admin/categories.php'],
        ['cities',     'fas fa-map-marker-alt', 'Cities & States',  SITE_URL . '/admin/cities.php'],
        ['banners',    'fas fa-image',          'Banners',          SITE_URL . '/admin/banners.php'],
        ['cms',        'fas fa-file-alt',       'CMS Pages',        SITE_URL . '/admin/cms.php'],
    ],

    'Settings' => [
        ['seo',      'fas fa-search',      'SEO Settings',     SITE_URL . '/admin/seo.php'],
        ['reports',  'fas fa-chart-bar',   'Reports',          SITE_URL . '/admin/reports.php'],
        ['contacts', 'fas fa-envelope',    'Contact Messages', SITE_URL . '/admin/contacts.php'],
    ],

];
    ?>
    <div class="adm-sidebar">
        <div class="nav-logo">
            <div style="font-family:var(--font-heading);font-size:1.2rem;font-weight:800;color:white;"><span style="color:var(--gold);">Nyaya</span> Guru</div>
            <div style="font-size:.68rem;color:rgba(255,255,255,.35);margin-top:2px;">Admin Panel</div>
        </div>
        <?php if ($admin): ?>
        <div style="padding:14px 16px;border-bottom:1px solid rgba(255,255,255,.06);display:flex;align-items:center;gap:10px;">
            <div style="width:34px;height:34px;background:var(--gold);border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;color:var(--primary);font-size:.8rem;"><?= strtoupper(substr($admin['name'],0,1)) ?></div>
            <div>
                <div style="color:white;font-size:.8rem;font-weight:600;"><?= htmlspecialchars(explode(' ',$admin['name'])[0]) ?></div>
                <div style="font-size:.65rem;color:rgba(255,255,255,.4);"><?= ucfirst($admin['role']) ?></div>
            </div>
        </div>
        <?php endif; ?>
        <?php foreach ($nav as $section => $items): ?>
        <div class="nav-section"><?= $section ?></div>
        <?php foreach ($items as [$key,$icon,$label,$url]): ?>
        <a href="<?= $url ?>" class="nav-link-item <?= $active===$key?'active':'' ?>">
            <i class="<?= $icon ?>"></i><?= $label ?>
        </a>
        <?php endforeach; ?>
        <?php endforeach; ?>
        <div style="margin-top:auto;padding:12px 8px;border-top:1px solid rgba(255,255,255,.07);">
            <a href="/admin/logout.php" class="nav-link-item" style="color:rgba(220,53,69,.75);"><i class="fas fa-sign-out-alt"></i>Logout</a>
            <a href="/" target="_blank" class="nav-link-item"><i class="fas fa-external-link-alt"></i>View Site</a>
        </div>
    </div>
    <?php
}

function adminTopbar(string $pageTitle): void {
    ?>
    <div class="adm-topbar">
        <div>
            <h5 style="margin:0;font-size:.95rem;color:var(--primary);font-weight:700;"><?= htmlspecialchars($pageTitle) ?></h5>
        </div>
        <div style="display:flex;align-items:center;gap:16px;">
            <span style="font-size:.78rem;color:#718096;"><?= date('d M Y, h:i A') ?></span>
            <a href="/admin/logout.php" style="font-size:.8rem;color:#dc3545;font-weight:600;text-decoration:none;">Logout</a>
        </div>
    </div>
    <?php
}

function adminFoot(): void { ?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script>
// Confirm delete
document.querySelectorAll('.confirm-del').forEach(btn => {
    btn.addEventListener('click', e => { if (!confirm('Delete this record? This cannot be undone.')) e.preventDefault(); });
});
// Flash auto-dismiss
setTimeout(() => document.querySelectorAll('.auto-dismiss').forEach(el => el.style.display='none'), 4000);
</script>
</body></html>
<?php }

function flashHtml(): void {
    if (isset($_SESSION['admin_flash'])) {
        $f = $_SESSION['admin_flash'];
        unset($_SESSION['admin_flash']);
        $bg = $f['type']==='success' ? 'rgba(40,167,69,.08)' : 'rgba(220,53,69,.07)';
        $bc = $f['type']==='success' ? 'rgba(40,167,69,.3)' : 'rgba(220,53,69,.25)';
        $tc = $f['type']==='success' ? '#1a7a34' : '#c0392b';
        $ic = $f['type']==='success' ? 'fa-check-circle' : 'fa-exclamation-circle';
        echo "<div class='auto-dismiss' style='background:$bg;border:1px solid $bc;border-radius:10px;padding:12px 18px;margin-bottom:18px;color:$tc;font-size:.86rem;'>
              <i class='fas $ic me-2'></i>".htmlspecialchars($f['msg'])."</div>";
    }
}
function setAdminFlash(string $type, string $msg): void {
    $_SESSION['admin_flash'] = ['type'=>$type,'msg'=>$msg];
}