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

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

$saleStmt = $pdo->prepare('SELECT s.*, u.name AS cashier_name FROM offline_sales s JOIN users u ON u.id = s.cashier_id WHERE s.id = ? LIMIT 1');
$saleStmt->execute([$id]);
$sale = $saleStmt->fetch();

if (!$sale) {
    echo '<div class="alert error">Transaksi tidak ditemukan.</div>';
    require_once __DIR__ . '/../includes/footer_admin.php';
    exit;
}

$itemStmt = $pdo->prepare('SELECT i.qty, i.price, i.subtotal, p.name FROM offline_sale_items i JOIN products p ON p.id = i.product_id WHERE i.offline_sale_id = ?');
$itemStmt->execute([$id]);
$items = $itemStmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h2 class="fw-bold">Nota Penjualan Offline</h2>
    <button class="btn btn-sm" onclick="window.print()">Cetak</button>
</div>

<div class="card shadow-sm mb-4">
    <div class="card-body">
        <div class="row">
            <div class="col-md-6">
                <h5 class="fw-bold">Al-Qanuni Store</h5>
                <p>Jl. Contoh No. 123, Kota Makkah Baru</p>
            </div>
            <div class="col-md-6 text-md-end">
                <p>Kode: <strong><?= sanitize($sale['code']); ?></strong></p>
                <p>Tanggal: <?= sanitize(date('d M Y H:i', strtotime($sale['sold_at']))); ?></p>
                <p>Kasir: <?= sanitize($sale['cashier_name']); ?></p>
            </div>
        </div>
        <hr>
        <p>Pembeli: <?= sanitize($sale['customer_name'] ?? '-'); ?></p>
    </div>
</div>

<div class="table-responsive">
    <table class="table align-middle">
        <thead>
            <tr>
                <th>Produk</th>
                <th>Harga</th>
                <th>Qty</th>
                <th>Subtotal</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $item): ?>
                <tr>
                    <td><?= sanitize($item['name']); ?></td>
                    <td><?= format_currency($item['price']); ?></td>
                    <td><?= (int) $item['qty']; ?></td>
                    <td><?= format_currency($item['subtotal']); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr>
                <th colspan="3" class="text-end">Total</th>
                <th><?= format_currency($sale['total']); ?></th>
            </tr>
        </tfoot>
    </table>
</div>

<div class="d-flex justify-content-end mt-4">
    <div style="text-align: center;">
        <p>Tanda tangan</p>
        <div style="height: 60px;"></div>
        <strong><?= sanitize($sale['cashier_name']); ?></strong>
    </div>
</div>

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