<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/helpers.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$startDate = trim($_GET['start_date'] ?? '');
$endDate = trim($_GET['end_date'] ?? '');
$status = trim($_GET['status'] ?? '');

$allowedStatuses = ['paid', 'packed', 'shipped', 'done'];
$where = ["o.status IN ('paid','packed','shipped','done')"];
$params = [];

if ($status !== '' && in_array($status, $allowedStatuses, true)) {
    $where[] = 'o.status = ?';
    $params[] = $status;
}

if ($startDate !== '' && $endDate !== '') {
    $where[] = 'o.created_at BETWEEN ? AND ?';
    $params[] = date('Y-m-d 00:00:00', strtotime($startDate));
    $params[] = date('Y-m-d 23:59:59', strtotime($endDate));
} elseif ($startDate !== '') {
    $where[] = 'o.created_at >= ?';
    $params[] = date('Y-m-d 00:00:00', strtotime($startDate));
} elseif ($endDate !== '') {
    $where[] = 'o.created_at <= ?';
    $params[] = date('Y-m-d 23:59:59', strtotime($endDate));
}

$whereSql = 'WHERE ' . implode(' AND ', $where);

$summaryStmt = $pdo->prepare("SELECT COUNT(*) AS total_tx, COALESCE(SUM(o.total),0) AS total_revenue
    FROM orders o {$whereSql}");
$summaryStmt->execute($params);
$summary = $summaryStmt->fetch();

$itemStmt = $pdo->prepare("SELECT COALESCE(SUM(oi.qty),0) AS total_items
    FROM order_items oi
    JOIN orders o ON o.id = oi.order_id
    {$whereSql}");
$itemStmt->execute($params);
$totalItems = (int) $itemStmt->fetchColumn();

$topStmt = $pdo->prepare("SELECT p.name, SUM(oi.qty) AS qty
    FROM order_items oi
    JOIN orders o ON o.id = oi.order_id
    JOIN products p ON p.id = oi.product_id
    {$whereSql}
    GROUP BY p.id, p.name
    ORDER BY qty DESC
    LIMIT 5");
$topStmt->execute($params);
$topProducts = $topStmt->fetchAll();

$listStmt = $pdo->prepare("SELECT o.code, o.total, o.status, o.created_at, u.name AS customer_name
    FROM orders o
    JOIN users u ON u.id = o.user_id
    {$whereSql}
    ORDER BY o.created_at DESC");
$listStmt->execute($params);
$orders = $listStmt->fetchAll();
?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <title>Laporan Online</title>
    <style>
        @page { size: A4; margin: 12mm; }
        body { font-family: Arial, sans-serif; color: #111; }
        .header { text-align: center; margin-bottom: 16px; }
        table { width: 100%; border-collapse: collapse; margin-top: 12px; }
        th, td { border: 1px solid #ccc; padding: 6px 8px; font-size: 12px; }
        th { background: #f3f3f3; }
        .summary { margin: 12px 0; }
        .summary div { margin-bottom: 4px; }
    </style>
</head>
<body onload="window.print()">
    <div class="header">
        <h2>Laporan Penjualan Online</h2>
        <div>Periode: <?= sanitize($startDate ?: '-'); ?> s/d <?= sanitize($endDate ?: '-'); ?></div>
    </div>

    <div class="summary">
        <div>Total Transaksi: <?= (int) $summary['total_tx']; ?></div>
        <div>Total Omzet: <?= format_currency($summary['total_revenue']); ?></div>
        <div>Item Terjual: <?= $totalItems; ?></div>
    </div>

    <h4>Produk Terlaris</h4>
    <table>
        <thead>
            <tr><th>Produk</th><th>Qty</th></tr>
        </thead>
        <tbody>
            <?php if (!$topProducts): ?>
                <tr><td colspan="2">Belum ada data.</td></tr>
            <?php endif; ?>
            <?php foreach ($topProducts as $product): ?>
                <tr><td><?= sanitize($product['name']); ?></td><td><?= (int) $product['qty']; ?></td></tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <h4>Detail Transaksi</h4>
    <table>
        <thead>
            <tr>
                <th>Kode</th>
                <th>Tanggal</th>
                <th>Customer</th>
                <th>Total</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!$orders): ?>
                <tr><td colspan="5">Tidak ada transaksi.</td></tr>
            <?php endif; ?>
            <?php foreach ($orders as $order): ?>
                <tr>
                    <td><?= sanitize($order['code']); ?></td>
                    <td><?= sanitize(date('d M Y', strtotime($order['created_at']))); ?></td>
                    <td><?= sanitize($order['customer_name']); ?></td>
                    <td><?= format_currency($order['total']); ?></td>
                    <td><?= strtoupper(sanitize($order['status'])); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>
