<?php
require_once __DIR__ . '/../config.php';
require_login();
if (!is_admin()) die("Access denied");

header('Content-Type: text/html; charset=utf-8');

// --- Handle AJAX search request ---
if (isset($_GET['ajax']) && $_GET['ajax'] === '1' && !empty($_GET['q'])) {
    $q = '%' . $_GET['q'] . '%';
    $stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE name LIKE ? OR email LIKE ? ORDER BY id DESC LIMIT 10");
    $stmt->execute([$q, $q]);
    $users = $stmt->fetchAll();
    foreach ($users as $u) {
        echo '<div class="user-item" data-id="' . h($u['id']) . '">'
           . h($u['name']) . ' <small>(' . h($u['email']) . ')</small></div>';
    }
    exit;
}

// --- If user selected ---
$selected_user = null;
$stats = [];
if (isset($_GET['user_id']) && is_numeric($_GET['user_id'])) {
    $user_id = (int)$_GET['user_id'];
    $stmt = $pdo->prepare("SELECT id, name, email, balance FROM users WHERE id=?");
    $stmt->execute([$user_id]);
    $selected_user = $stmt->fetch();

    if ($selected_user) {
        $stats['total_orders']     = $pdo->query("SELECT COUNT(*) FROM orders WHERE user_id=$user_id")->fetchColumn();
        $stats['completed_orders'] = $pdo->query("SELECT COUNT(*) FROM orders WHERE user_id=$user_id AND status='completed'")->fetchColumn();
        $stats['cancelled_orders'] = $pdo->query("SELECT COUNT(*) FROM orders WHERE user_id=$user_id AND status='cancelled'")->fetchColumn();
        $stats['total_recharge']   = $pdo->query("SELECT SUM(amount) FROM recharges WHERE user_id=$user_id")->fetchColumn() ?? 0;
        $stats['last_recharge']    = $pdo->query("SELECT MAX(created_at) FROM recharges WHERE user_id=$user_id")->fetchColumn();
        $stats['last_order']       = $pdo->query("SELECT MAX(created_at) FROM orders WHERE user_id=$user_id")->fetchColumn();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Statistics</title>
<style>
body {
    font-family: 'Poppins', sans-serif;
    background: linear-gradient(135deg, #667eea, #764ba2);
    margin: 0; padding: 0;
    display: flex; justify-content: center; align-items: flex-start;
    min-height: 100vh;
}
.container {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
    margin-top: 40px;
    width: 95%; max-width: 1100px;
    padding: 40px 50px;
}
h1 {
    text-align: center;
    color: #333;
    margin-bottom: 30px;
    font-size: 28px;
}
.search-box {
    position: relative;
    max-width: 400px;
    margin: 0 auto 25px;
}
.search-box input {
    width: 100%;
    padding: 12px 15px;
    border-radius: 10px;
    border: 1px solid #ccc;
    font-size: 15px;
}
.suggestions {
    position: absolute;
    top: 100%;
    left: 0; right: 0;
    background: white;
    border: 1px solid #ddd;
    border-radius: 10px;
    max-height: 250px;
    overflow-y: auto;
    box-shadow: 0 5px 12px rgba(0,0,0,0.1);
    display: none;
    z-index: 99;
}
.user-item {
    padding: 10px 15px;
    cursor: pointer;
    transition: background 0.2s;
}
.user-item:hover {
    background: #f0f0ff;
}
.user-item small {
    color: #777;
}
.stats-box {
    background: #f8f9fc;
    border-radius: 14px;
    padding: 25px 30px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.stats-box h2 {
    text-align: center;
    margin-bottom: 10px;
    color: #333;
}
.stats-box p {
    text-align: center;
    color: #555;
    font-size: 15px;
    margin-bottom: 25px;
}
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
    gap: 20px;
}
.stat-card {
    background: white;
    border-radius: 12px;
    padding: 20px 15px;
    text-align: center;
    box-shadow: 0 3px 12px rgba(0,0,0,0.08);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 18px rgba(0,0,0,0.1);
}
.stat-card h3 {
    font-size: 16px;
    color: #555;
    margin-bottom: 8px;
}
.stat-card strong {
    font-size: 26px;
    color: #5a67d8;
}
</style>
</head>
<body>
<div class="container">
    <h1>🔍 User Statistics Dashboard</h1>

    <div class="search-box">
        <input type="text" id="userSearch" placeholder="Type name or email...">
        <div class="suggestions" id="suggestions"></div>
    </div>

    <?php if ($selected_user): ?>
    <div class="stats-box">
        <h2><?=h($selected_user['name'])?>’s Summary</h2>
        <p><strong>Email:</strong> <?=h($selected_user['email'])?> | 
           <strong>Balance:</strong> <?=number_format($selected_user['balance'], 2)?> ৳</p>

        <div class="stats-grid">
            <div class="stat-card"><h3>Total Orders</h3><strong><?=h($stats['total_orders'])?></strong></div>
            <div class="stat-card"><h3>Completed Orders</h3><strong><?=h($stats['completed_orders'])?></strong></div>
            <div class="stat-card"><h3>Cancelled Orders</h3><strong><?=h($stats['cancelled_orders'])?></strong></div>
            <div class="stat-card"><h3>Total Recharged</h3><strong><?=number_format($stats['total_recharge'], 2)?> ৳</strong></div>
            <div class="stat-card"><h3>Last Recharge</h3><strong><?=h($stats['last_recharge'] ?: '—')?></strong></div>
            <div class="stat-card"><h3>Last Order</h3><strong><?=h($stats['last_order'] ?: '—')?></strong></div>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
const input = document.getElementById('userSearch');
const suggBox = document.getElementById('suggestions');

input.addEventListener('input', () => {
    const q = input.value.trim();
    if (q.length < 2) {
        suggBox.style.display = 'none';
        return;
    }
    fetch(`user_stats.php?ajax=1&q=${encodeURIComponent(q)}`)
        .then(res => res.text())
        .then(html => {
            suggBox.innerHTML = html;
            suggBox.style.display = html.trim() ? 'block' : 'none';
            document.querySelectorAll('.user-item').forEach(el => {
                el.addEventListener('click', () => {
                    const id = el.getAttribute('data-id');
                    window.location = `user_stats.php?user_id=${id}`;
                });
            });
        });
});
document.addEventListener('click', e => {
    if (!e.target.closest('.search-box')) suggBox.style.display = 'none';
});
</script>
</body>
</html>