<?php
/**
 * Print Invoice - Unified for POS and Online Orders
 * Online: 100mm x 80mm (Landscape)
 * POS: 70mm (Portrait)
 */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
date_default_timezone_set('Asia/Vientiane');

// Check login
if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo "Unauthorized";
    exit;
}

require_once '../../include/con_data.php';

$shop_id = $_SESSION['shop_id'] ?? null;
if (!$shop_id) {
    echo "Shop not found";
    exit;
}

// Get order IDs
$order_ids = [];
if (isset($_GET['order_ids'])) {
    $order_ids = explode(',', $_GET['order_ids']);
} elseif (isset($_GET['id'])) {
    $order_ids = [$_GET['id']];
}

if (empty($order_ids)) {
    echo "No order ID specified";
    exit;
}

// Sanitize order IDs
$sanitized_order_ids = [];
foreach ($order_ids as $id) {
    $sanitized_order_ids[] = $conn->real_escape_string(trim($id));
}

// Get shop info
$shop_stmt = $conn->prepare("SELECT * FROM shops WHERE shop_id = ?");
$shop_stmt->bind_param("i", $shop_id);
$shop_stmt->execute();
$shop_result = $shop_stmt->get_result();
$shop = $shop_result->fetch_assoc();
$shop_stmt->close();

$shop_name = $shop['shop_name'] ?? 'Muanjai Shop';
$shop_phone = $shop['phone'] ?? '-';

?>
<!DOCTYPE html>
<html lang="lo">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print Invoice - MUANJAI</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@300;400;500;600;700;800;900&display=swap"
        rel="stylesheet">
    <style>
        /* ===== Reset & Base ===== */
        * {
            font-family: 'Noto Sans Lao', 'Arial', sans-serif !important;
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: #e8e8e8;
        }

        /* ===== Print Button ===== */
        .print-actions {
            text-align: center;
            padding: 20px;
            background: #fff;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .print-actions button {
            padding: 12px 35px;
            background: #222;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: background 0.2s;
        }

        .print-actions button:hover {
            background: #444;
        }

        /* ============================================
           ONLINE RECEIPT - Landscape 100mm x 80mm
           ============================================ */
        .receipt {
            width: 100mm;
            height: 80mm;
            margin: 15px auto;
            background: #fff;
            border: 2.5px solid #000;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        /* --- Header --- */
        .receipt-header {
            display: flex;
            align-items: stretch;
            border-bottom: 2.5px solid #000;
        }

        .header-left {
            display: flex;
            align-items: center;
            flex: 1;
        }

        .header-logo {
            width: 16mm;
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .header-logo img {
            width: 9.401mm;
            height: 8.696mm;
        }

        .header-brand {
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .header-brand .slogan {
            font-size: 9pt;
            font-weight: 600;
            line-height: 1.4;
            color: #000;
        }

        .header-right {
            flex: 1;
            border-left: 2.5px solid #000;
            display: flex;
            padding: 3px 3px 3px 2px;
            flex-direction: column;
            justify-content: center;
        }

        .social-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
        }

        .social-item {
            display: flex;
            align-items: center;
            gap: 1.5mm;
            font-size: 8pt;
            font-weight: 700;
            color: #000;
            white-space: nowrap;
        }

        .social-item img {
            width: 3.5mm;
            height: 3.5mm;
            object-fit: contain;
        }

        /* --- Info Section (NO grid borders, open layout) --- */
        .receipt-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 1mm 0;
        }

        .info-row {
            display: grid;
            grid-template-columns: 1.6fr 1fr;
            padding-left: 8px;
            padding-right: 8px;
            gap: 2mm;
        }

        .info-cell {
            display: block;
        }

        .info-cell.full {
            grid-column: 1 / -1;
        }

        .info-label {
            font-size: 10pt;
            font-weight: 800;
            color: #000;
            white-space: nowrap;
        }

        .info-value {
            font-size: 10pt;
            font-weight: 500;
            color: #000;
        }

        .info-value.bold {
            font-weight: 900;
            font-size: 13pt;
        }

        /* First row (bill# + date) separated from header */
        .info-row.first-row {
            border-bottom: 1.5px solid #000;
            padding-top: 1.5mm;
            padding-bottom: 1.5mm;
        }

        .info-row.last-row {
            padding-bottom: 1.5mm;
        }

        /* --- Footer Section --- */
        .receipt-footer {
            display: flex;
            border-top: 2.5px solid #000;
            min-height: 20mm;
        }

        .footer-left {
            flex: 1;
            padding: 2mm;
            display: flex;
            flex-direction: column;
            justify-content: center;
            gap: 2mm;
        }

        .warning-item {
            display: flex;
            align-items: center;
            gap: 2.5mm;
        }

        .warning-icon {
            flex-shrink: 0;
        }

        .warning-icon img {
            width: 8mm;
            height: 8mm;
            object-fit: contain;
        }

        .warning-text {
            font-size: 12pt;
            font-weight: 700;
            line-height: 1.3;
            color: #000;
        }

        .warning-text .fragile-en {
            font-weight: 900;
            font-size: 9pt;
            letter-spacing: 1px;
        }

        .footer-right {
            width: 32mm;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2mm;
        }

        .qr-placeholder {
            width: 28mm;
            height: 28mm;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 8pt;
            color: #999;
            font-weight: 600;
            text-align: center;
            line-height: 1.4;
        }

        .qr-placeholder img {
            width: 90px;
            height: 90px;
            object-fit: contain;
        }

        /* ============================================
           POS RECEIPT - Portrait 70mm
           ============================================ */
        .receipt-pos {
            width: 70mm;
            margin: 15px auto;
            padding: 3mm;
            background: #fff;
            border: 2px solid #000;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        }

        .pos-header {
            text-align: center;
            border-bottom: 2px solid #000;
            padding-bottom: 2mm;
            margin-bottom: 2mm;
        }

        .pos-header img {
            width: 10mm;
            margin-bottom: 1mm;
        }

        .pos-header .pos-shop-name {
            font-size: 11pt;
            font-weight: 800;
        }

        .pos-header .pos-phone {
            font-size: 7.5pt;
            color: #333;
        }

        .pos-meta {
            display: flex;
            justify-content: space-between;
            font-size: 7pt;
            border-bottom: 1px solid #000;
            padding-bottom: 2mm;
            margin-bottom: 2mm;
        }

        .pos-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 7.5pt;
            margin-bottom: 2mm;
        }

        .pos-table th {
            text-align: left;
            border-bottom: 1px solid #000;
            padding: 1mm 0;
            font-weight: 700;
            font-size: 7pt;
        }

        .pos-table td {
            padding: 1mm 0;
            border-bottom: 0.5px solid #ddd;
        }

        .pos-totals {
            border-top: 2px solid #000;
            padding-top: 2mm;
            margin-top: 1mm;
        }

        .pos-total-row {
            display: flex;
            justify-content: space-between;
            font-size: 8pt;
            padding: 0.5mm 0;
        }

        .pos-total-row.grand {
            font-size: 11pt;
            font-weight: 800;
            border-top: 1px solid #000;
            padding-top: 1.5mm;
            margin-top: 1mm;
        }

        .pos-cash-info {
            border-top: 1px dashed #000;
            margin-top: 2mm;
            padding-top: 2mm;
            font-size: 7pt;
        }

        .pos-cash-row {
            display: flex;
            justify-content: space-between;
            padding: 0.3mm 0;
        }

        .pos-footer {
            text-align: center;
            margin-top: 3mm;
            padding-top: 2mm;
            border-top: 1px solid #000;
            font-size: 7.5pt;
            font-weight: 500;
        }

        /* ===== Print Styles ===== */
        @media print {
            .print-actions {
                display: none !important;
            }

            body {
                background: #fff;
                margin: 0;
                padding: 0;
            }

            .receipt,
            .receipt-pos {
                box-shadow: none;
                margin: 0;
                page-break-after: always;
            }

            @page {
                margin: 0;
            }
        }
    </style>
</head>

<body>
    <div class="print-actions">
        <button onclick="window.print()">🖨️ ພິມໃບບິນ / Print</button>
    </div>

    <?php
    foreach ($sanitized_order_ids as $order_id_param) {
        $where_clause = "o.id = ?";
        if (strpos($order_id_param, 'OR_') === 0) {
            $where_clause = "o.OR_id = ?";
        }

        $sql = "SELECT o.*, 
                       c.name as customer_name, c.phone as customer_phone,
                       sc.company_name, sb.branch_name,
                       curr.currencys_symbol
                FROM orders o
                LEFT JOIN customers c ON o.customer_id = c.CU_id
                LEFT JOIN shipping_companies sc ON o.shipping_company_id = sc.SC_id
                LEFT JOIN shipping_branches sb ON o.shipping_branch_id = sb.SB_id
                LEFT JOIN currencys curr ON o.currencys_id = curr.currencys_id AND curr.shop_id = o.shop_id
                WHERE $where_clause AND o.shop_id = ?";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $order_id_param, $shop_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0)
            continue;

        $order = $result->fetch_assoc();
        $order_type = $order['order_type'];
        $currency_symbol = $order['currencys_symbol'] ?? '₭';

        // Get Items
        $items_sql = "SELECT * FROM order_items WHERE order_id = ?";
        $istmt = $conn->prepare($items_sql);
        $istmt->bind_param("i", $order['id']);
        $istmt->execute();
        $iresult = $istmt->get_result();
        $items = [];
        while ($row = $iresult->fetch_assoc())
            $items[] = $row;
        $istmt->close();

        // Extract COD info
        $cod_info = '-';
        if (!empty($order['notes'])) {
            if (strpos($order['notes'], 'ປາຍທາງ') !== false) {
                $cod_info = 'ປາຍທາງ';
            } elseif (strpos($order['notes'], 'ຕົ້ນທາງ') !== false || strpos($order['notes'], 'ຫັກ COD') !== false) {
                $cod_info = 'ຕົ້ນທາງ';
            }
        }

        // Generate Secure QR Code URL - แก้ไขให้ force domain ไม่มี www.
        $protocol = 'https';  // force https เสมอ
        $fixed_domain = 'epgroups.com';  // force ไม่มี www. เพื่อให้ session ไม่หาย
        $base_dir = rtrim(dirname($_SERVER['REQUEST_URI']), '/');
        $view_order_url = $protocol . "://" . $fixed_domain . $base_dir . "/view_order.php?id=" . $order['OR_id'];

        // หรือถ้าต้องการใช้ relative path (แนะนำมากกว่า เพราะไม่ขึ้นกับ domain เลย)
        // $view_order_url = "/muanjai/system/pos/view_order.php?id=" . $order['OR_id'];
    
        $qr_api_url = "https://api.qrserver.com/v1/create-qr-code/?size=110x110&margin=0&data=" . urlencode($view_order_url);

        if ($order_type === 'online') {
            ?>
            <!-- ========== ONLINE RECEIPT ========== -->
            <div class="receipt">
                <!-- HEADER -->
                <div class="receipt-header">
                    <div class="header-left">
                        <div class="header-logo">
                            <img src="../../img/logo_icon/logo.png" alt="MUANJAI">
                        </div>
                        <div class="header-brand">
                            <div class="slogan">ເພາະຄວາມສຸກຂອງທ່ານ</div>
                            <div class="slogan">ຄືຄວາມພາກພູມໃຈຂອງເຮົາ</div>
                        </div>
                    </div>
                    <div class="header-right">
                        <div class="social-grid">
                            <div class="social-item">
                                <img src="../../img/logo_icon/facebook.png" alt="fb"> MUANJAI
                            </div>
                            <div class="social-item">
                                <img src="../../img/logo_icon/whatapp.png" alt="wa"> 020 <?= htmlspecialchars($shop_phone) ?>
                            </div>
                            <div class="social-item">
                                <img src="../../img/logo_icon/tiktok.png" alt="tt"> MUANJAI
                            </div>
                            <div class="social-item">
                                <img src="../../img/logo_icon/ins.png" alt="ig"> Muanjai_Beauty
                            </div>
                        </div>
                    </div>
                </div>

                <!-- INFO SECTION -->
                <div class="receipt-info">
                    <div class="info-row first-row">
                        <div class="info-cell" style="text-align: left;">
                            <span class="info-label">ເລກບິນ:</span>
                            <span class="info-value"><?= htmlspecialchars($order['OR_id']) ?></span>
                        </div>
                        <div class="info-cell" style="text-align: right;">
                            <span class="info-label">ວ/ດ/ປ:</span>
                            <span class="info-value"><?= date('d/m/Y', strtotime($order['created_at'])) ?></span>
                        </div>
                    </div>

                    <div class="info-row">
                        <div class="info-cell">
                            <span class="info-label">ຜູ້ຝາກ:</span>
                            <span class="info-value">MUANJAI</span>
                        </div>
                        <div class="info-cell">
                            <span class="info-label">ເບີຜູ້ຝາກ:</span>
                            <span class="info-value"><?= htmlspecialchars($shop_phone) ?></span>
                        </div>
                    </div>

                    <div class="info-row">
                        <div class="info-cell">
                            <span class="info-label">ຜູ້ຮັບ:</span>
                            <span class="info-value"><?= htmlspecialchars($order['customer_name'] ?? '-') ?></span>
                        </div>
                        <div class="info-cell">
                            <span class="info-label">ເບີຜູ້ຮັບ:</span>
                            <span class="info-value"><?= htmlspecialchars($order['customer_phone'] ?? '-') ?></span>
                        </div>
                    </div>

                    <div class="info-row">
                        <div class="info-cell">
                            <span class="info-label">ຂົນສົ່ງ:</span>
                            <span class="info-value bold"><?= htmlspecialchars($order['company_name'] ?? '-') ?></span>
                        </div>
                        <div class="info-cell">
                            <span class="info-label">ຄ່າຝາກ:</span>
                            <span class="info-value bold"><?= $cod_info ?></span>
                        </div>
                    </div>

                    <div class="info-row last-row">
                        <div class="info-cell full">
                            <span class="info-label">ສາຂາຝາກ:</span>
                            <span class="info-value"><?= htmlspecialchars($order['branch_name'] ?? '-') ?></span>
                        </div>
                    </div>
                </div>

                <!-- FOOTER -->
                <div class="receipt-footer">
                    <div class="footer-left">
                        <div class="warning-item">
                            <div class="warning-icon">
                                <img src="../../img/logo_icon/video.png" alt="video">
                            </div>
                            <div class="warning-text">
                                ບັນທຶກວິດິໂອກ່ອນເປີດກ່ອງທຸກຄັ້ງ
                            </div>
                        </div>
                        <div class="warning-item">
                            <div class="warning-icon">
                                <img src="../../img/logo_icon/grass.png" alt="fragile">
                            </div>
                            <div class="warning-text">
                                ຫ້າມໂຍນ ລະທວັງແຕກ<br>
                                <span class="fragile-en">( FRAGILE )</span>
                            </div>
                        </div>
                    </div>
                    <div class="footer-right">
                        <div class="qr-placeholder">
                            <img src="<?= $qr_api_url ?>" alt="QR Code">
                        </div>
                    </div>
                </div>
            </div>
            <?php
        } else {
            // ========== POS RECEIPT ========== (ไม่มี QR ใน POS ตามโค้ดเดิม)
            ?>
            <div class="receipt-pos">
                <div class="pos-header">
                    <img src="../../img/logo_icon/logo.png" alt="MUANJAI">
                    <div class="pos-shop-name">MUANJAI</div>
                    <div class="pos-phone">Tel: <?= htmlspecialchars($shop_phone) ?></div>
                </div>

                <div class="pos-meta">
                    <span><strong>ເລກບິນ:</strong> <?= $order['OR_id'] ?></span>
                    <span><?= date('d/m/Y H:i', strtotime($order['created_at'])) ?></span>
                </div>

                <table class="pos-table">
                    <thead>
                        <tr>
                            <th>ລາຍການ</th>
                            <th style="text-align:center; width:15%;">ຈນ</th>
                            <th style="text-align:right; width:25%;">ລວມ</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($items as $item): ?>
                            <tr>
                                <td><?= htmlspecialchars($item['product_name']) ?></td>
                                <td style="text-align:center;"><?= $item['quantity'] ?></td>
                                <td style="text-align:right;"><?= number_format($item['total']) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>

                <div class="pos-totals">
                    <div class="pos-total-row">
                        <span>ລວມຍ່ອຍ:</span>
                        <span><?= number_format($order['subtotal']) ?>         <?= $currency_symbol ?></span>
                    </div>
                    <?php if ($order['discount_amount'] > 0): ?>
                        <div class="pos-total-row">
                            <span>ສ່ວນຫຼຸດ:</span>
                            <span>-<?= number_format($order['discount_amount']) ?>             <?= $currency_symbol ?></span>
                        </div>
                    <?php endif; ?>
                    <?php if ($order['tax_amount'] > 0): ?>
                        <div class="pos-total-row">
                            <span>VAT (10%):</span>
                            <span><?= number_format($order['tax_amount']) ?>             <?= $currency_symbol ?></span>
                        </div>
                    <?php endif; ?>
                    <div class="pos-total-row grand">
                        <span>ສຸດທິ:</span>
                        <span><?= number_format($order['total_amount']) ?>         <?= $currency_symbol ?></span>
                    </div>
                </div>

                <?php if ($order['cash_received'] > 0): ?>
                    <div class="pos-cash-info">
                        <div class="pos-cash-row">
                            <span>ຮັບເງິນ:</span>
                            <span><?= number_format($order['cash_received']) ?>             <?= $currency_symbol ?></span>
                        </div>
                        <div class="pos-cash-row">
                            <span>ເງິນທອນ:</span>
                            <span><?= number_format($order['cash_change']) ?>             <?= $currency_symbol ?></span>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="pos-footer">
                    ຂອບໃຈທີ່ໃຊ້ບໍລິການ
                </div>
            </div>
            <?php
        }
    }
    ?>

    <script>
        window.onload = function () {
            setTimeout(() => {
                window.print();
                updatePrintStatus();
            }, 500);
        };

        function updatePrintStatus() {
            const orderIds = <?= json_encode($order_ids) ?>;
            fetch('../api/update_print_status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ order_ids: orderIds })
            });
        }
    </script>
</body>

</html>