<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Kasir</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="crud.js"></script>
    <script src="report.js"></script> <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f4f4f4;
        }
        .container {
            max-width: 900px;
            margin: auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .controls {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid #ccc;
        }
        .controls label {
            font-weight: bold;
        }
        .controls input,
        .controls select,
        .controls button {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ccc;
            font-size: 14px;
        }
        .controls button {
            background-color: #007bff;
            color: white;
            cursor: pointer;
            padding: 8px 16px;
        }
        .controls button:hover {
            background-color: #0056b3;
        }
        .controls button#backBtn {
            background-color: #6c757d;
        }
        .controls button#backBtn:hover {
            background-color: #5a6268;
        }
        #report-output {
            white-space: pre;
            font-family: 'Courier New', Courier, monospace;
            background-color: #2d2d2d;
            color: #f1f1f1;
            padding: 20px;
            border-radius: 5px;
            overflow-x: auto;
            font-size: 14px;
            line-height: 1.5;
            min-height: 200px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>Laporan Kasir Harian</h1>

        <div class="controls">
            <div>
                <label for="startDate">Dari Tanggal:</label>
                <input type="date" id="startDate">
            </div>
            <div>
                <label for="endDate">Sampai Tanggal:</label>
                <input type="date" id="endDate">
            </div>
            <div>
                <label for="kasir">Kasir:</label>
                <select id="kasir">
                    <option value="All">All</option>
                </select>
            </div>
            <button id="generateBtn">Buat Laporan</button>
            <button id="printBtn">Cetak</button>
            <button id="backBtn" onclick="window.parent.closeReportModal()">Kembali ke POS</button>
        </div>

        <pre id="report-output">Laporan akan ditampilkan di sini...</pre>
    </div>

 <script>
        // Set brand & cab secara dinamis dari localStorage
        let xbrand = '';
        let xcab = '';

        try {
            // 1. Ambil data 'xpos' dari localStorage yang disimpan oleh index.html
            const xposData = localStorage.getItem('xpos');

            // 2. Cek apakah data ada
            if (xposData) {
                // 3. Ubah string JSON menjadi objek
                const xpos = JSON.parse(xposData);
                
                // 4. Set nilai xbrand dan xcab
                xbrand = xpos.brand || '';
                xcab = xpos.cab || '';
            }

            // 5. Jika salah satu kosong, beri tahu di console (untuk debugging)
            if (!xbrand || !xcab) {
                console.error("Gagal memuat brand/cab dari localStorage. Pastikan sudah login di halaman POS utama.");
                // Anda bisa menambahkan nilai default di sini jika perlu
                // xbrand = '001'; 
                // xcab = '002';
            }
        } catch (error) {
            console.error("Terjadi error saat membaca data dari localStorage:", error);
        };

        // Fungsi untuk mengirim data ke WebSocket Server (cetak.js)
        function sendReportToPrinter(printerName, port, textData) {
            return new Promise((resolve, reject) => {
                const ws = new WebSocket('ws://localhost:8080');

                // Fungsi helper untuk mengubah teks menjadi HEX
                function textToHex(str) {
                    let hex = '';
                    for (let i = 0; i < str.length; i++) {
                        hex += str.charCodeAt(i).toString(16).padStart(2, '0');
                    }
                    return hex;
                }

                ws.onopen = () => {
                    console.log("Terhubung ke Print Server...");
                    const payload = {
                        action: 'cetak',
                        nama_printer: printerName,
                        port: port,
                        printData: textToHex(textData)
                    };
                    ws.send(JSON.stringify(payload));
                };

                ws.onmessage = (event) => {
                    const response = JSON.parse(event.data);
                    if (response.type === 'success') {
                        ws.close();
                        resolve(response.message);
                    } else if (response.type === 'error') {
                        ws.close();
                        reject(response.message);
                    }
                };

                ws.onerror = (error) => {
                    reject('Tidak dapat terhubung ke Print Server. Pastikan aplikasi cetak.js sudah berjalan.');
                };
            });
        }


        $(document).ready(function () {
            // Set tanggal default
            const defaultDate = new Date().toISOString().slice(0, 10);
            $('#startDate').val(defaultDate);
            $('#endDate').val(defaultDate);

            // Tombol Kembali
            $('#backBtn').on('click', function() {
                window.location.href = 'index.html';
            });
            
            // Tombol Generate Laporan
            $('#generateBtn').on('click', async function () {
                const startDate = $('#startDate').val();
                const endDate = $('#endDate').val();
                const kasir = $('#kasir').val();

                try {
                    $('#report-output').text('Sedang mengambil data...');

                    // Ambil data jual
                    const jualQuery = `SELECT * FROM jual WHERE brand='${xbrand}' AND cab='${xcab}' AND tanggal >= '${startDate}' AND tanggal <= '${endDate}' AND batal != '1'`;
                    
                    const jualData = JSON.parse(await ambil_select('jual', jualQuery));
                    

                    if (jualData.length === 0) {
                        $('#report-output').text("❌ Tidak ada transaksi pada tanggal tersebut.");
                        return;
                    }
                    const nomorList = jualData.map(j => `'${j.nomor}'`).join(',');
                    
                    // Ambil data pesani
                    const pesaniQuery = `SELECT * FROM pesani WHERE brand='${xbrand}' AND cab='${xcab}' AND tglo >= '${startDate} 00:00:00' AND tglo <= '${endDate} 23:59:59' AND nomor IN (${nomorList})`;
                    const pesaniData = JSON.parse(await ambil_select('pesani', pesaniQuery));
                    
                    // Ambil data pos settings
                    const posQuery = `SELECT * FROM pos WHERE brand='${xbrand}' AND cab='${xcab}'`;
                    const posData = JSON.parse(await ambil_select('pos', posQuery));
                    const posSettings = {};
                    posData.forEach(p => { posSettings[p.kode] = p.isi; });

                    // Ambil data users
                    const userQuery = `SELECT * FROM users WHERE brand='${xbrand}' AND cab='${xcab}'`;
                    const userData = JSON.parse(await ambil_select('users', userQuery));
                    
                    // Ambil data cart untuk outstanding
                    const cartQuery = `SELECT * FROM cart WHERE brand='${xbrand}' AND cab='${xcab}'`;
                    const cartData = JSON.parse(await ambil_select('cart', cartQuery));

                    // Generate laporan
                    const reportText = generateCashierReport(jualData, pesaniData, posSettings, userData, {
                        startDate,
                        endDate,
                        kasir
                    }, cartData);

                    $('#report-output').text(reportText);

                } catch (err) {
                    const errorMsg = `❌ Gagal generate laporan:\n${err.message}`;
                    $('#report-output').text(errorMsg);
                    console.error(err);
                }
            });

            // Tombol Cetak (Logika Baru)
            $('#printBtn').on('click', async function () {
                const content = $('#report-output').text();
                if (!content || content.includes('Tidak ada') || content.includes('Error') || content.includes('ditampilkan')) {
                    alert('Tidak ada laporan untuk dicetak. Silakan buat laporan terlebih dahulu.');
                    return;
                }

                try {
                    // 1. Ambil kode printer struk dari tabel 'pos'
                    const posJson = await ambil_select('pos', `SELECT * FROM pos WHERE kode='receipt_printer_code'`);
                    const receiptPrinterCode = JSON.parse(posJson)[0].isi;
                    
                    if (!receiptPrinterCode) {
                        throw new Error("Printer struk belum diatur di tabel 'pos'.");
                    }

                    // 2. Ambil detail printer dari tabel 'kitchen'
                    const kitchenJson = await ambil_select('kitchen', `SELECT * FROM kitchen WHERE kode='${receiptPrinterCode}'`);
                    const printerInfo = JSON.parse(kitchenJson)[0];

                    if (!printerInfo) {
                        throw new Error(`Printer dengan kode '${receiptPrinterCode}' tidak ditemukan di tabel kitchen.`);
                    }

                    const printerName = printerInfo.windows; // cth: "Epson TM-T82"
                    const port = `LPT${printerInfo.lpt}:`;    // cth: "LPT1:"

                    alert(`Mengirim laporan ke printer: ${printerName} (${port})...`);

                    // 3. Kirim ke WebSocket Server
                    const result = await sendReportToPrinter(printerName, port, content);
                    alert("Berhasil mengirim laporan ke printer!");
                    console.log(result);

                } catch (error) {
                    alert(`Gagal mencetak laporan: ${error.message}`);
                    console.error(error);
                }
            });
        });
    </script>
</body>
</html>