<?php
/**
 * Enfhess Marketplace - Premium Admin Hub Reports & Analytics Panel
 * Path: admin/reports.php
 */
require_once __DIR__ . '/../config/config.php';

if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

// Capture Filter Inputs
$filter = $_GET['filter'] ?? 'all';
$start = $_GET['start_date'] ?? '';
$end = $_GET['end_date'] ?? '';

// Build Query Condition
$where = " WHERE payment_status = 'Paid' ";
if ($filter === 'this_month') {
    $where .= " AND created_at >= DATE_FORMAT(NOW(), '%Y-%m-01 00:00:00')";
} elseif ($filter === 'previous_month') {
    $where .= " AND created_at >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH), '%Y-%m-01 00:00:00') AND created_at <= LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH))";
} elseif ($filter === 'custom' && !empty($start) && !empty($end)) {
    $where .= " AND created_at BETWEEN '$start 00:00:00' AND '$end 23:59:59'";
}

// Execute Metrics Query
// Net Profit = (Total Price - Seller's Net Income)
$query = "SELECT COUNT(*) as total_sold, SUM(price) as total_revenue, SUM(price - net_seller_income) as total_profit FROM orders $where";
$stats = $pdo->query($query)->fetch(PDO::FETCH_ASSOC);

// Fetch Withdrawal Status for Chart
$withdrawQuery = $pdo->query("SELECT withdrawal_status, COUNT(*) as count FROM withdrawal_requests GROUP BY withdrawal_status")->fetchAll(PDO::FETCH_KEY_PAIR);

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">
    <?php require_once __DIR__ . '/admin-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-7xl mx-auto space-y-8">
            <div class="flex flex-wrap items-center justify-between border-b border-slate-900/60 pb-6 gap-4">
                <div>
                    <h1 class="text-3xl font-extrabold tracking-tight">Marketplace Analytics</h1>
                    <p class="text-sm text-nftTextGray mt-1">Platform financial performance and liquidity tracking.</p>
                </div>

                <form method="GET" action="reports.php" class="flex items-center gap-2 bg-slate-950/60 p-2 rounded-xl border border-slate-900">
                    <select name="filter" onchange="this.form.submit()" class="bg-slate-900 text-xs px-3 py-2 rounded-lg border border-slate-800 focus:border-nftAccentCyan outline-none">
                        <option value="all" <?php if($filter=='all') echo 'selected'; ?>>All Time</option>
                        <option value="this_month" <?php if($filter=='this_month') echo 'selected'; ?>>This Month</option>
                        <option value="previous_month" <?php if($filter=='previous_month') echo 'selected'; ?>>Previous Month</option>
                        <option value="custom" <?php if($filter=='custom') echo 'selected'; ?>>Custom Range</option>
                    </select>
                    <?php if($filter == 'custom'): ?>
                        <input type="date" name="start_date" value="<?=$start?>" onchange="this.form.submit()" class="bg-slate-900 text-xs px-2 py-1.5 rounded-lg border border-slate-800">
                        <input type="date" name="end_date" value="<?=$end?>" onchange="this.form.submit()" class="bg-slate-900 text-xs px-2 py-1.5 rounded-lg border border-slate-800">
                    <?php endif; ?>
                </form>
            </div>

            <?php require_once __DIR__ . '/report-card.php'; ?>
            <?php require_once __DIR__ . '/report-chart.php'; ?>
        </div>
    </main>
</body>
</html>