<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner();
require_once __DIR__ . '/../includes/header_admin.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;
?>

<h2 class="fw-bold mb-4">Laporan Keseluruhan</h2>

<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form class="row g-3" method="get">
            <div class="col-md-4">
                <label>Tanggal Mulai</label>
                <input class="form-control" type="date" name="start_date" value="<?= sanitize($startDate); ?>">
            </div>
            <div class="col-md-4">
                <label>Tanggal Akhir</label>
                <input class="form-control" type="date" name="end_date" value="<?= sanitize($endDate); ?>">
            </div>
            <div class="col-md-4 d-flex align-items-end">
                <button class="btn w-100" type="submit">Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="card shadow-sm">
            <div class="card-body">
                <div class="text-muted">Total Transaksi</div>
                <h4 class="fw-bold mb-0"><?= $totalTx; ?></h4>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card shadow-sm">
            <div class="card-body">
                <div class="text-muted">Total Omzet</div>
                <h4 class="fw-bold mb-0"><?= format_currency($totalRevenue); ?></h4>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card shadow-sm">
            <div class="card-body">
                <div class="text-muted">Item Terjual</div>
                <h4 class="fw-bold mb-0"><?= $totalItems; ?></h4>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm mb-4">
    <div class="card-body">
        <h5 class="fw-bold">Produk Terlaris (Top 5)</h5>
        <div class="table-responsive">
            <table class="table align-middle">
                <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>
        </div>
        <a class="btn btn-sm" href="<?= base_url('admin/report_all_print.php?' . http_build_query($_GET)); ?>">Cetak</a>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_admin.php'; ?>
