<?php
$pageTitle  = 'Dashboard';
$activePage = 'dashboard';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../db.php';

// ─── Stats ──────────────────────────────────────────────────────────────────
$totalUsers    = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$newThisWeek   = $pdo->query("SELECT COUNT(*) FROM users WHERE created_at >= NOW() - INTERVAL 7 DAY")->fetchColumn();
$activeWeek    = $pdo->query("
    SELECT COUNT(DISTINCT chat_id) FROM (
        SELECT chat_id FROM diet_plans    WHERE created_at >= NOW() - INTERVAL 7 DAY
        UNION ALL
        SELECT chat_id FROM workout_plans WHERE created_at >= NOW() - INTERVAL 7 DAY
        UNION ALL
        SELECT chat_id FROM progress      WHERE logged_at  >= NOW() - INTERVAL 7 DAY
    ) t
")->fetchColumn();
$totalDiets    = $pdo->query("SELECT COUNT(*) FROM diet_plans")->fetchColumn();
$totalWorkouts = $pdo->query("SELECT COUNT(*) FROM workout_plans")->fetchColumn();
$totalLogs     = $pdo->query("SELECT COUNT(*) FROM progress")->fetchColumn();
$creditsCirc   = $pdo->query("SELECT COALESCE(SUM(credits),0) FROM users")->fetchColumn();
$activeSubs    = $pdo->query("SELECT COUNT(*) FROM subscriptions WHERE status='active' AND expires_at > NOW()")->fetchColumn();
$creditsSpent  = $pdo->query("SELECT COALESCE(ABS(SUM(amount)),0) FROM credit_transactions WHERE amount < 0")->fetchColumn();

// Recent transactions (last 10)
$recentTx = $pdo->query("
    SELECT ct.*, u.first_name
    FROM credit_transactions ct
    LEFT JOIN users u ON u.chat_id = ct.chat_id
    ORDER BY ct.id DESC LIMIT 10
")->fetchAll(PDO::FETCH_ASSOC);

// Signup chart — last 7 days
$signupData  = $pdo->query("
    SELECT DATE(created_at) AS day, COUNT(*) AS cnt
    FROM users WHERE created_at >= NOW() - INTERVAL 7 DAY
    GROUP BY DATE(created_at) ORDER BY day
")->fetchAll(PDO::FETCH_ASSOC);
$chartLabels = json_encode(array_column($signupData, 'day'));
$chartData   = json_encode(array_column($signupData, 'cnt'));

// Top 5 users by credits spent
$topSpenders = $pdo->query("
    SELECT u.first_name, ct.chat_id, ABS(SUM(ct.amount)) AS spent
    FROM credit_transactions ct
    JOIN users u ON u.chat_id = ct.chat_id
    WHERE ct.amount < 0
    GROUP BY ct.chat_id
    ORDER BY spent DESC LIMIT 5
")->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/_header.php';
?>

<div class="page-header d-flex justify-content-between align-items-center">
    <h4 class="fw-bold mb-0">Dashboard</h4>
    <span class="text-muted small"><?= date('d M Y, H:i') ?></span>
</div>

<!-- Stat cards -->
<div class="row g-3 mb-4">
<?php
$cards = [
    ['👥', 'Total Users',      number_format($totalUsers),    "+{$newThisWeek} this week",  'bg-primary bg-opacity-10',   'text-primary'],
    ['🟢', 'Active (7 days)',  number_format($activeWeek),    'unique users',                'bg-success bg-opacity-10',   'text-success'],
    ['🍽️', 'Diet Plans',       number_format($totalDiets),    'generated',                  'bg-warning bg-opacity-10',   'text-warning'],
    ['💪', 'Workout Plans',    number_format($totalWorkouts), 'generated',                  'bg-info bg-opacity-10',      'text-info'],
    ['📈', 'Weight Logs',      number_format($totalLogs),     'entries',                    'bg-secondary bg-opacity-10', 'text-secondary'],
    ['💳', 'Credits In Circ.', number_format($creditsCirc),   'held by users',              'bg-primary bg-opacity-10',   'text-primary'],
    ['💸', 'Credits Spent',    number_format($creditsSpent),  'all time',                   'bg-danger bg-opacity-10',    'text-danger'],
    ['⭐', 'Subscribers',      number_format($activeSubs),    'active subscriptions',        'bg-warning bg-opacity-10',   'text-warning'],
];
foreach ($cards as [$icon, $label, $value, $sub, $bg, $ic]): ?>
<div class="col-6 col-md-4 col-xl-3">
    <div class="card stat-card">
        <div class="card-body d-flex align-items-center gap-3 py-3">
            <div class="icon-box <?= $bg ?> <?= $ic ?>"><?= $icon ?></div>
            <div>
                <div class="fw-bold fs-5 lh-1"><?= $value ?></div>
                <div class="text-muted" style="font-size:.78rem"><?= $label ?></div>
                <div style="font-size:.7rem;color:#9ca3af"><?= $sub ?></div>
            </div>
        </div>
    </div>
</div>
<?php endforeach; ?>
</div>

<div class="row g-3">
    <!-- Signup chart -->
    <div class="col-md-5">
        <div class="card table-card h-100">
            <div class="card-header bg-white border-0 pt-3 pb-0 d-flex justify-content-between">
                <h6 class="fw-semibold mb-0">New Signups (Last 7 Days)</h6>
            </div>
            <div class="card-body">
                <canvas id="signupChart" height="180"></canvas>
            </div>
        </div>
    </div>

    <!-- Recent transactions -->
    <div class="col-md-7">
        <div class="card table-card">
            <div class="card-header bg-white border-0 pt-3 pb-0 d-flex justify-content-between align-items-center">
                <h6 class="fw-semibold mb-0">Recent Transactions</h6>
                <a href="transactions.php" class="small text-decoration-none text-primary">View all →</a>
            </div>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead><tr><th>User</th><th>Amount</th><th>Type</th><th>Date</th></tr></thead>
                    <tbody>
                    <?php foreach ($recentTx as $tx): ?>
                    <tr>
                        <td>
                            <a href="user.php?id=<?= $tx['chat_id'] ?>" class="text-decoration-none fw-semibold text-dark">
                                <?= htmlspecialchars($tx['first_name'] ?? 'User') ?>
                            </a>
                            <div class="text-muted" style="font-size:.7rem"><?= $tx['chat_id'] ?></div>
                        </td>
                        <td class="fw-bold <?= $tx['amount'] > 0 ? 'text-success' : 'text-danger' ?>">
                            <?= $tx['amount'] > 0 ? '+' : '' ?><?= $tx['amount'] ?>
                        </td>
                        <td><span class="badge bg-secondary-subtle text-secondary" style="font-size:.7rem"><?= htmlspecialchars($tx['type']) ?></span></td>
                        <td class="text-muted" style="font-size:.75rem"><?= date('d M, H:i', strtotime($tx['created_at'])) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($recentTx)): ?>
                    <tr><td colspan="4" class="text-center text-muted py-3">No transactions yet.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Top spenders -->
<?php if (!empty($topSpenders)): ?>
<div class="row g-3 mt-0">
    <div class="col-md-5">
        <div class="card table-card">
            <div class="card-header bg-white border-0 pt-3 pb-0">
                <h6 class="fw-semibold mb-0">Top Credit Spenders</h6>
            </div>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead><tr><th>#</th><th>User</th><th>Credits Spent</th></tr></thead>
                    <tbody>
                    <?php foreach ($topSpenders as $i => $s): ?>
                    <tr>
                        <td class="text-muted"><?= $i + 1 ?></td>
                        <td>
                            <a href="user.php?id=<?= $s['chat_id'] ?>" class="text-decoration-none fw-semibold text-dark">
                                <?= htmlspecialchars($s['first_name'] ?? 'User') ?>
                            </a>
                        </td>
                        <td><span class="badge bg-danger-subtle text-danger"><?= (int)$s['spent'] ?> cr</span></td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('signupChart'), {
    type: 'bar',
    data: {
        labels: <?= $chartLabels ?>,
        datasets: [{
            label: 'New Users',
            data: <?= $chartData ?>,
            backgroundColor: 'rgba(99,102,241,.65)',
            borderColor: '#6366f1',
            borderRadius: 6,
            borderSkipped: false,
        }]
    },
    options: {
        responsive: true,
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true, ticks: { stepSize: 1, precision: 0 } } }
    }
});
</script>

<?php require_once __DIR__ . '/_footer.php'; ?>
