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

// Actions
if (isset($_GET['toggle_status'])) {

    $db->prepare("UPDATE users SET status = 1-status WHERE id=?")
       ->execute([(int)$_GET['toggle_status']]);

    setAdminFlash('success','User status updated.');

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

if (isset($_GET['delete']) && (int)$_GET['delete']) {

    $db->prepare("DELETE FROM users WHERE id=?")
       ->execute([(int)$_GET['delete']]);

    setAdminFlash('success','User deleted.');

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

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

$where = ['1=1']; $params = [];
if ($search) {
    $where[]  = "(name LIKE ? OR email LIKE ? OR mobile LIKE ?)";
    $params[] = "%$search%"; $params[] = "%$search%"; $params[] = "%$search%";
}
$wsql   = implode(' AND ', $where);
$total  = (int)$db->prepare("SELECT COUNT(*) FROM users WHERE $wsql")->execute($params) ? $db->prepare("SELECT COUNT(*) FROM users WHERE $wsql") : 0;
$cstmt  = $db->prepare("SELECT COUNT(*) FROM users WHERE $wsql"); $cstmt->execute($params); $total=(int)$cstmt->fetchColumn();
$pages  = max(1,ceil($total/$pp));
$offset = ($page-1)*$pp;

$stmt = $db->prepare("SELECT u.*, c.name AS city_name, s.name AS state_name, (SELECT COUNT(*) FROM appointments WHERE user_id=u.id) AS appt_count FROM users u LEFT JOIN cities c ON u.city_id=c.id LEFT JOIN states s ON u.state_id=s.id WHERE $wsql ORDER BY u.created_at DESC LIMIT $pp OFFSET $offset");
$stmt->execute($params);
$users = $stmt->fetchAll();

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

<!-- Stats row -->
<div class="row g-3 mb-4">
<?php
$uStats = [
    ['fas fa-users','rgba(10,35,66,.08)','var(--primary)', $db->query("SELECT COUNT(*) FROM users")->fetchColumn(), 'Total Clients'],
    ['fas fa-user-check','rgba(40,167,69,.1)','#1a7a34', $db->query("SELECT COUNT(*) FROM users WHERE status=1")->fetchColumn(), 'Active'],
    ['fas fa-calendar-check','rgba(212,175,55,.14)','var(--gold-dark)', $db->query("SELECT COUNT(*) FROM appointments")->fetchColumn(), 'Total Bookings'],
    ['fas fa-user-plus','rgba(102,16,242,.1)','#6610f2', $db->query("SELECT COUNT(*) FROM users WHERE DATE(created_at)=CURDATE()")->fetchColumn(), 'Joined Today'],
];
foreach ($uStats as [$ic,$bg,$co,$val,$lbl]): ?>
<div class="col-6 col-md-3">
    <div class="stat-box">
        <div class="stat-icon" style="background:<?= $bg ?>;color:<?= $co ?>;"><i class="<?= $ic ?>"></i></div>
        <div><div class="stat-num"><?= $val ?></div><div class="stat-lbl"><?= $lbl ?></div></div>
    </div>
</div>
<?php endforeach; ?>
</div>

<!-- Filter -->
<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;align-items:flex-end;flex-wrap:wrap;">
        <div><label class="lbl" style="font-size:.72rem;">Search</label>
        <input type="text" name="q" class="form-ctrl" style="width:240px;" placeholder="Name, email or mobile..." value="<?= htmlspecialchars($search) ?>"></div>
        <button type="submit" class="btn-gold">Search</button>
        <?php if ($search): ?><a href="<?= SITE_URL ?>/admin/users.php"
href="<?= SITE_URL ?>/admin/add-user.php"
href="<?= SITE_URL ?>/admin/edit-user.php?id= style="padding:9px 14px;background:var(--off-white);border-radius:8px;font-size:.82rem;color:#718096;text-decoration:none;border:1px solid var(--border);">Clear</a><?php endif; ?>
    </form>
</div>
<div style="margin-bottom:10px;font-size:.82rem;color:#718096;"><?= $total ?> user<?= $total!=1?'s':'' ?> found</div>
<div style="margin-bottom:15px;text-align:right;">

    <a href="<?= SITE_URL ?>/admin/add-user.php"
       style="
       background:#D4AF37;
       color:#000;
       padding:10px 18px;
       border-radius:8px;
       text-decoration:none;
       font-weight:700;
       font-size:.82rem;
       display:inline-block;
       ">
       + Add User
    </a>

</div>
<div class="adm-card">
<div style="overflow-x:auto;">
<table class="table tbl mb-0">
    <thead><tr><th>#</th><th>Client</th><th>Mobile</th><th>Location</th><th>Consultations</th><th>Joined</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($users as $i => $u): ?>
    <tr>
        <td style="font-size:.78rem;color:#718096;"><?= ($page-1)*$pp + $i + 1 ?></td>
        <td>
            <div style="display:flex;align-items:center;gap:10px;">
                <?php if ($u['profile_photo']): ?>
                <img src="/meevakeel/assets/uploads/users/<?= $u['profile_photo'] ?>" style="width:34px;height:34px;border-radius:50%;object-fit:cover;border:2px solid var(--gold);">
                <?php else: ?>
                <div style="width:34px;height:34px;background:linear-gradient(135deg,var(--primary),#1a3a6b);border-radius:50%;display:flex;align-items:center;justify-content:center;color:var(--gold);font-weight:700;font-size:.78rem;"><?= strtoupper(substr($u['name'],0,1)) ?></div>
                <?php endif; ?>
                <div>
                    <div style="font-weight:700;font-size:.83rem;"><?= htmlspecialchars($u['name']) ?></div>
                    <div style="font-size:.7rem;color:#718096;"><?= $u['email'] ?></div>
                </div>
            </div>
        </td>
        <td style="font-size:.82rem;"><?= $u['mobile'] ?></td>
        <td style="font-size:.78rem;color:#718096;"><?= ($u['city_name']??'').($u['state_name']?', '.$u['state_name']:'') ?: '—' ?></td>
        <td>
            <span style="background:rgba(10,35,66,.08);color:var(--primary);padding:3px 10px;border-radius:50px;font-size:.75rem;font-weight:700;"><?= $u['appt_count'] ?></span>
        </td>
        <td style="font-size:.78rem;color:#718096;"><?= date('d M Y', strtotime($u['created_at'])) ?></td>
        <td>
            <a href="?toggle_status=<?= $u['id'] ?>&q=<?= urlencode($search) ?>" style="font-size:.72rem;padding:4px 10px;border-radius:50px;font-weight:700;text-decoration:none;background:<?= $u['status']?'rgba(40,167,69,.1)':'rgba(220,53,69,.1)' ?>;color:<?= $u['status']?'#1a7a34':'#c0392b' ?>;">
                <?= $u['status'] ? 'Active' : 'Inactive' ?>
            </a>
        </td>
       <td>
    <div style="display:flex;gap:6px;align-items:center;">

        <a href="<?= SITE_URL ?>/admin/edit-user.php?id=<?= $u['id'] ?>" 
           style="
           background:#0A2342;
           color:#fff;
           padding:6px 12px;
           border-radius:6px;
           text-decoration:none;
           font-size:.75rem;
           font-weight:600;
           ">
           Edit
        </a>

       <a href="<?= SITE_URL ?>/admin/users.php?delete=<?= $u['id'] ?>&q=<?= urlencode($search) ?>" 
   onclick="return confirm('Are you sure you want to delete this user?')"
   style="
   background:#dc3545;
   color:#fff;
   padding:6px 12px;
   border-radius:6px;
   text-decoration:none;
   font-size:.75rem;
   font-weight:600;
   ">
   Delete
</a>

    </div>
</td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($users)): ?>
    <tr><td colspan="8" style="text-align:center;padding:40px;color:#718096;">No users 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="?<?= 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(); ?>