<?php
/**
 * Enfhess Marketplace - Financial Dashboard
 * All-in-one file: Filter logic, Cards, Chart, and Table.
 */
require_once __DIR__ . '/../config/config.php';
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') { header('Location: ../login.php'); exit; }

// 1. Fetch Dynamic Currency
$settings = $pdo->query("SELECT currency FROM general_settings LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$currency = $settings['currency'] ?? 'USD';

// 2. Filter Logic (Shared across all sections)
$filter = $_GET['filter'] ?? '30_days';
$start = $_GET['start_date'] ?? '';
$end = $_GET['end_date'] ?? '';

$date_sql = match($filter) {
    'this_month' => " AND MONTH(created_at) = MONTH(NOW()) AND YEAR(created_at) = YEAR(NOW())",
    'prev_month' => " AND MONTH(created_at) = MONTH(DATE_SUB(NOW(), INTERVAL 1 MONTH))",
    'custom'     => ($start && $end) ? " AND created_at BETWEEN '$start 00:00:00' AND '$end 23:59:59'" : "",
    default      => " AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"
};

// Data Queries
$stats = $pdo->query("SELECT SUM(price) as received, SUM(price - net_seller_income) as profit FROM orders WHERE payment_status = 'Paid' $date_sql")->fetch();
$withdraw = $pdo->query("SELECT SUM(withdrawal_amount) as total FROM withdrawal_requests WHERE withdrawal_status = 'Accepted' $date_sql")->fetch();
$withdrawals = $pdo->query("SELECT * FROM withdrawal_requests WHERE withdrawal_status = 'Accepted' $date_sql ORDER BY accepted_at DESC")->fetchAll();

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

<body class="bg-slate-950 text-white">
    <?php require_once __DIR__ . '/admin-sidebar.php'; ?>
    <main class="lg:ml-64 p-8">
        
        <form method="GET" class="mb-8 flex gap-4 bg-slate-900 p-4 rounded-xl border border-slate-800">
            <select name="filter" onchange="this.form.submit()" class="bg-slate-800 border border-slate-700 rounded px-3 py-2 text-sm">
                <option value="30_days" <?=($filter=='30_days')?'selected':''?>>Last 30 Days</option>
                <option value="this_month" <?=($filter=='this_month')?'selected':''?>>This Month</option>
                <option value="prev_month" <?=($filter=='prev_month')?'selected':''?>>Previous Month</option>
                <option value="custom" <?=($filter=='custom')?'selected':''?>>Custom Range</option>
            </select>
            <?php if($filter == 'custom'): ?>
                <input type="date" name="start_date" value="<?=$start?>" class="bg-slate-800 border border-slate-700 rounded px-2">
                <input type="date" name="end_date" value="<?=$end?>" class="bg-slate-800 border border-slate-700 rounded px-2">
                <button type="submit" class="bg-blue-600 px-4 rounded font-bold">Apply</button>
            <?php endif; ?>
        </form>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-slate-900 p-6 rounded-xl border border-slate-800">
                <div class="text-xs uppercase text-slate-500">Total Received</div>
                <div class="text-2xl text-emerald-400 font-bold"><?= htmlspecialchars(format_currency($stats['received'] ?? 0), ENT_QUOTES, 'UTF-8') ?></div>
            </div>
            <div class="bg-slate-900 p-6 rounded-xl border border-slate-800">
                <div class="text-xs uppercase text-slate-500">Total Withdraw</div>
                <div class="text-xl text-rose-400 font-bold"><?= htmlspecialchars(format_currency($withdraw['total'] ?? 0), ENT_QUOTES, 'UTF-8') ?></div>
            </div>
            <div class="bg-slate-900 p-6 rounded-xl border border-slate-800">
                <div class="text-xs uppercase text-slate-500">Net Profit</div>
                <div class="text-xl text-purple-400 font-bold"><?= htmlspecialchars(format_currency($stats['profit'] ?? 0), ENT_QUOTES, 'UTF-8') ?></div>
            </div>
        </div>

        <div class="bg-slate-900 p-6 rounded-xl border border-slate-800 mb-8">
            <canvas id="financeChart" height="80"></canvas>
        </div>

        <div class="bg-slate-900 p-6 rounded-xl border border-slate-800">
            <h3 class="mb-4 font-bold text-sm text-slate-400">Accepted Withdrawals</h3>
            <table class="w-full text-left text-xs">
                <thead><tr class="text-slate-500"><th>User</th><th>Amount</th><th>Method</th><th>Date</th></tr></thead>
                <tbody>
                    <?php foreach($withdrawals as $w): ?>
                    <tr class="border-t border-slate-800">
                        <td class="p-3"><?=$w['user_name']?></td>
                        <td class="p-3 text-rose-400"><?=htmlspecialchars(format_currency($w['withdrawal_amount']), ENT_QUOTES, 'UTF-8')?></td>
                        <td class="p-3"><?=$w['withdrawal_method']?></td>
                        <td class="p-3"><?=date('M d, Y', strtotime($w['accepted_at']))?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        const cur = "<?= addslashes(currency_symbol()) ?>";
        new Chart(document.getElementById('financeChart'), {
            type: 'bar',
            data: {
                labels: ['Financial Overview'],
                datasets: [
                    { label: 'Received', data: [<?= (float)($stats['received'] ?? 0) ?>], backgroundColor: '#10b981' },
                    { label: 'Withdraw', data: [<?= (float)($withdraw['total'] ?? 0) ?>], backgroundColor: '#f43f5e' },
                    { label: 'Profit', data: [<?= (float)($stats['profit'] ?? 0) ?>], backgroundColor: '#a855f7' }
                ]
            },
            options: {
                plugins: { tooltip: { callbacks: { label: (ctx) => cur + ctx.raw.toLocaleString() } } },
                scales: { y: { ticks: { callback: (val) => cur + val.toLocaleString() } } }
            }
        });
    </script>
</body>
