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

// ── Stats ──────────────────────────────────────
$stats = [
    'lawyers'       => $db->query("SELECT COUNT(*) FROM lawyers WHERE status=1")->fetchColumn(),
    'pending_v'     => $db->query("SELECT COUNT(*) FROM lawyers WHERE verification_status='pending'")->fetchColumn(),
    'users'         => $db->query("SELECT COUNT(*) FROM users WHERE status=1")->fetchColumn(),
    'appointments'  => $db->query("SELECT COUNT(*) FROM appointments")->fetchColumn(),
    'today_appts'   => $db->query("SELECT COUNT(*) FROM appointments WHERE DATE(created_at)=CURDATE()")->fetchColumn(),
    'completed'     => $db->query("SELECT COUNT(*) FROM appointments WHERE status='completed'")->fetchColumn(),
    'revenue'       => $db->query("SELECT COALESCE(SUM(amount),0) FROM payments WHERE status='completed'")->fetchColumn(),
    'platform_fee'  => $db->query("SELECT COALESCE(SUM(platform_fee),0) FROM payments WHERE status='completed'")->fetchColumn(),
    'contacts'      => $db->query("SELECT COUNT(*) FROM contact_messages WHERE is_read=0")->fetchColumn(),
];

// Recent lawyers
$recentLawyers = $db->query("SELECT l.*,s.name AS state_name FROM lawyers l LEFT JOIN states s ON l.state_id=s.id ORDER BY l.created_at DESC LIMIT 6")->fetchAll();

// Recent appointments
$recentAppts = $db->query("SELECT a.*,u.name AS client_name,l.name AS lawyer_name FROM appointments a JOIN users u ON a.user_id=u.id JOIN lawyers l ON a.lawyer_id=l.id ORDER BY a.created_at DESC LIMIT 8")->fetchAll();

// Monthly appointments (last 6 months)
$monthly = $db->query("SELECT DATE_FORMAT(created_at,'%b %Y') AS month, COUNT(*) AS cnt FROM appointments WHERE created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH) GROUP BY YEAR(created_at),MONTH(created_at) ORDER BY created_at ASC")->fetchAll();

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

<!-- Stat grid -->
<div class="row g-3 mb-4">
<?php
$statBoxes = [
    ['fas fa-user-tie',      'rgba(10,35,66,.08)',    'var(--primary)', $stats['lawyers'],      'Total Lawyers'],
    ['fas fa-hourglass-half','rgba(255,193,7,.14)',   '#b8860b',        $stats['pending_v'],    'Pending Verification'],
    ['fas fa-users',         'rgba(40,167,69,.1)',    '#1a7a34',        $stats['users'],         'Clients'],
    ['fas fa-calendar-check','rgba(23,162,184,.1)',   '#0c7590',        $stats['appointments'],  'Total Consultations'],
    ['fas fa-calendar-day',  'rgba(102,16,242,.1)',   '#6610f2',        $stats['today_appts'],   'Today\'s Bookings'],
    ['fas fa-check-double',  'rgba(40,167,69,.1)',    '#1a7a34',        $stats['completed'],     'Completed'],
    ['fas fa-rupee-sign',    'rgba(212,175,55,.14)',  'var(--gold-dark)','₹'.number_format($stats['revenue'],0), 'Total Revenue'],
    ['fas fa-envelope',      'rgba(220,53,69,.1)',    '#c0392b',        $stats['contacts'],      'Unread Messages'],
];
foreach ($statBoxes as [$icon,$bg,$color,$val,$lbl]): ?>
<div class="col-6 col-md-3">
    <div class="stat-box">
        <div class="stat-icon" style="background:<?= $bg ?>;color:<?= $color ?>;"><i class="<?= $icon ?>"></i></div>
        <div><div class="stat-num"><?= $val ?></div><div class="stat-lbl"><?= $lbl ?></div></div>
    </div>
</div>
<?php endforeach; ?>
</div>

<!-- Quick actions -->
<div class="row g-3 mb-4">
<?php
$actions = [
    [SITE_URL . '/admin/verification.php','fas fa-check-circle','var(--gold-dark)','Verify Lawyers',    $stats['pending_v'].' pending'],
    [SITE_URL . '/admin/lawyers.php',     'fas fa-user-tie',    'var(--primary)',  'Manage Lawyers',    $stats['lawyers'].' total'],
    [SITE_URL . '/admin/users.php',       'fas fa-users',       '#2d6a4f',         'Manage Clients',    $stats['users'].' registered'],
    [SITE_URL . '/admin/consultations.php','fas fa-calendar',   '#8e44ad',         'Consultations',     $stats['appointments'].' total'],
];
foreach ($actions as [$url,$icon,$color,$title,$sub]): ?>
<div class="col-md-3">
    <a href="<?= $url ?>" style="display:flex;align-items:center;gap:12px;background:white;border-radius:12px;padding:16px;border:1px solid var(--border);text-decoration:none;transition:all .25s;"
       onmouseover="this.style.borderColor='var(--gold)';this.style.transform='translateY(-2px)'"
       onmouseout="this.style.borderColor='var(--border)';this.style.transform=''">
        <div style="width:42px;height:42px;background:<?= $color ?>;border-radius:10px;display:flex;align-items:center;justify-content:center;color:white;font-size:.95rem;min-width:42px;"><i class="<?= $icon ?>"></i></div>
        <div><div style="font-weight:700;font-size:.85rem;color:var(--primary);"><?= $title ?></div><div style="font-size:.74rem;color:#718096;"><?= $sub ?></div></div>
    </a>
</div>
<?php endforeach; ?>
</div>

<div class="row g-4">
    <!-- Recent Lawyers -->
    <div class="col-lg-6">
        <div class="adm-card">
            <div class="adm-card-head">
                <h6>Recent Lawyer Registrations</h6>
                <a href="<?= SITE_URL ?>/admin/lawyers.php" style="font-size:.78rem;color:var(--primary);font-weight:600;">View All</a>
            </div>
            <table class="table tbl mb-0">
                <thead><tr><th>Name</th><th>Experience</th><th>Status</th><th>Action</th></tr></thead>
                <tbody>
                <?php foreach ($recentLawyers as $l): ?>
                <tr>
                    <td>
                        <div style="font-weight:600;font-size:.83rem;"><?= htmlspecialchars($l['name']) ?></div>
                        <div style="font-size:.7rem;color:#718096;"><?= $l['email'] ?></div>
                    </td>
                    <td style="font-size:.8rem;"><?= $l['experience_years'] ?> yrs</td>
                    <td><span class="badge-pill badge-<?= $l['verification_status'] ?>"><?= ucfirst($l['verification_status']) ?></span></td>
                  <td>
    <?php if ($l['verification_status'] === 'pending'): ?>

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

    <?php else: ?>

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

    <?php endif; ?>
</td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Recent Appointments -->
    <div class="col-lg-6">
        <div class="adm-card">
            <div class="adm-card-head">
                <h6>Recent Appointments</h6>
                <a href="<?= SITE_URL ?>/admin/consultations.php" style="font-size:.78rem;color:var(--primary);font-weight:600;">View All</a>
            </div>
            <table class="table tbl mb-0">
                <thead><tr><th>Client</th><th>Lawyer</th><th>Date</th><th>Status</th></tr></thead>
                <tbody>
                <?php foreach ($recentAppts as $a): ?>
                <tr>
                    <td style="font-size:.82rem;font-weight:600;"><?= htmlspecialchars($a['client_name']) ?></td>
                    <td style="font-size:.8rem;color:#718096;"><?= htmlspecialchars($a['lawyer_name']) ?></td>
                    <td style="font-size:.78rem;"><?= $a['appointment_date'] ? date('d M', strtotime($a['appointment_date'])) : '—' ?></td>
                    <td><span class="badge-pill badge-<?= $a['status'] ?>"><?= ucfirst($a['status']) ?></span></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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