<?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'] ?? '');

$where = [];
$params = [];

if ($startDate !== '' && $endDate !== '') {
    $where[] = 's.sold_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[] = 's.sold_at >= ?';
    $params[] = date('Y-m-d 00:00:00', strtotime($startDate));
} elseif ($endDate !== '') {
    $where[] = 's.sold_at <= ?';
    $params[] = date('Y-m-d 23:59:59', strtotime($endDate));
}

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

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

$itemStmt = $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
    {$whereSql}");
$itemStmt->execute($params);
$totalItems = (int) $itemStmt->fetchColumn();

$topStmt = $pdo->prepare("SELECT p.name, SUM(i.qty) AS qty
    FROM offline_sale_items i
    JOIN offline_sales s ON s.id = i.offline_sale_id
    JOIN products p ON p.id = i.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 s.code, s.sold_at, s.total, u.name AS cashier_name
    FROM offline_sales s
    JOIN users u ON u.id = s.cashier_id
    {$whereSql}
    ORDER BY s.sold_at DESC");
$listStmt->execute($params);
$sales = $listStmt->fetchAll();
?>
<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <title>Laporan Offline</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 Offline</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>Kasir</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!$sales): ?>
                <tr><td colspan="4">Tidak ada transaksi.</td></tr>
            <?php endif; ?>
            <?php foreach ($sales as $sale): ?>
                <tr>
                    <td><?= sanitize($sale['code']); ?></td>
                    <td><?= sanitize(date('d M Y H:i', strtotime($sale['sold_at']))); ?></td>
                    <td><?= sanitize($sale['cashier_name']); ?></td>
                    <td><?= format_currency($sale['total']); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>
