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

// Update status
if (isset($_GET['set_status']) && isset($_GET['id'])) {
    $allowed = ['pending','confirmed','completed','cancelled','rejected'];
    $newStatus = $_GET['set_status'];
    if (in_array($newStatus, $allowed)) {
        $db->prepare("UPDATE appointments SET status=? WHERE id=?")->execute([$newStatus,(int)$_GET['id']]);
        setAdminFlash('success','Appointment status updated.');
    }
   header('Location: ' . SITE_URL . '/admin/consultations.php');
    exit;
}

$statusFilter = sanitize($_GET['status'] ?? '');
$search       = sanitize($_GET['q'] ?? '');
$dateFrom     = sanitize($_GET['date_from'] ?? '');
$dateTo       = sanitize($_GET['date_to'] ?? '');
$page         = max(1,(int)($_GET['page'] ?? 1));
$pp           = 15;

$where = ['1=1']; $params = [];
if ($statusFilter) { $where[] = "a.status=?"; $params[] = $statusFilter; }
if ($dateFrom)     { $where[] = "a.appointment_date >= ?"; $params[] = $dateFrom; }
if ($dateTo)       { $where[] = "a.appointment_date <= ?"; $params[] = $dateTo; }
if ($search)       { $where[] = "(u.name LIKE ? OR l.name LIKE ? OR a.booking_id LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%"; }

$wsql   = implode(' AND ', $where);
$cstmt  = $db->prepare("SELECT COUNT(*) FROM appointments a JOIN users u ON a.user_id=u.id JOIN lawyers l ON a.lawyer_id=l.id WHERE $wsql");
$cstmt->execute($params); $total=(int)$cstmt->fetchColumn();
$pages  = max(1,ceil($total/$pp));
$offset = ($page-1)*$pp;

$stmt = $db->prepare("SELECT a.*,u.name AS client_name,u.mobile AS client_mobile,l.name AS lawyer_name,l.consultation_fee FROM appointments a JOIN users u ON a.user_id=u.id JOIN lawyers l ON a.lawyer_id=l.id WHERE $wsql ORDER BY a.created_at DESC LIMIT $pp OFFSET $offset");
$stmt->execute($params);
$appts = $stmt->fetchAll();

// Status counts
$sCounts = [];
foreach(['pending','confirmed','completed','cancelled','rejected'] as $s){
    $cs=$db->prepare("SELECT COUNT(*) FROM appointments WHERE status=?");$cs->execute([$s]);$sCounts[$s]=(int)$cs->fetchColumn();
}
$sCounts['all']=(int)$db->query("SELECT COUNT(*) FROM appointments")->fetchColumn();

function aBadge(string $s): string {
    $m=['pending'=>['rgba(255,193,7,.14)','#b8860b'],'confirmed'=>['rgba(255,193,7,.18)','#b8860b'],'completed'=>['rgba(40,167,69,.14)','#1a7a34'],'cancelled'=>['rgba(220,53,69,.1)','#c0392b'],'rejected'=>['rgba(220,53,69,.1)','#c0392b'],'ongoing'=>['rgba(23,162,184,.1)','#0c7590']];
    [$bg,$c]=$m[$s]??['rgba(0,0,0,.06)','#555'];
    return "<span style='background:$bg;color:$c;padding:3px 10px;border-radius:50px;font-size:.7rem;font-weight:700;'>".ucfirst($s)."</span>";
}

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

<!-- Status tabs -->
<div style="display:flex;gap:7px;margin-bottom:20px;flex-wrap:wrap;overflow-x:auto;">
<a href="<?= SITE_URL ?>/admin/consultations.php?" style="white-space:nowrap;padding:7px 16px;border-radius:50px;font-size:.79rem;font-weight:700;text-decoration:none;border:1px solid var(--border);<?= !$statusFilter?'background:var(--primary);color:white;border-color:var(--primary);':'background:white;color:#718096;' ?>">All (<?= $sCounts['all'] ?>)</a>
<?php foreach(['pending'=>'⏳','confirmed'=>'✅','completed'=>'🏁','cancelled'=>'❌','rejected'=>'🚫'] as $s=>$em): ?>
<a href="<?= SITE_URL ?>/admin/consultations.php?status=<?= $s ?>" style="white-space:nowrap;padding:7px 16px;border-radius:50px;font-size:.79rem;font-weight:700;text-decoration:none;border:1px solid var(--border);<?= $statusFilter===$s?'background:var(--primary);color:white;border-color:var(--primary);':'background:white;color:#718096;' ?>"><?= $em ?> <?= ucfirst($s) ?> (<?= $sCounts[$s] ?>)</a>
<?php endforeach; ?>
</div>

<!-- Filters -->
<div style="background:white;border-radius:12px;padding:14px 18px;border:1px solid var(--border);margin-bottom:18px;">
    <form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;align-items:flex-end;">
        <?php if ($statusFilter): ?><input type="hidden" name="status" value="<?= $statusFilter ?>"><?php endif; ?>
        <div><label class="lbl" style="font-size:.72rem;">Search</label>
        <input type="text" name="q" class="form-ctrl" style="width:200px;" placeholder="Client, lawyer, booking ID..." value="<?= htmlspecialchars($search) ?>"></div>
        <div><label class="lbl" style="font-size:.72rem;">From Date</label>
        <input type="date" name="date_from" class="form-ctrl" style="width:145px;" value="<?= $dateFrom ?>"></div>
        <div><label class="lbl" style="font-size:.72rem;">To Date</label>
        <input type="date" name="date_to" class="form-ctrl" style="width:145px;" value="<?= $dateTo ?>"></div>
        <button type="submit" class="btn-gold">Filter</button>
       <a href="<?= SITE_URL ?>/admin/consultations.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="font-size:.82rem;color:#718096;margin-bottom:10px;"><?= $total ?> consultation<?= $total!=1?'s':'' ?> found</div>

<div class="adm-card">
<div style="overflow-x:auto;">
<table class="table tbl mb-0">
    <thead><tr><th>Booking ID</th><th>Client</th><th>Lawyer</th><th>Type</th><th>Date</th><th>Fee</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($appts as $a): ?>
    <tr>
        <td style="font-size:.75rem;font-weight:700;color:var(--primary);"><?= $a['booking_id'] ?></td>
        <td>
            <div style="font-weight:600;font-size:.83rem;"><?= htmlspecialchars($a['client_name']) ?></div>
            <div style="font-size:.7rem;color:#718096;"><?= $a['client_mobile'] ?></div>
        </td>
        <td style="font-size:.82rem;font-weight:600;"><?= htmlspecialchars($a['lawyer_name']) ?></td>
        <td><span style="background:rgba(10,35,66,.07);color:var(--primary);padding:3px 9px;border-radius:50px;font-size:.7rem;font-weight:600;text-transform:capitalize;"><?= str_replace('_',' ',$a['consultation_type']) ?></span></td>
        <td style="font-size:.78rem;color:#718096;">
            <?= $a['appointment_date'] ? date('d M Y', strtotime($a['appointment_date'])) : '—' ?>
            <?= $a['appointment_time'] ? '<br>'.date('h:i A', strtotime($a['appointment_time'])) : '' ?>
        </td>
        <td style="font-size:.82rem;font-weight:600;color:var(--primary);">
            <?= $a['consultation_fee'] > 0 ? '₹'.number_format($a['consultation_fee'],0) : '<span style="color:var(--success);">Free</span>' ?>
        </td>
        <td><?= aBadge($a['status']) ?></td>
        <td>
            <div style="display:flex;gap:5px;flex-wrap:wrap;">
                <?php
                $actions = [];
 if ($a['status']==='pending') {

    $actions[] = [
        'confirmed',
        'Confirm',
        'rgba(40,167,69,.1)',
        '#1a7a34'
    ];

    $actions[] = [
        'rejected',
        'Reject',
        'rgba(220,53,69,.1)',
        '#c0392b'
    ];
}

if ($a['status']==='confirmed') {

    $actions[] = [
        'completed',
        'Complete',
        'rgba(10,35,66,.08)',
        '#0A2342'
    ];

    $actions[] = [
        'cancelled',
        'Cancel',
        'rgba(220,53,69,.1)',
        '#c0392b'
    ];
}
                foreach ($actions as [$s,$lbl,$bg,$co]): ?>
                <a href="<?= SITE_URL ?>/admin/consultations.php?set_status=<?= $s ?>&id=<?= $a['id'] ?>" style="background:<?= $bg ?>;color:<?= $co ?>;padding:4px 9px;border-radius:6px;font-size:.7rem;font-weight:700;text-decoration:none;border:1px solid <?= $bg ?>;"
                   onclick="return confirm('Set status to <?= $lbl ?>?')"><?= $lbl ?></a>
                <?php endforeach; ?>
            </div>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($appts)): ?>
    <tr><td colspan="8" style="text-align:center;padding:40px;color:#718096;">No consultations found.</td></tr>
    <?php endif; ?>
    </tbody>
</table>
</div>
</div>

<?php if ($pages > 1): ?>
<nav style="margin-top:18px;"><ul class="pagination justify-content-center gap-1">
<?php for($p=1;$p<=$pages;$p++): ?>
<li><a href="<?= SITE_URL ?>/admin/consultations.php?<?= http_build_query(array_merge($_GET,['page'=>$p])) ?>" style="display:block;padding:7px 13px;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(); ?>