<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$page_title = 'ລາຍລະອຽດບິນ';
require_once '../includes/header.php';

$order_id = $_GET['id'] ?? null;
if (!$order_id) {
    echo "<div class='card'><div class='card-body' style='text-align:center;padding:40px;'>
                <i class='fas fa-exclamation-triangle fa-3x' style='color:var(--accent);margin-bottom:15px;display:block;'></i>
                <h4>ບໍ່ພົບລະຫັດບິນ</h4>
                <p style='color:var(--text-secondary);'>ກະລຸນາສະແກນ QR Code ໃບບິນໃໝ່</p>
                <a href='scan_order.php' class='btn btn-primary' style='margin-top:15px;'><i class='fas fa-qrcode'></i> ສະແກນໃໝ່</a>
            </div></div>";
    require_once '../includes/footer.php';
    exit;
}

$shop_id = $_SESSION['shop_id'];

// Get Order Details
$sql = "SELECT o.*, c.name as customer_name, c.phone as customer_phone,
                sc.company_name as shipping_company, sb.branch_name as shipping_branch,
                cur.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 cur ON o.currencys_id = cur.currencys_id
            WHERE o.OR_id = ? AND o.shop_id = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo "<div class='card'><div class='card-body' style='padding:20px;color:#dc3545;'>
                <strong>SQL Error (order):</strong> " . htmlspecialchars($conn->error) . "
            </div></div>";
    require_once '../includes/footer.php';
    exit;
}
$stmt->bind_param("si", $order_id, $shop_id);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();

if (!$order) {
    echo "<div class='card'><div class='card-body' style='text-align:center;padding:40px;'>
                <i class='fas fa-box-open fa-3x' style='color:var(--text-secondary);margin-bottom:15px;display:block;'></i>
                <h4>ບໍ່ພົບຂໍ້ມູນບິນນີ້</h4>
                <p style='color:var(--text-secondary);'>ລະຫັດບິນ: <strong>" . htmlspecialchars($order_id) . "</strong><br>Shop ID: " . htmlspecialchars($shop_id) . "<br>ອາດຈະບໍ່ຖືກຕ້ອງ ຫຼື ອາດຖືກລົບໄປແລ້ວ.</p>
                <a href='history_pos.php' class='btn btn-primary' style='margin-top:15px;'><i class='fas fa-history'></i> ກັບຄືນໜ້າປະຫວັດ</a>
                <a href='scan_order.php' class='btn btn-secondary' style='margin-top:15px;margin-left:10px;'><i class='fas fa-qrcode'></i> ສະແກນໃໝ່</a>
            </div></div>";
    require_once '../includes/footer.php';
    exit;
}

// Get Order Items
$sql = "SELECT oi.*, COALESCE(p.products_name, oi.product_name) as product_name, p.image as product_image, p.barcode, p.product_code 
            FROM order_items oi 
            LEFT JOIN products p ON (
                (oi.product_id != '' AND (oi.product_id = p.id OR oi.product_id = p.product_code OR oi.product_id = p.barcode))
                OR (TRIM(oi.product_name) = TRIM(p.products_name))
            )
            WHERE oi.order_id = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo "<div class='card'><div class='card-body' style='padding:20px;color:#dc3545;'>
                <strong>SQL Error (items):</strong> " . htmlspecialchars($conn->error) . "
            </div></div>";
    require_once '../includes/footer.php';
    exit;
}
$stmt->bind_param("i", $order['id']);
$stmt->execute();
$items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$symbol = $order['currencys_symbol'] ?? '₭';
?>

<style>
    .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        flex-wrap: wrap;
        gap: 15px;
    }

    .order-title {
        font-size: 24px;
        font-weight: 700;
        margin: 0;
    }

    .vo-badge {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 13px;
        font-weight: 600;
    }

    .vo-badge.paid {
        background: rgba(40, 167, 69, 0.15);
        color: #28a745;
    }

    .vo-badge.pending {
        background: rgba(255, 193, 7, 0.15);
        color: #ffc107;
    }

    .vo-info-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        margin-bottom: 25px;
    }

    .vo-info-card {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 20px;
        border-top: 4px solid var(--accent);
    }

    .vo-info-card h4 {
        margin-top: 0;
        margin-bottom: 15px;
        color: var(--accent);
        font-size: 16px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .vo-info-row {
        display: flex;
        justify-content: space-between;
        padding: 8px 0;
        border-bottom: 1px dashed var(--border-color);
    }

    .vo-info-row:last-child {
        border-bottom: none;
    }

    .vo-info-label {
        color: var(--text-secondary);
        font-weight: 500;
    }

    .vo-info-val {
        font-weight: 600;
        text-align: right;
    }

    .vo-items-table {
        width: 100%;
        border-collapse: collapse;
        background: var(--card-bg);
        border-radius: 12px;
        overflow: hidden;
        border: 1px solid var(--border-color);
    }

    .vo-items-table th {
        background: var(--accent);
        padding: 12px 15px;
        text-align: left;
        color: #fff;
        font-weight: 600;
    }

    .vo-items-table td {
        padding: 12px 15px;
        border-bottom: 1px solid var(--border-color);
        vertical-align: middle;
    }

    .vo-items-table tr:last-child td {
        border-bottom: none;
    }

    .vo-totals-box {
        background: var(--card-bg);
        border: 1px solid var(--border-color);
        border-radius: 12px;
        padding: 20px;
        margin-top: 20px;
        width: 300px;
        margin-left: auto;
    }

    .vo-totals-row {
        display: flex;
        justify-content: space-between;
        padding: 8px 0;
    }

    .vo-totals-row.grand {
        border-top: 2px solid var(--border-color);
        margin-top: 10px;
        padding-top: 15px;
        font-size: 18px;
        font-weight: 700;
        color: var(--accent);
    }

    /* Desktop: hide the mobile header content, show only index */
    .vo-mobile-header-content {
        display: none;
    }

    .vo-desktop-index {
        display: inline;

    }


    @media (max-width: 768px) {
        .vo-info-grid {
            grid-template-columns: 1fr;
        }

        .vo-totals-box {
            width: 100%;
        }

        .order-title {
            font-size: 18px;
        }

        /* Responsive Table */
        .vo-items-table,
        .vo-items-table tbody,
        .vo-items-table tr,
        .vo-items-table td {
            display: block;
            width: 100%;
        }

        .vo-items-table thead {
            display: none;
        }

        .vo-items-table td {
            text-align: right !important;
            padding-left: 40%;
            position: relative;
        }

        .vo-items-table td::before {
            content: attr(data-label);
            position: absolute;
            left: 15px;
            font-weight: 600;
            text-align: left;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-secondary);
        }

        .vo-items-table tr {
            border-bottom: 2px solid var(--border-color);
            margin-bottom: 10px;
        }

        .vo-items-table tr:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }

        /* Row header: # 1 centered with code/barcode on right */
        .vo-items-table td.vo-mobile-header {
            display: flex;
            justify-content: center;
            align-items: center;
            padding-left: 15px;
            background: rgba(0, 0, 0, 0.02);
            font-weight: 700;
            font-size: 15px;
        }

        .vo-items-table td.vo-mobile-header::before {
            display: none;
        }

        .vo-mobile-header-content {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            flex-wrap: wrap;
        }

        /* Product cell */
        .vo-items-table td:nth-child(2) {
            text-align: left !important;
            padding-left: 15px;
            padding-top: 15px;
        }

        .vo-items-table td:nth-child(2)::before {
            display: none;
        }

        /* Hide desktop-only code & barcode columns */
        .vo-items-table td.vo-desktop-only {
            display: none;
        }

        /* Mobile: show mobile header, hide desktop index */
        .vo-desktop-index {
            display: none;
        }
    }
</style>

<div class="order-header">
    <div>
        <h1 class="order-title">
            <i class="fas fa-file-invoice"></i> ບິນເລກທີ: <?= htmlspecialchars($order['OR_id']) ?>
        </h1>
        <p style="color:var(--text-secondary);margin-top:8px;">
            <i class="far fa-clock"></i> ວັນທີສັ່ງຊື້: <?= date('d/m/Y H:i', strtotime($order['created_at'])) ?>
        </p>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap;">
        <a href="history_pos.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> ກັບຄືນ
        </a>
        <a href="print_invoice.php?id=<?= urlencode($order['OR_id']) ?>" target="_blank" class="btn btn-primary">
            <i class="fas fa-print"></i> ພິມໃບບິນ
        </a>
        <a href="scan_order.php" class="btn btn-secondary">
            <i class="fas fa-qrcode"></i> ສະແກນໃໝ່
        </a>
    </div>
</div>

<div class="vo-info-grid">
    <!-- Customer Info -->
    <div class="vo-info-card">
        <h4><i class="fas fa-user"></i> ຂໍ້ມູນລູກຄ້າ</h4>
        <div class="vo-info-row">
            <span class="vo-info-label">ຊື່:</span>
            <span class="vo-info-val"><?= htmlspecialchars($order['customer_name'] ?? 'ລູກຄ້າທົ່ວໄປ') ?></span>
        </div>
        <div class="vo-info-row">
            <span class="vo-info-label">ເບີໂທ:</span>
            <span class="vo-info-val"><?= htmlspecialchars($order['customer_phone'] ?? '-') ?></span>
        </div>
        
    </div>

    <!-- Shipping Info -->
    <div class="vo-info-card">
        <h4><i class="fas fa-truck"></i> ຂໍ້ມູນການຈັດສົ່ງ</h4>
        <div class="vo-info-row">
            <span class="vo-info-label">ບໍລິສັດຂົນສົ່ງ:</span>
            <span class="vo-info-val"><?= htmlspecialchars($order['shipping_company'] ?? '-') ?></span>
        </div>
        <div class="vo-info-row">
            <span class="vo-info-label">ສາຂາ:</span>
            <span class="vo-info-val"><?= htmlspecialchars($order['shipping_branch'] ?? '-') ?></span>
        </div>
        <div class="vo-info-row">
            <span class="vo-info-label">ເລກພັດສະດຸ:</span>
            <span class="vo-info-val"><?= htmlspecialchars($order['shipping_code'] ?? '-') ?></span>
        </div>
    </div>

    <!-- Order Status -->
    <div class="vo-info-card">
        <h4><i class="fas fa-info-circle"></i> ສະຖານະບິນ</h4>
        <div class="vo-info-row">
            <span class="vo-info-label">ປະເພດ:</span>
            <span class="vo-info-val">
                <?= $order['order_type'] === 'pos' ? 'ໜ້າຮ້ານ' : ($order['order_type'] === 'online' ? 'ອອນລາຍ' : 'ຂາຍສົ່ງ') ?>
            </span>
        </div>
        <div class="vo-info-row">
            <span class="vo-info-label">ສະຖານະ:</span>
            <span class="vo-info-val">
                <?php if ($order['payment_status'] === 'paid'): ?>
                        <span class="vo-badge paid"><i class="fas fa-check"></i> ຈ່າຍແລ້ວ</span>
                <?php else: ?>
                        <span class="vo-badge pending"><i class="fas fa-clock"></i> <?= $order['payment_status'] ?></span>
                <?php endif; ?>
            </span>
        </div>
        <div class="vo-info-row">
            <span class="vo-info-label">ໝາຍເຫດ:</span>
            <span class="vo-info-val"><?= htmlspecialchars($order['notes'] ?? '-') ?></span>
        </div>
    </div>
</div>

<!-- Items Table -->
<h4 style="margin-bottom:15px;"><i class="fas fa-box"></i> ລາຍການສິນຄ້າ</h4>
<div style="overflow-x: auto;">
    <table class="vo-items-table">
        <thead>
            <tr>
                <th width="50">#</th>
                <th>ສິນຄ້າ</th>
                <th>ລະຫັດສິນຄ້າ</th>
                <th>ບາໂຄດ</th>
                <th style="text-align: right;">ລາຄາ/ໜ່ວຍ</th>
                <th style="text-align: center;">ຈຳນວນ</th>
                <th style="text-align: right;">ລວມ</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($items)): ?>
                    <tr>
                        <td colspan="7" style="text-align:center;padding:30px;color:var(--text-secondary);">ບໍ່ມີລາຍການສິນຄ້າ
                        </td>
                    </tr>
            <?php else: ?>
                    <?php foreach ($items as $index => $item): ?>
                            <tr>
                                <td class="vo-mobile-header" data-label="#">
                                    <span class="vo-desktop-index"><?= $index + 1 ?></span>
                                    <span class="vo-mobile-header-content">
                                        <span># <?= $index + 1 ?></span>
                                        <?php if (!empty($item['product_code'])): ?>
                                                <span
                                                    style="font-size: 13px; font-weight: 500; color: var(--text-secondary);"><?= htmlspecialchars($item['product_code']) ?></span>
                                        <?php endif; ?>
                                        <?php if (!empty($item['barcode'])): ?>
                                                <span
                                                    style="font-size: 13px; font-weight: 500; color: var(--text-secondary);"><?= htmlspecialchars($item['barcode']) ?></span>
                                        <?php endif; ?>
                                    </span>
                                </td>
                                <td data-label="ສິນຄ້າ">
                                    <div style="display: flex; flex-direction: column; align-items: flex-start; gap: 8px;">
                                        <?php if (!empty($item['product_image'])): ?>
                                                <img src="../api/get_image.php?f=<?= urlencode($item['product_image']) ?>&w=200"
                                                    style="width: 70px; height: 70px; border-radius: 8px; object-fit: cover; border: 1px solid var(--border-color);"
                                                    alt="">
                                        <?php else: ?>
                                                <div
                                                    style="width: 70px; height: 70px; border-radius: 8px; background: rgba(0,0,0,0.03); border: 1px solid var(--border-color); display: flex; align-items: center; justify-content: center; color: var(--text-secondary);">
                                                    <i class="fas fa-box fa-2x"></i>
                                                </div>
                                        <?php endif; ?>
                                        <div style="text-align: left;">
                                            <div style="font-weight: 500; font-size: 14px; line-height: 1.4;">
                                                <?= htmlspecialchars($item['product_name'] ?? '') ?>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="vo-desktop-only" data-label="ລະຫັດ">
                                    <?= !empty($item['product_code']) ? htmlspecialchars($item['product_code']) : '-' ?></td>
                                <td class="vo-desktop-only" data-label="ບາໂຄດ">
                                    <?= !empty($item['barcode']) ? htmlspecialchars($item['barcode']) : '-' ?></td>
                                <td data-label="ລາຄາ/ໜ່ວຍ" style="text-align: right;"><?= number_format($item['unit_price'] ?? 0) ?>
                                    <?= $symbol ?>
                                </td>
                                <td data-label="ຈຳນວນ" style="text-align: center; font-weight: 600;"><?= $item['quantity'] ?></td>
                                <td data-label="ລວມ" style="text-align: right; font-weight: 600; color: var(--accent);">
                                    <?= number_format($item['total']) ?>                 <?= $symbol ?>
                                </td>
                            </tr>
                    <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<!-- Totals -->
<div class="vo-totals-box">
    <div class="vo-totals-row">
        <span>ລວມຍ່ອຍ:</span>
        <span><?= number_format($order['subtotal']) ?> <?= $symbol ?></span>
    </div>
    <?php if ($order['discount_amount'] > 0): ?>
            <div class="vo-totals-row">
                <span>ສ່ວນຫຼຸດ:</span>
                <span style="color: var(--danger);">-<?= number_format($order['discount_amount']) ?>         <?= $symbol ?></span>
            </div>
    <?php endif; ?>
    <?php if ($order['tax_amount'] > 0): ?>
            <div class="vo-totals-row">
                <span>VAT (10%):</span>
                <span><?= number_format($order['tax_amount']) ?>         <?= $symbol ?></span>
            </div>
    <?php endif; ?>
    <div class="vo-totals-row grand">
        <span>ຍອດລວມສູດທິ:</span>
        <span><?= number_format($order['total_amount']) ?> <?= $symbol ?></span>
    </div>

    <?php if ($order['cash_received'] > 0): ?>
            <div class="vo-totals-row"
                style="font-size: 14px; border-top: 1px dashed var(--border-color); padding-top: 10px; margin-top: 10px;">
                <span style="color:var(--text-secondary);">ຮັບເງິນ:</span>
                <span><?= number_format($order['cash_received']) ?>         <?= $symbol ?></span>
            </div>
            <div class="vo-totals-row" style="font-size: 14px;">
                <span style="color:var(--text-secondary);">ເງິນທອນ:</span>
                <span><?= number_format($order['cash_change']) ?>         <?= $symbol ?></span>
            </div>
    <?php endif; ?>
</div>

<?php require_once '../includes/footer.php'; ?>