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

<h2 class="fw-bold mb-4">Laporan Offline</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"><?= (int) $summary['total_tx']; ?></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($summary['total_revenue']); ?></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_offline_print.php?' . http_build_query($_GET)); ?>">Cetak</a>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-body table-responsive">
        <table class="table align-middle">
            <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>
    </div>
</div>

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