<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__.'/../inc/config.php';
require_once __DIR__.'/../inc/db.php';
require_once __DIR__.'/../inc/helpers.php';

if(empty($_SESSION['admin_id'])){ 
    header('Location: login.php'); 
    exit; 
}

$is_admin = (isset($_SESSION['admin_role']) && $_SESSION['admin_role'] === 'admin');
$ads_cost_daily = (float)setting('ADS_COST_DAILY', '0');

// Fungsi bantuan untuk mengelak ralat pembahagian dengan sifar
function calculate_diff_percentage($current, $previous) {
    if ($previous > 0) {
        return (($current - $previous) / $previous) * 100;
    }
    return $current > 0 ? 100.0 : 0.0;
}

// -- DATA HARIAN (Query Dibaiki) --
$today_data = db()->query("SELECT IFNULL(SUM(amount),0) as s, COUNT(id) as c FROM orders WHERE status IN ('Paid','Shipped') AND date(created_at) = date('now', '+8 hours')")->fetch();
$visits_today = (int)db()->query("SELECT COUNT(id) c FROM visits WHERE date(created_at) = date('now', '+8 hours')")->fetch()['c'];
$revenue_today = (float)$today_data['s'];
$paid_orders_today = (int)$today_data['c'];

// -- DATA SEMALAM (Query Dibaiki) --
$yesterday_data = db()->query("SELECT IFNULL(SUM(amount),0) as s, COUNT(id) as c FROM orders WHERE status IN ('Paid','Shipped') AND date(created_at) = date('now', '+8 hours', '-1 day')")->fetch();
$visits_yesterday = (int)db()->query("SELECT COUNT(id) c FROM visits WHERE date(created_at) = date('now', '+8 hours', '-1 day')")->fetch()['c'];
$revenue_yesterday = (float)$yesterday_data['s'];
$paid_orders_yesterday = (int)$yesterday_data['c'];

// -- PENGIRAAN PERBEZAAN HARIAN --
$visits_diff_day = calculate_diff_percentage($visits_today, $visits_yesterday);
$revenue_diff_day = calculate_diff_percentage($revenue_today, $revenue_yesterday);
$paid_orders_diff_day = calculate_diff_percentage($paid_orders_today, $paid_orders_yesterday);

// Metrik lain untuk hari ini
$conv_rate_today = $visits_today > 0 ? round(($paid_orders_today / $visits_today) * 100, 2) : 0;
$cpa_today = $paid_orders_today > 0 ? round($ads_cost_daily / $paid_orders_today, 2) : 0;
$roi_today = $ads_cost_daily > 0 ? round((($revenue_today - $ads_cost_daily) / $ads_cost_daily) * 100, 2) : 0;
$roas_today = $ads_cost_daily > 0 ? round($revenue_today / $ads_cost_daily, 2) : 0;

// -- DATA BULANAN (Hanya untuk Admin) --
if ($is_admin) {
    // -- DATA BULAN INI (Query Dibaiki) --
    $this_month_data = db()->query("SELECT IFNULL(SUM(amount),0) as s, COUNT(id) as c FROM orders WHERE status IN ('Paid','Shipped') AND strftime('%Y-%m', created_at) = strftime('%Y-%m', 'now', '+8 hours')")->fetch();
    $visits_this_month = (int)db()->query("SELECT COUNT(id) c FROM visits WHERE strftime('%Y-%m', created_at) = strftime('%Y-%m', 'now', '+8 hours')")->fetch()['c'];
    $revenue_this_month = (float)$this_month_data['s'];
    $paid_orders_this_month = (int)$this_month_data['c'];

    // -- DATA BULAN LEPAS (Query Dibaiki) --
    $last_month_data = db()->query("SELECT IFNULL(SUM(amount),0) as s, COUNT(id) as c FROM orders WHERE status IN ('Paid','Shipped') AND strftime('%Y-%m', created_at) = strftime('%Y-%m', 'now', '+8 hours', '-1 month')")->fetch();
    $visits_last_month = (int)db()->query("SELECT COUNT(id) c FROM visits WHERE strftime('%Y-%m', created_at) = strftime('%Y-%m', 'now', '+8 hours', '-1 month')")->fetch()['c'];
    $revenue_last_month = (float)$last_month_data['s'];
    $paid_orders_last_month = (int)$last_month_data['c'];

    // -- PENGIRAAN PERBEZAAN BULANAN --
    $visits_diff_month = calculate_diff_percentage($visits_this_month, $visits_last_month);
    $revenue_diff_month = calculate_diff_percentage($revenue_this_month, $revenue_last_month);
    $paid_orders_diff_month = calculate_diff_percentage($paid_orders_this_month, $paid_orders_last_month);
    
    // Metrik lain untuk bulan ini
    $days_so_far = (int)date('j');
    $ads_cost_this_month = $ads_cost_daily * $days_so_far;
    $conv_rate_this_month = $visits_this_month > 0 ? round(($paid_orders_this_month / $visits_this_month) * 100, 2) : 0;
    $cpa_this_month = $paid_orders_this_month > 0 ? round($ads_cost_this_month / $paid_orders_this_month, 2) : 0;
    $roi_this_month = $ads_cost_this_month > 0 ? round((($revenue_this_month - $ads_cost_this_month) / $ads_cost_this_month) * 100, 2) : 0;
    $roas_this_month = $ads_cost_this_month > 0 ? round($revenue_this_month / $ads_cost_this_month, 2) : 0;
}

$recent_orders = db()->query("SELECT id, name, amount, status FROM orders ORDER BY id DESC LIMIT 5")->fetchAll();
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../public/assets/css/style.css">
    <title>Dashboard</title>
    <style>
        .admin-wrapper { display: flex; align-items: flex-start; gap: 24px; }
        .admin-sidebar { width: 220px; flex-shrink: 0; }
        .admin-content { flex-grow: 1; }
        .main-grid { display: grid; grid-template-columns: 1fr; gap: 24px; margin-bottom: 24px; }
        @media (min-width: 1200px) { .main-grid { grid-template-columns: 1fr 1fr; } }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; }
        .stat-card { background: #fff; border: 1px solid #e5e7eb; border-radius: 14px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        .stat-card h3 { margin: 0 0 8px 0; font-size: 15px; color: #64748b; font-weight: 600; }
        .stat-card p { margin: 0; font-size: 26px; font-weight: 700; color: #0f172a; }
        .stat-card .comparison { font-size: 13px; font-weight: 600; margin-top: 6px; }
        .positive { color: #16a34a; }
        .negative { color: #dc2626; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #e5e7eb; }
        th { background-color: #f8fafc; }
        .status-paid, .status-shipped { background-color: #dcfce7; color: #166534; padding: 4px 8px; border-radius: 999px; font-size: 12px; font-weight: bold; display: inline-block;}
        .status-pending, .status-payment-review, .status-diproses { background-color: #fef9c3; color: #854d0e; padding: 4px 8px; border-radius: 999px; font-size: 12px; font-weight: bold; display: inline-block;}
        .status-cancelled { background-color: #fee2e2; color: #991b1b; padding: 4px 8px; border-radius: 999px; font-size: 12px; font-weight: bold; display: inline-block;}
    </style>
</head>
<body>
<div class="container">
    <div class="admin-wrapper">
        <aside class="admin-sidebar"><?php require_once '_menu.php'; ?></aside>
        <main class="admin-content">
            <h1>Dashboard</h1>

            <div class="main-grid">
                <div class="card">
                    <h2 style="margin-top:0;">Prestasi Hari Ini</h2>
                    <div class="stats-grid">
                        <div class="stat-card">
                            <h3>Pelawat</h3><p><?= $visits_today ?></p>
                            <div class="comparison <?= $visits_diff_day >= 0 ? 'positive' : 'negative' ?>">
                                <?= $visits_diff_day >= 0 ? '↑' : '↓' ?> <?= number_format(abs($visits_diff_day), 0) ?>% vs semalam
                            </div>
                        </div>
                        <div class="stat-card">
                            <h3>Jualan</h3><p><?= money($revenue_today) ?></p>
                            <div class="comparison <?= $revenue_diff_day >= 0 ? 'positive' : 'negative' ?>">
                                <?= $revenue_diff_day >= 0 ? '↑' : '↓' ?> <?= number_format(abs($revenue_diff_day), 0) ?>% vs semalam
                            </div>
                        </div>
                        <div class="stat-card">
                            <h3>Pesanan Berbayar</h3><p><?= $paid_orders_today ?></p>
                            <div class="comparison <?= $paid_orders_diff_day >= 0 ? 'positive' : 'negative' ?>">
                                <?= $paid_orders_diff_day >= 0 ? '↑' : '↓' ?> <?= number_format(abs($paid_orders_diff_day), 0) ?>% vs semalam
                            </div>
                        </div>
                        <div class="stat-card"><h3>Kadar Penukaran</h3><p><?= $conv_rate_today ?>%</p></div>
                        <div class="stat-card"><h3>CPA</h3><p><?= money($cpa_today) ?></p></div>
                        <div class="stat-card"><h3>ROI</h3><p class="<?= $roi_today >= 0 ? 'positive' : 'negative' ?>"><?= round($roi_today) ?>%</p></div>
                        <div class="stat-card"><h3>ROAS</h3><p><?= e(number_format($roas_today, 2)) ?></p></div>
                    </div>
                </div>
                
                <?php if ($is_admin): ?>
                <div class="card">
                    <h2 style="margin-top:0;">Prestasi Bulan Ini</h2>
                     <div class="stats-grid">
                        <div class="stat-card">
                            <h3>Pelawat</h3><p><?= $visits_this_month ?></p>
                             <div class="comparison <?= $visits_diff_month >= 0 ? 'positive' : 'negative' ?>">
                                <?= $visits_diff_month >= 0 ? '↑' : '↓' ?> <?= number_format(abs($visits_diff_month), 0) ?>% vs bulan lepas
                            </div>
                        </div>
                        <div class="stat-card">
                            <h3>Jualan</h3><p><?= money($revenue_this_month) ?></p>
                            <div class="comparison <?= $revenue_diff_month >= 0 ? 'positive' : 'negative' ?>">
                                <?= $revenue_diff_month >= 0 ? '↑' : '↓' ?> <?= number_format(abs($revenue_diff_month), 0) ?>% vs bulan lepas
                            </div>
                        </div>
                        <div class="stat-card">
                            <h3>Pesanan Berbayar</h3><p><?= $paid_orders_this_month ?></p>
                             <div class="comparison <?= $paid_orders_diff_month >= 0 ? 'positive' : 'negative' ?>">
                                <?= $paid_orders_diff_month >= 0 ? '↑' : '↓' ?> <?= number_format(abs($paid_orders_diff_month), 0) ?>% vs bulan lepas
                            </div>
                        </div>
                        <div class="stat-card"><h3>Kadar Penukaran</h3><p><?= $conv_rate_this_month ?>%</p></div>
                        <div class="stat-card"><h3>CPA</h3><p><?= money($cpa_this_month) ?></p></div>
                        <div class="stat-card"><h3>ROI</h3><p class="<?= $roi_this_month >= 0 ? 'positive' : 'negative' ?>"><?= round($roi_this_month) ?>%</p></div>
                        <div class="stat-card"><h3>ROAS</h3><p><?= e(number_format($roas_this_month, 2)) ?></p></div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="recent-orders card">
                <h2>Pesanan Terkini</h2>
                <table>
                    <tr><th>ID</th><th>Nama</th><th>Jumlah</th><th>Status</th></tr>
                    <?php foreach($recent_orders as $order): ?>
                    <tr>
                        <td><a href="orders.php">#<?= e($order['id']) ?></a></td>
                        <td><?= e($order['name']) ?></td>
                        <td><?= money($order['amount']) ?></td>
                        <td><span class="status-<?= strtolower(str_replace(' ', '-', e($order['status']))) ?>"><?= e($order['status']) ?></span></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
            </div>
        </main>
    </div>
</div>
<script>
    const refreshInterval = 30000; 
    setTimeout(function() {
        window.location.reload();
    }, refreshInterval);
</script>
</body>
</html>