<?php
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

requireLogin();

$id = intval($_GET['id'] ?? 0);

if ($id <= 0) {
    die('ID transaksi tidak valid');
}

// Get transaksi data
$sql = "SELECT t.*, u.nama as kasir 
        FROM transaksi t 
        JOIN users u ON t.id_user = u.id 
        WHERE t.id = ?";
$result = query($sql, [$id], 'i');

if ($result->num_rows === 0) {
    die('Transaksi tidak ditemukan');
}

$transaksi = $result->fetch_assoc();

// Get transaksi details
$sql_detail = "SELECT * FROM transaksi_detail WHERE id_transaksi = ?";
$result_detail = query($sql_detail, [$id], 'i');

$details = [];
while ($row = $result_detail->fetch_assoc()) {
    $details[] = $row;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Struk #<?php echo $id; ?> - Umbul Tirtomarto V2</title>
    <script src="/v2/includes/native-bridge.js"></script>
    <script src="includes/thermal-printer.js"></script>
    <script src="includes/printer-manager.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
            padding: 10px;
        }
        
        .struk {
            max-width: 300px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            margin-bottom: 10px;
            border-bottom: 2px dashed #000;
            padding-bottom: 10px;
        }
        
        .header h1 {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .header p {
            font-size: 11px;
            margin: 2px 0;
        }
        
        .info {
            margin: 10px 0;
            font-size: 11px;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            margin: 3px 0;
        }
        
        .items {
            margin: 10px 0;
            border-top: 2px dashed #000;
            border-bottom: 2px dashed #000;
            padding: 10px 0;
        }
        
        .item {
            margin: 5px 0;
        }
        
        .item-name {
            font-weight: bold;
        }
        
        .item-detail {
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            margin-top: 2px;
        }
        
        .total-section {
            margin: 10px 0;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin: 5px 0;
        }
        
        .grand-total {
            font-size: 14px;
            font-weight: bold;
            border-top: 2px solid #000;
            padding-top: 5px;
            margin-top: 5px;
        }
        
        .footer {
            text-align: center;
            margin-top: 15px;
            margin-bottom: 20px;
            font-size: 11px;
            border-top: 2px dashed #000;
            padding-top: 10px;
            padding-bottom: 15px;
        }
        
        .no-print {
            text-align: center;
            margin: 20px 0;
        }
        
        .btn {
            padding: 10px 20px;
            margin: 5px;
            font-size: 14px;
            cursor: pointer;
            border: none;
            border-radius: 5px;
        }
        
        .btn-primary {
            background-color: #0ea5e9;
            color: white;
        }
        
        .btn-secondary {
            background-color: #6b7280;
            color: white;
        }
        
        .btn-bluetooth {
            background-color: #3b82f6;
            color: white;
        }
        
        .btn-bluetooth:disabled {
            background-color: #9ca3af;
            cursor: not-allowed;
        }
        
        @media print {
            body {
                padding: 0;
                padding-bottom: 30mm;
                margin: 0;
                font-size: 13px;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            .no-print {
                display: none !important;
            }
            
            .struk {
                max-width: 100%;
                margin: 0;
            }
            
            /* Ukuran kertas thermal 80mm dengan margin */
            @page {
                size: 80mm auto;
                margin: 8mm 5mm 20mm 5mm;
            }
            
            /* Font lebih jelas saat print */
            .header h1 {
                font-size: 20px;
                font-weight: 900;
                color: #000 !important;
            }
            
            .header p {
                font-size: 12px;
                font-weight: 600;
            }
            
            .item-name {
                font-weight: 900;
                font-size: 13px;
            }
            
            .grand-total {
                font-size: 16px;
                font-weight: 900;
                border-top: 3px solid #000;
            }
            
            /* Border lebih tebal */
            .header,
            .items,
            .footer {
                border-color: #000 !important;
                border-width: 2px;
            }
        }
    </style>
</head>
<body>
    <div class="struk" id="printArea">
        <!-- Header -->
        <div class="header">
            <h1>UMBUL TIRTOMARTO</h1>
            <p>Sehat, Alami, Berbudaya</p>
            <p>Pengging, Boyolali, Jawa Tengah</p>
        </div>
        
        <!-- Info -->
        <div class="info">
            <div class="info-row">
                <span>No. Struk</span>
                <span>#<?php echo str_pad($transaksi['id'], 6, '0', STR_PAD_LEFT); ?></span>
            </div>
            <div class="info-row">
                <span>Tanggal</span>
                <span><?php echo date('d/m/Y H:i', strtotime($transaksi['created_at'])); ?></span>
            </div>
            <div class="info-row">
                <span>Kasir</span>
                <span><?php echo htmlspecialchars($transaksi['kasir']); ?></span>
            </div>
        </div>
        
        <!-- Items -->
        <div class="items">
            <?php foreach ($details as $item): ?>
            <div class="item">
                <div class="item-name"><?php echo htmlspecialchars($item['nama_layanan']); ?></div>
                <div class="item-detail">
                    <span><?php echo $item['quantity']; ?> x <?php echo formatRupiah($item['harga']); ?></span>
                    <span><?php echo formatRupiah($item['subtotal']); ?></span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Total -->
        <div class="total-section">
            <div class="total-row grand-total">
                <span>TOTAL</span>
                <span><?php echo formatRupiah($transaksi['total']); ?></span>
            </div>
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <p>Terima kasih atas kunjungan Anda</p>
            <p>Selamat menikmati Umbul Tirtomarto</p>
            <p>=================================</p>
            <h3>Wahana Kreasi Nusantara</h1>
            <p style="margin-top: 5px; font-size: 10px;">   </p>
        </div>
    </div>
    
    <!-- Actions -->
    <div class="no-print">
        <button onclick="window.print()" class="btn btn-primary">
            📄 Print Struk
        </button>
        <button onclick="window.location.href='riwayat-struk.php'" class="btn btn-secondary">Kembali</button>
    </div>
    
    <script>
        // Data struk untuk thermal printer
        const strukData = {
            id: <?php echo $id; ?>,
            tanggal: '<?php echo formatTanggal($transaksi['tanggal']); ?>',
            kasir: '<?php echo $transaksi['kasir']; ?>',
            total: <?php echo $transaksi['total']; ?>,
            items: <?php echo json_encode(array_map(function($item) {
                return [
                    'nama' => $item['nama_layanan'],
                    'quantity' => $item['quantity'],
                    'harga' => $item['harga'],
                    'subtotal' => $item['subtotal']
                ];
            }, $details)); ?>
        };
        
        console.log('[Print Struk] Data loaded:', strukData);
        console.log('[Print Struk] Print method detected:', window.printerManager ? printerManager.detectedMethod : 'unknown');
        // Detect native app dan show appropriate buttons
        if (window.isNativeApp) {
            console.log('[Print Struk] Running in native app');
            document.getElementById('nativeButtons').style.display = 'block';
            document.getElementById('webButtons').style.display = 'none';
        }
        
        // Native print function
        async function printNative() {
            try {
                const message = await window.NativePrintManager.print(strukData);
                alert('Print berhasil!');
                console.log('[Print Struk] Print success:', message);
            } catch (error) {
                alert('Print gagal: ' + error.message);
                console.error('[Print Struk] Print error:', error);
            }
        }
        
        // Select printer function
        function selectPrinter() {
            window.NativePrintManager.selectPrinter();
        }
        
        // Get printer status
        if (window.isNativeApp) {
            const status = window.NativePrintManager.getStatus();
            console.log('[Print Struk] Printer status:', status);
        }
    </script>
</body>
</html>
