<?php
require_once __DIR__ . '/../../templates/header.php';
?>
<style>
    /* Bỏ đi các style của trang desktop cũ */
    body {
        font-size: 14px;
    }
    .pos-mobile-container {
        padding: 10px;
        padding-bottom: 80px; /* Tạo khoảng trống cho sticky footer */
    }
    .order-table-wrapper {
        width: 100%;
        overflow-x: auto; /* Cho phép cuộn ngang */
        -webkit-overflow-scrolling: touch;
    }
    #order-table {
        min-width: 600px; /* Đặt chiều rộng tối thiểu để các cột không bị bóp quá nhỏ */
    }
    #order-table input {
        min-width: 70px;
    }
    .sticky-footer {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        background-color: #ffffff;
        border-top: 1px solid #e3e6f0;
        padding: 10px;
        box-shadow: 0 -2px 5px rgba(0,0,0,0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .sticky-footer .summary-text {
        font-size: 16px;
        font-weight: bold;
    }
    .sticky-footer .summary-total {
        color: #e74a3b;
    }
    /* Style cho modal checkout toàn màn hình hơn */
    #checkout-modal .modal-dialog {
        max-width: 100%;
        margin: 0;
    }
     #checkout-modal .modal-content {
        min-height: 100vh;
        border-radius: 0;
        border: none;
    }
    .select2-container { width: 100% !important; }
</style>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">


<div class="pos-mobile-container">
    <h4>Tạo đơn hàng từ xa</h4>
    
    <div class="form-group">
        <select class="form-control" id="product-search" data-placeholder="Quét mã vạch hoặc tìm tên sản phẩm..."></select>
    </div>

    <div class="order-table-wrapper">
        <table class="table table-sm table-bordered" id="order-table">
            <thead class="thead-light">
                <tr>
                    <th>#</th>
                    <th>Tên sản phẩm</th>
                    <th>SL</th>
                    <th>Giá bán</th>
                    <th>%CK</th>
                    <th>Thành tiền</th>
                    <th></th>
                </tr>
            </thead>
            <tbody id="order-table-body"></tbody>
        </table>
    </div>
</div>

<div class="sticky-footer">
    <div class="summary-text">
        Tổng: <span class="summary-total" id="footer-grand-total">0</span>
    </div>
    <button class="btn btn-success" id="btn-checkout" data-toggle="modal" data-target="#checkout-modal">
        <i class="fas fa-shopping-cart"></i> Thanh toán
    </button>
</div>


<div class="modal fade" id="checkout-modal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Thông tin đơn hàng</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="form-group"><label>Khách hàng</label><div class="input-group"><select class="form-control" id="customer-search"><option value="1" selected>Khách lẻ</option></select><div class="input-group-append"><button class="btn btn-primary" type="button">+</button></div></div></div>
                <div class="form-group"><label for="order-notes">Ghi chú</label><textarea class="form-control" id="order-notes" rows="2"></textarea></div><hr>
                <div class="payment-summary">
                    <div class="form-group row"><label class="col-5 col-form-label">Tiền hàng:</label><div class="col-7"><input type="text" readonly class="form-control-plaintext text-right" id="sub-total" value="0"></div></div>
                    <div class="form-group row"><label class="col-5 col-form-label">Giảm giá:</label><div class="col-7"><div class="input-group"><input type="number" class="form-control" id="order-discount-value" value="0" min="0"><div class="input-group-append"><select class="form-control" id="order-discount-type" style="width: 60px;"><option value="percent">%</option><option value="fixed">VND</option></select></div></div></div></div>
                    <div class="form-group row"><label class="col-5 col-form-label">VAT:</label><div class="col-7"><select class="form-control" id="order-vat"><option value="0">0%</option><option value="5">5%</option><option value="8">8%</option><option value="10">10%</option></select></div></div><hr>
                    <div class="form-group row"><label class="col-5 col-form-label">Tổng cộng:</label><div class="col-7"><input type="text" readonly class="form-control-plaintext text-right" id="grand-total" value="0" style="font-weight:bold; color: #e74a3b;"></div></div>
                    <div class="form-group row"><label class="col-5 col-form-label">Khách trả:</label><div class="col-7"><input type="number" class="form-control text-right" id="amount-paid" value="0" min="0"></div></div>
                    <div class="form-group row"><label class="col-5 col-form-label">Còn nợ:</label><div class="col-7"><input type="text" readonly class="form-control-plaintext text-right" id="amount-debt" value="0"></div></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Quay lại</button>
                <button type="button" class="btn btn-primary" id="btn-save">Lưu đơn hàng</button>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    // Toàn bộ JS logic gần như giữ nguyên, chỉ thay đổi tên nút lưu
    const AJAX_URL = '/quanlybanhang/ajax/pos_ajax.php';
    function formatNumber(num) { return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); }
    function parseNumber(str) { return Number(String(str).replace(/,/g, '')) || 0; }

    $('#product-search').select2({ theme: 'bootstrap4', placeholder: 'Quét mã vạch hoặc tìm sản phẩm...', minimumInputLength: 1, ajax: { url: AJAX_URL, dataType: 'json', delay: 250, data: function (params) { return { action: 'search_products', term: params.term }; }, processResults: function (data) { return { results: $.map(data, function(item) { return { id: item.id, text: item.label, productData: item } }) }; } } });
    $('#customer-search').select2({ theme: 'bootstrap4', placeholder: 'Tìm khách hàng...', dropdownParent: $('#checkout-modal') /* Quan trọng: để dropdown hiển thị đúng trong modal */, ajax: { url: AJAX_URL, dataType: 'json', delay: 250, data: function (params) { return { action: 'search_customers', term: params.term }; }, processResults: function (data) { return { results: $.map(data, function(item) { return { id: item.id, text: item.label } })}; } } });

    function addProductToCart(product) {
        if (!product || !product.name) return;
        if (product.inventory <= 0) { alert('Sản phẩm "' + product.name + '" đã hết hàng!'); return; }
        const existingRow = $(`#order-table-body tr[data-product-id="${product.id}"]`);
        if (existingRow.length > 0) {
            const quantityInput = existingRow.find('.quantity-input');
            quantityInput.val(parseNumber(quantityInput.val()) + 1).trigger('input');
        } else {
            const stt = $('#order-table-body tr').length + 1;
            const newRow = `<tr data-product-id="${product.id}" data-code="${product.code}" data-inventory="${product.inventory}" data-origin-price="${product.origin_price}"><td>${stt}</td><td class="text-left">${product.name}</td><td><input type="number" class="form-control form-control-sm quantity-input" value="1" min="1"></td><td><input type="text" class="form-control form-control-sm price-input" value="${product.price}"></td><td><input type="number" class="form-control form-control-sm discount-input" value="0" min="0" max="100"></td><td class="line-total text-right font-weight-bold">0</td><td><button class="btn btn-danger btn-sm btn-remove-item">&times;</button></td></tr>`;
            $('#order-table-body').append(newRow);
        }
        updateCalculations();
    }
    
    function updateCalculations() {
        let subTotal = 0;
        $('#order-table-body tr').each(function() {
            const row = $(this);
            const quantity = parseNumber(row.find('.quantity-input').val());
            const price = parseNumber(row.find('.price-input').val());
            const discount = parseNumber(row.find('.discount-input').val());
            const originPrice = parseNumber(row.data('origin-price'));
            if (price < originPrice) { row.find('.price-input').css('border-color', 'red'); } else { row.find('.price-input').css('border-color', '#ddd'); }
            const lineTotal = (quantity * price) * (1 - (discount / 100));
            row.find('.line-total').text(formatNumber(Math.round(lineTotal)));
            subTotal += lineTotal;
        });
        $('#sub-total').val(formatNumber(Math.round(subTotal)));
        const discountValue = parseNumber($('#order-discount-value').val());
        const discountType = $('#order-discount-type').val();
        let totalDiscountAmount = (discountType === 'percent') ? (subTotal * (discountValue / 100)) : discountValue;
        const subTotalAfterDiscount = subTotal - totalDiscountAmount;
        const vatPercent = parseNumber($('#order-vat').val());
        const vatAmount = subTotalAfterDiscount * (vatPercent / 100);
        const grandTotal = subTotalAfterDiscount + vatAmount;
        const amountPaid = parseNumber($('#amount-paid').val());
        const amountDebt = grandTotal - amountPaid;
        $('#grand-total').val(formatNumber(Math.round(grandTotal)));
        $('#footer-grand-total').text(formatNumber(Math.round(grandTotal))); // Cập nhật footer
        $('#amount-debt').val(formatNumber(Math.round(amountDebt)));
    }

    function resetOrderForm() {
        $('#order-table-body').empty();
        $('#order-notes').val('');
        $('#customer-search').val('1').trigger('change');
        $('#order-discount-value').val(0);
        $('#amount-paid').val(0);
        $('#checkout-modal').modal('hide');
        updateCalculations();
        $('#product-search').select2('focus');
    }

    $('#product-search').on('select2:select', function (e) { if (e.params.data.productData) { addProductToCart(e.params.data.productData); } $(this).val(null).trigger('change'); $('#product-search').select2('open'); });
    $('#order-table-body').on('input', '.quantity-input, .price-input, .discount-input', updateCalculations);
    $('#order-discount-value, #order-discount-type, #order-vat, #amount-paid').on('input change', updateCalculations);
    $('#order-table-body').on('click', '.btn-remove-item', function() { $(this).closest('tr').remove(); $('#order-table-body tr').each(function(index) { $(this).find('td:first').text(index + 1); }); updateCalculations(); });
    
    // Nút lưu giờ nằm trong modal
    $('#btn-save').on('click', function(e) {
        e.preventDefault();
        let items = [];
        let hasError = false;
        if ($('#order-table-body tr').length === 0) { alert('Vui lòng thêm sản phẩm vào đơn hàng.'); return; }
        $('#order-table-body tr').each(function() {
            const row = $(this);
            const productName = row.find('td:nth-child(2)').text();
            const price = parseNumber(row.find('.price-input').val());
            const originPrice = parseNumber(row.data('origin-price'));
            if (price < originPrice) { alert(`Giá bán của "${productName}" không được thấp hơn giá vốn!`); hasError = true; return false; }
            items.push({ id: row.data('product-id'), code: row.data('code'), quantity: parseNumber(row.find('.quantity-input').val()), price: price, discount: parseNumber(row.find('.discount-input').val()), name: productName });
        });
        if (hasError) return;
        const orderData = { action: 'save_order', customer_id: $('#customer-search').val() || 1, notes: $('#order-notes').val(), customer_pay: parseNumber($('#amount-paid').val()), items: JSON.stringify(items), discount_value: parseNumber($('#order-discount-value').val()), discount_type: $('#order-discount-type').val(), vat: parseNumber($('#order-vat').val()) };
        
        $(this).prop('disabled', true).text('Đang lưu...');
        $.ajax({
            url: AJAX_URL, type: 'POST', data: orderData, dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert(response.message);
                    resetOrderForm();
                } else {
                    alert('Lỗi: ' + (response.message || 'Không thể lưu đơn hàng.'));
                }
            },
            error: function() { alert('Đã có lỗi kết nối xảy ra.'); },
            complete: function() { $('#btn-save').prop('disabled', false).text('Lưu đơn hàng'); }
        });
    });

    updateCalculations();
    $('#product-search').select2('focus');
});
</script>