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

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

$onlineWhere = ["o.status IN ('paid','packed','shipped','done')"];
$onlineParams = [];
$offlineWhere = [];
$offlineParams = [];

if ($startDate !== '' && $endDate !== '') {
    $onlineWhere[] = 'o.created_at BETWEEN ? AND ?';
    $onlineParams[] = date('Y-m-d 00:00:00', strtotime($startDate));
    $onlineParams[] = date('Y-m-d 23:59:59', strtotime($endDate));

    $offlineWhere[] = 's.sold_at BETWEEN ? AND ?';
    $offlineParams[] = date('Y-m-d 00:00:00', strtotime($startDate));
    $offlineParams[] = date('Y-m-d 23:59:59', strtotime($endDate));
} elseif ($startDate !== '') {
    $onlineWhere[] = 'o.created_at >= ?';
    $onlineParams[] = date('Y-m-d 00:00:00', strtotime($startDate));

    $offlineWhere[] = 's.sold_at >= ?';
    $offlineParams[] = date('Y-m-d 00:00:00', strtotime($startDate));
} elseif ($endDate !== '') {
    $onlineWhere[] = 'o.created_at <= ?';
    $onlineParams[] = date('Y-m-d 23:59:59', strtotime($endDate));

    $offlineWhere[] = 's.sold_at <= ?';
    $offlineParams[] = date('Y-m-d 23:59:59', strtotime($endDate));
}

$onlineWhereSql = 'WHERE ' . implode(' AND ', $onlineWhere);
$offlineWhereSql = $offlineWhere ? 'WHERE ' . implode(' AND ', $offlineWhere) : '';

$onlineSummary = $pdo->prepare("SELECT COUNT(*) AS total_tx, COALESCE(SUM(o.total),0) AS total_revenue
    FROM orders o {$onlineWhereSql}");
$onlineSummary->execute($onlineParams);
$online = $onlineSummary->fetch();

$offlineSummary = $pdo->prepare("SELECT COUNT(*) AS total_tx, COALESCE(SUM(s.total),0) AS total_revenue
    FROM offline_sales s {$offlineWhereSql}");
$offlineSummary->execute($offlineParams);
$offline = $offlineSummary->fetch();

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

$offlineItemsStmt = $pdo->prepare("SELECT COALESCE(SUM(i.qty),0) AS total_items
    FROM offline_sale_items i JOIN offline_sales s ON s.id = i.offline_sale_id {$offlineWhereSql}");
$offlineItemsStmt->execute($offlineParams);
$offlineItems = (int) $offlineItemsStmt->fetchColumn();

$combinedTopSql = "SELECT p.name, SUM(x.qty) AS qty FROM (
    SELECT oi.product_id, oi.qty FROM order_items oi
    JOIN orders o ON o.id = oi.order_id {$onlineWhereSql}
    UNION ALL
    SELECT i.product_id, i.qty FROM offline_sale_items i
    JOIN offline_sales s ON s.id = i.offline_sale_id {$offlineWhereSql}
) x JOIN products p ON p.id = x.product_id
GROUP BY p.id, p.name
ORDER BY qty DESC
LIMIT 5";

$topStmt = $pdo->prepare($combinedTopSql);
$topStmt->execute(array_merge($onlineParams, $offlineParams));
$topProducts = $topStmt->fetchAll();

$totalTx = (int) $online['total_tx'] + (int) $offline['total_tx'];
$totalRevenue = (float) $online['total_revenue'] + (float) $offline['total_revenue'];
$totalItems = $onlineItems + $offlineItems;
?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <title>Laporan Keseluruhan</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 Keseluruhan</h2>
        <div>Periode: <?= sanitize($startDate ?: '-'); ?> s/d <?= sanitize($endDate ?: '-'); ?></div>
    </div>

    <div class="summary">
        <div>Total Transaksi: <?= $totalTx; ?></div>
        <div>Total Omzet: <?= format_currency($totalRevenue); ?></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>
</body>
</html>
