<?php
require_once '../../includes/auth_middleware.php';
require_once '../../config/database.php';
require_once '../../includes/header.php';
checkRole(['admin']);

// Default filter
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-d');

// 1. Ambil data Transaksi (Termasuk Kolom Diskon)
$stmt = $pdo->prepare("SELECT t.*, u.username FROM transactions t JOIN users u ON t.user_id = u.id WHERE DATE(t.transaction_date) BETWEEN ? AND ? ORDER BY t.transaction_date DESC");
$stmt->execute([$start_date, $end_date]);
$all_logs = $stmt->fetchAll();

$total_omzet_kotor = 0;
$total_diskon = 0;
$total_profit = 0;

foreach ($all_logs as $row) {
    $total_omzet_kotor += $row['total_omzet'];
    $total_diskon += $row['discount_amount'];
    $total_profit += $row['total_profit'];
}

// 2. Total Penggunaan Bahan Baku
$ing_stmt = $pdo->prepare("
    SELECT i.name, i.unit, SUM(td.qty * r.usage_qty) as total_used
    FROM transactions t
    JOIN transaction_details td ON t.id = td.transaction_id
    JOIN recipes r ON td.product_id = r.product_id
    JOIN ingredients i ON r.ingredient_id = i.id
    WHERE DATE(t.transaction_date) BETWEEN ? AND ?
    GROUP BY i.id
    ORDER BY total_used DESC
");
$ing_stmt->execute([$start_date, $end_date]);
$usage_logs = $ing_stmt->fetchAll();

// 3. Rincian Bahan Baku per Menu
$detail_stmt = $pdo->prepare("
    SELECT i.name AS ingredient_name, i.unit, p.product_name, SUM(td.qty) as product_sold, SUM(td.qty * r.usage_qty) as detail_used
    FROM transactions t
    JOIN transaction_details td ON t.id = td.transaction_id
    JOIN recipes r ON td.product_id = r.product_id
    JOIN ingredients i ON r.ingredient_id = i.id
    JOIN products p ON td.product_id = p.id
    WHERE DATE(t.transaction_date) BETWEEN ? AND ?
    GROUP BY i.id, p.id
    ORDER BY i.name ASC, detail_used DESC
");
$detail_stmt->execute([$start_date, $end_date]);
$raw_details = $detail_stmt->fetchAll();

$breakdown = [];
foreach ($raw_details as $row) {
    $breakdown[$row['ingredient_name']]['unit'] = $row['unit'];
    $breakdown[$row['ingredient_name']]['menus'][] = [
        'product' => $row['product_name'],
        'sold' => $row['product_sold'],
        'used' => $row['detail_used']
    ];
}

// 4. Log Historis Detail (Audit Trail)
$log_stmt = $pdo->prepare("
    SELECT t.transaction_date, t.discount_amount, u.username, p.product_name, td.qty AS product_qty, i.name AS ingredient_name, (td.qty * r.usage_qty) AS amount_used, i.unit
    FROM transactions t
    JOIN transaction_details td ON t.id = td.transaction_id
    JOIN recipes r ON td.product_id = r.product_id
    JOIN ingredients i ON r.ingredient_id = i.id
    JOIN products p ON td.product_id = p.id
    JOIN users u ON t.user_id = u.id
    WHERE DATE(t.transaction_date) BETWEEN ? AND ?
    ORDER BY t.transaction_date DESC
");
$log_stmt->execute([$start_date, $end_date]);
$chrono_logs = $log_stmt->fetchAll();
?>

<div class="container" style="max-width: 1200px;">
    <header style="margin-bottom: 2rem; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 1rem;">
        <div>
            <h2 style="margin:0;">LAPORAN LENGKAP</h2>
            <p class="report-period" style="color: #4b5563; margin:5px 0 0 0; font-weight: bold; font-size: 1.1rem;">
                Periode: <?= date('d M Y', strtotime($start_date)) ?> s/d <?= date('d M Y', strtotime($end_date)) ?>
            </p>
        </div>
        
        <form method="GET" class="no-print" style="display: flex; gap: 10px; align-items: center; background: white; padding: 10px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
            <div style="display: flex; flex-direction: column;">
                <label style="font-size: 0.75rem; color: #666; font-weight: bold;">Dari Tanggal</label>
                <input type="date" name="start_date" value="<?= $start_date ?>" style="padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
            </div>
            <span style="font-weight: bold; color: #999; margin-top: 15px;">-</span>
            <div style="display: flex; flex-direction: column;">
                <label style="font-size: 0.75rem; color: #666; font-weight: bold;">Sampai Tanggal</label>
                <input type="date" name="end_date" value="<?= $end_date ?>" style="padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
            </div>
            <button type="submit" class="btn-primary" style="margin-top: 15px; padding: 10px 15px; border-radius: 6px;">Filter</button>
            <button type="button" onclick="window.print()" style="margin-top: 15px; padding: 10px 15px; border-radius: 6px; background: #374151; color: white; border: none; cursor: pointer; font-weight: bold;">Print PDF</button>
        </form>
    </header>

    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
        <div class="card" style="border-left: 5px solid #3b82f6;">
            <label style="color: #6b7280; font-weight: bold; font-size: 0.8rem;">TOTAL OMZET (KOTOR)</label>
            <div style="font-size: 1.5rem; font-weight: 900; color: #1f2937;">Rp <?= number_format($total_omzet_kotor, 0, ',', '.') ?></div>
        </div>
        <div class="card" style="border-left: 5px solid #fbbf24;">
            <label style="color: #6b7280; font-weight: bold; font-size: 0.8rem;">TOTAL DISKON KELUAR</label>
            <div style="font-size: 1.5rem; font-weight: 900; color: #b45309;">- Rp <?= number_format($total_diskon, 0, ',', '.') ?></div>
        </div>
        <div class="card" style="border-left: 5px solid #10B981;">
            <label style="color: #6b7280; font-weight: bold; font-size: 0.8rem;">TOTAL PROFIT BERSIH</label>
            <div style="font-size: 1.5rem; font-weight: 900; color: #10B981;">Rp <?= number_format($total_profit, 0, ',', '.') ?></div>
        </div>
    </div>

    <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 1.5rem; align-items: start; margin-bottom: 2rem;">
        <div class="card" style="overflow-x: auto; height: 100%;">
            <label style="font-weight: bold; color: var(--accent); margin-bottom: 10px; display: block;">RIWAYAT PENJUALAN</label>
            <table style="width: 100%; border-collapse: collapse; min-width: 500px;">
                <thead>
                    <tr style="text-align: left; border-bottom: 2px solid #eee;">
                        <th style="padding: 10px; color: #6b7280; font-size: 0.8rem;">WAKTU</th>
                        <th style="padding: 10px; color: #6b7280; font-size: 0.8rem; text-align: right;">OMZET</th>
                        <th style="padding: 10px; color: #6b7280; font-size: 0.8rem; text-align: right;">DISKON</th>
                        <th style="padding: 10px; color: #6b7280; font-size: 0.8rem; text-align: right;">PROFIT</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($all_logs as $row): ?>
                    <tr style="border-bottom: 1px solid #f3f4f6;">
                        <td style="padding: 10px;">
                            <div style="font-weight: bold; font-size: 0.9rem;"><?= date('d/m/y H:i', strtotime($row['transaction_date'])) ?></div>
                            <div style="font-size: 0.7rem; color: #9ca3af;">Kasir: <?= htmlspecialchars($row['username']) ?></div>
                        </td>
                        <td style="padding: 10px; text-align: right; font-weight: 600;">Rp <?= number_format($row['total_omzet'], 0, ',', '.') ?></td>
                        <td style="padding: 10px; text-align: right; color: #dc2626; font-size: 0.85rem;">
                            <?= $row['discount_amount'] > 0 ? '-Rp ' . number_format($row['discount_amount'], 0, ',', '.') : '-' ?>
                        </td>
                        <td style="padding: 10px; text-align: right; font-weight: 900; color: #10B981;">Rp <?= number_format($row['total_profit'], 0, ',', '.') ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="card" style="background: #fffbeb; border: 1px solid #fde68a; height: 100%;">
            <label style="font-weight: bold; color: #b45309; margin-bottom: 10px; display: block;">TOTAL BAHAN TERPAKAI</label>
            <table style="width: 100%; border-collapse: collapse;">
                <tbody>
                    <?php foreach($usage_logs as $use): ?>
                    <tr style="border-bottom: 1px solid #fde68a;">
                        <td style="padding: 10px 0; font-weight: 600; font-size: 0.9rem;"><?= htmlspecialchars($use['name']) ?></td>
                        <td style="padding: 10px 0; text-align: right; font-weight: 900; color: #dc2626;">
                            <?= number_format($use['total_used'], 2, ',', '.') ?> <small><?= $use['unit'] ?></small>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card" style="border-top: 5px solid #3b82f6; margin-bottom: 2rem;">
        <label style="font-weight: bold; color: #1d4ed8; font-size: 1rem; margin-bottom: 10px; display: block;">PENGGUNAAN BAHAN PER MENU</label>
        <table style="width: 100%; border-collapse: collapse;">
            <?php foreach($breakdown as $ing_name => $data): ?>
                <tr style="background: #eff6ff;"><td colspan="3" style="padding: 10px; font-weight: 900; color: #1e3a8a; border-bottom: 1px solid #bfdbfe;">📦 <?= htmlspecialchars($ing_name) ?></td></tr>
                <?php foreach($data['menus'] as $menu): ?>
                <tr style="border-bottom: 1px solid #f3f4f6;">
                    <td style="padding: 8px 10px 8px 30px; font-size: 0.85rem; color: #4b5563;">↳ Untuk: <?= htmlspecialchars($menu['product']) ?> (<?= $menu['sold'] ?>x)</td>
                    <td style="padding: 8px 10px; text-align: right; font-weight: bold; color: #dc2626;"><?= number_format($menu['used'], 2, ',', '.') ?> <?= $data['unit'] ?></td>
                </tr>
                <?php endforeach; ?>
            <?php endforeach; ?>
        </table>
    </div>

    <div class="card" style="border-top: 5px solid #8b5cf6;">
        <label style="font-weight: bold; color: #6d28d9; font-size: 1rem; margin-bottom: 10px; display: block;">AUDIT TRAIL (JEJAK DETAIL)</label>
        <table style="width: 100%; border-collapse: collapse;">
            <thead style="background: #f9fafb;">
                <tr style="text-align: left; border-bottom: 2px solid #ddd;">
                    <th style="padding: 10px; font-size: 0.75rem;">WAKTU</th>
                    <th style="padding: 10px; font-size: 0.75rem;">BAHAN BAKU</th>
                    <th style="padding: 10px; font-size: 0.75rem; text-align: center;">JUMLAH</th>
                    <th style="padding: 10px; font-size: 0.75rem;">MENU</th>
                    <th style="padding: 10px; font-size: 0.75rem;">KET. DISKON</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($chrono_logs as $log): ?>
                <tr style="border-bottom: 1px solid #eee;">
                    <td style="padding: 10px; font-size: 0.8rem;"><?= date('H:i', strtotime($log['transaction_date'])) ?> <small><?= date('d/m', strtotime($log['transaction_date'])) ?></small></td>
                    <td style="padding: 10px; font-weight: 600; font-size: 0.85rem;"><?= htmlspecialchars($log['ingredient_name']) ?></td>
                    <td style="padding: 10px; text-align: center;"><span style="color: #dc2626; font-weight: bold;">-<?= number_format($log['amount_used'], 2, ',', '.') ?></span></td>
                    <td style="padding: 10px; font-size: 0.85rem; color: #4b5563;"><?= htmlspecialchars($log['product_name']) ?> (<?= $log['product_qty'] ?>)</td>
                    <td style="padding: 10px; font-size: 0.75rem;">
                        <?= $log['discount_amount'] > 0 ? '<span style="color:#b45309; font-weight:bold;">Disc: Rp'.number_format($log['discount_amount'],0).'</span>' : '-' ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<style>
    @media print {
        .no-print, .floating-menu-btn, .menu-overlay, .side-menu { display: none !important; }
        .report-period { display: block !important; margin-bottom: 20px !important; }
        @page { margin: 1cm; }
        body { background: white !important; }
        .card { box-shadow: none !important; border: 1px solid #eee !important; break-inside: avoid; margin-bottom: 10px !important; }
    }
</style>