<?php
require_once '../init.php';

$invoice = $_GET['invoice'] ?? null;

if (!$invoice) {
    Helper::redirect('../dashboard.php');
}

// Get transaction details
$trans = $database->selectOne(
    "SELECT * FROM transactions WHERE invoice_number = ? AND user_id = ?",
    [$invoice, $_SESSION['user_id']]
);

if (!$trans) {
    Helper::redirect('../dashboard.php');
}

// Get user details for company info
$user = $database->selectOne(
    "SELECT company_name, address, phone FROM users WHERE id = ?",
    [$_SESSION['user_id']]
);

$items = $database->select(
    "SELECT * FROM transaction_items WHERE transaction_id = ?",
    [$trans['id']]
);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Struk - KasirMurah.biz.id</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: #f8f9fa;
            margin: 0;
            padding: 10px;
        }
        .receipt-container {
            max-width: 320px;
            margin: 20px auto;
            background: white;
            padding: 15px 10px;
            border-radius: 0;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.4;
        }
        .receipt-app-name {
            text-align: center;
            font-size: 10px;
            color: #999;
            margin-bottom: 8px;
            letter-spacing: 1px;
        }
        .receipt-header {
            text-align: center;
            border-bottom: 1px solid #000;
            padding-bottom: 8px;
            margin-bottom: 8px;
        }
        .receipt-header h3 {
            margin: 0;
            font-size: 15px;
            font-weight: bold;
        }
        .receipt-header p {
            margin: 2px 0;
            font-size: 11px;
        }
        .receipt-item {
            display: flex;
            justify-content: space-between;
            padding: 3px 0;
            font-size: 12px;
        }
        .receipt-item-detail {
            font-size: 10px;
            color: #666;
            margin: 1px 0;
        }
        .receipt-total {
            border-top: 1px solid #000;
            border-bottom: 1px solid #000;
            padding: 6px 0;
            margin: 6px 0;
            font-weight: bold;
            font-size: 13px;
        }
        .receipt-footer {
            text-align: center;
            font-size: 10px;
            color: #666;
            margin-top: 8px;
        }
        .divider {
            border-bottom: 1px dashed #000;
            margin: 6px 0;
        }
        @media print {
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            html, body {
                width: 80mm;
                height: auto;
                background: white;
                margin: 0;
                padding: 0;
            }
            body {
                margin: 0 auto;
            }
            .receipt-container {
                max-width: 80mm !important;
                width: 80mm !important;
                margin: 0 !important;
                padding: 8px !important;
                box-shadow: none !important;
                border-radius: 0 !important;
                page-break-after: avoid;
            }
            .text-center {
                text-align: center;
            }
            .mt-4 {
                display: none;
            }
            .btn {
                display: none !important;
            }
        }
    </style>
</head>
<body>
    <div class="receipt-container">
        <!-- Header dengan info toko -->
        <div class="receipt-header">
            <h3><?php echo htmlspecialchars($user['company_name'] ?? 'Toko'); ?></h3>
            <?php if (!empty($user['address'])): ?>
            <p><?php echo htmlspecialchars($user['address']); ?></p>
            <?php endif; ?>
            <?php if (!empty($user['phone'])): ?>
            <p><?php echo htmlspecialchars($user['phone']); ?></p>
            <?php endif; ?>
        </div>

        <!-- Info transaksi -->
        <div style="font-size: 11px; margin-bottom: 6px;">
            <div style="display: flex; justify-content: space-between;">
                <span>Invoice:</span>
                <span><?php echo $trans['invoice_number']; ?></span>
            </div>
            <div style="display: flex; justify-content: space-between;">
                <span>Tanggal:</span>
                <span><?php echo Helper::formatDateTime($trans['created_at']); ?></span>
            </div>
            <div style="display: flex; justify-content: space-between;">
                <span>Kasir:</span>
                <span><?php echo $trans['cashier_name']; ?></span>
            </div>
        </div>

        <div class="divider"></div>
        
        <!-- Item list -->
        <div style="margin-bottom: 6px;">
            <?php foreach ($items as $item): ?>
            <div style="margin-bottom: 4px;">
                <div style="display: flex; justify-content: space-between;">
                    <span style="font-weight: bold;"><?php echo htmlspecialchars(substr($item['product_name'], 0, 25)); ?></span>
                    <span style="font-weight: bold;"><?php echo Helper::formatCurrency($item['subtotal']); ?></span>
                </div>
                <div class="receipt-item-detail">
                    <?php echo $item['quantity']; ?> x <?php echo Helper::formatCurrency($item['unit_price']); ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="divider"></div>
        
        <!-- Summary -->
        <div style="font-size: 11px;">
            <div style="display: flex; justify-content: space-between;">
                <span>Subtotal</span>
                <span><?php echo Helper::formatCurrency($trans['subtotal']); ?></span>
            </div>
            <?php if ($trans['tax_amount'] > 0): ?>
            <div style="display: flex; justify-content: space-between;">
                <span>Tax</span>
                <span><?php echo Helper::formatCurrency($trans['tax_amount']); ?></span>
            </div>
            <?php endif; ?>
            <?php if ($trans['discount_amount'] > 0): ?>
            <div style="display: flex; justify-content: space-between;">
                <span>Diskon</span>
                <span>-<?php echo Helper::formatCurrency($trans['discount_amount']); ?></span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Total -->
        <div class="receipt-total" style="display: flex; justify-content: space-between;">
            <span>TOTAL</span>
            <span><?php echo Helper::formatCurrency($trans['total_amount']); ?></span>
        </div>

        <!-- Payment Method -->
        <div style="font-size: 11px; display: flex; justify-content: space-between; margin-bottom: 8px;">
            <span>Metode</span>
            <span><?php echo ucfirst($trans['payment_method']); ?></span>
        </div>

        <div class="divider"></div>

        <!-- Footer -->
        <div class="receipt-footer">
            <p style="margin: 4px 0;">Terima kasih atas pembelian Anda</p>
            <p style="margin: 2px 0; font-size: 10px;"><?php echo date('d/m/Y H:i:s'); ?></p>
            <p style="margin: 6px 0; font-size: 9px; color: #aaa; letter-spacing: 0.5px;">
                KASIRMURAH.BIZ.ID
            </p>
        </div>
    </div>
    
    <div class="text-center mt-4">
        <button class="btn btn-primary" onclick="window.print()"><i class="fas fa-print me-1"></i>Cetak</button>
        <button class="btn btn-success" onclick="downloadReceipt()"><i class="fas fa-download me-1"></i>Download Struk</button>
        <a href="../pos/index.php" class="btn btn-secondary">Transaksi Baru</a>
        <a href="../dashboard.php" class="btn btn-info">Dashboard</a>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script>
        function downloadReceipt() {
            const element = document.querySelector('.receipt-container');
            const invoiceNumber = '<?php echo $trans['invoice_number']; ?>';

            // Show loading
            const btn = event.target.closest('button');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Mengunduh...';
            btn.disabled = true;

            // Convert to image
            html2canvas(element, {
                backgroundColor: '#ffffff',
                scale: 2,
                logging: false
            }).then(canvas => {
                // Create download link
                const link = document.createElement('a');
                link.href = canvas.toDataURL('image/png');
                link.download = `Struk_${invoiceNumber}_${new Date().getTime()}.png`;

                // Trigger download
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);

                // Reset button
                btn.innerHTML = originalText;
                btn.disabled = false;
            }).catch(error => {
                alert('Gagal mengunduh struk: ' + error.message);
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        }
    </script>
</body>
</html>
