<?php
require_once __DIR__ . '/../../templates/header.php';

$suppliers_query = $conn->query("SELECT ID, supplier_name FROM cms_suppliers ORDER BY supplier_name ASC");
if ($suppliers_query === false) {
    die("Lỗi nghiêm trọng: Không thể truy vấn danh sách nhà cung cấp. Lỗi MySQL: " . $conn->error);
}
$suppliers = $suppliers_query->fetch_all(MYSQLI_ASSOC);

$slip_id = intval($_GET['id'] ?? 0);
$slip_data_for_js = 'null';
$page_title = 'Tạo phiếu nhập';
$page_sub_title = '';

if ($slip_id > 0) {
    $stmt = $conn->prepare("SELECT * FROM cms_input WHERE id = ? AND deleted = 0");
    if($stmt) {
        $stmt->bind_param("i", $slip_id);
        $stmt->execute();
        $slip = $stmt->get_result()->fetch_assoc();
        $stmt->close();
    
        if($slip) {
            $page_title = 'Chỉnh sửa Phiếu nhập';
            $page_sub_title = $slip['input_code'];
            
            $slip_items_from_db = json_decode($slip['detail_input'], true);
            $enriched_slip_items = [];

            if (is_array($slip_items_from_db) && !empty($slip_items_from_db)) {
                
                $product_ids = [];
                foreach ($slip_items_from_db as $item) {
                    if (!empty($item['id'])) {
                        $product_ids[] = intval($item['id']);
                    }
                }
                $product_ids = array_unique($product_ids);

                if (!empty($product_ids)) {
                    $products_info = [];
                    $units_data = [];
                    
                    $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
                    $types = str_repeat('i', count($product_ids));
                    
                    $sql_products = "SELECT id, prd_name, prd_code, prd_unit_id FROM cms_products WHERE id IN ($ids_placeholder)";
                    $stmt_products = $conn->prepare($sql_products);
                    $stmt_products->bind_param($types, ...$product_ids);
                    $stmt_products->execute();
                    $products_result = $stmt_products->get_result();
                    while($row = $products_result->fetch_assoc()) { $products_info[$row['id']] = $row; }
                    $stmt_products->close();

                    $unit_ids = array_filter(array_unique(array_column($products_info, 'prd_unit_id')));
                    if(!empty($unit_ids)) {
                        $unit_ids_placeholder = implode(',', array_fill(0, count($unit_ids), '?'));
                        $unit_types = str_repeat('i', count($unit_ids));
                        $sql_units = "SELECT id, prd_unit_name FROM cms_products_unit WHERE id IN ($unit_ids_placeholder)";
                        $stmt_units = $conn->prepare($sql_units);
                        $stmt_units->bind_param($unit_types, ...$unit_ids);
                        $stmt_units->execute();
                        $units_result = $stmt_units->get_result();
                        while($row = $units_result->fetch_assoc()) { $units_data[$row['id']] = $row['prd_unit_name']; }
                        $stmt_units->close();
                    }
                    
                    foreach ($slip_items_from_db as $item) {
                        if (isset($item['id']) && isset($products_info[$item['id']])) {
                            $product = $products_info[$item['id']];
                            $enriched_item = [
                                'id'               => $item['id'],
                                'name'             => htmlspecialchars($product['prd_name']), 
                                'code'             => htmlspecialchars($product['prd_code']),
                                'unit'             => htmlspecialchars($units_data[$product['prd_unit_id']] ?? 'N/A'),
                                'quantity'         => floatval($item['quantity'] ?? 0),
                                'price'            => floatval($item['price'] ?? 0),
                                'discount_percent' => floatval($item['discount_percent'] ?? 0)
                            ];
                            $enriched_slip_items[] = $enriched_item;
                        }
                    }
                }
            }
            $slip['detail_input'] = $enriched_slip_items;
            $slip_data_for_js = json_encode($slip);

        } else {
            header('Location: danhsach_phieunhap.php?error=not_found');
            exit();
        }
    } else {
        header('Location: danhsach_phieunhap.php?error=db_error');
        exit();
    }
}
?>

<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.3/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.13.3/jquery-ui.js"></script>

<div class="container-fluid">
    <form id="import-form" novalidate>
        <input type="hidden" id="slip_id" value="<?php echo $slip_id; ?>">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0 text-gray-800"><a href="danhsach_phieunhap.php" class="text-dark me-2" title="Quay lại"><i class="fas fa-arrow-left"></i></a><?php echo $page_title; ?> <?php if($page_sub_title): ?><span class="badge bg-primary align-middle"><?php echo $page_sub_title; ?></span><?php endif; ?></h1>
            <div><a href="danhsach_phieunhap.php" class="btn btn-secondary">Hủy</a><button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>Lưu phiếu</button></div>
        </div>
        <div class="row">
            <div class="col-lg-8">
                <div class="card shadow mb-4"><div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Thông tin sản phẩm</h6></div><div class="card-body"><div class="mb-3"><input type="text" id="product_search" class="form-control" placeholder="Nhập mã hoặc tên sản phẩm để tìm kiếm..."></div><div class="table-responsive"><table class="table table-bordered" id="product-table"><thead class="table-light text-center"><tr><th>STT</th><th>Tên sản phẩm</th><th style="width: 80px;">ĐVT</th><th style="width: 100px;">SL</th><th style="width: 130px;">Giá nhập</th><th style="width: 90px;">% CK</th><th style="width: 140px;">Thành tiền</th><th style="width: 50px;"></th></tr></thead><tbody><tr><td colspan="8" class="text-center p-5">Chưa có sản phẩm</td></tr></tbody></table></div></div></div>
            </div>
            <div class="col-lg-4">
                <div class="card shadow mb-4"><div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Thông tin chung</h6></div><div class="card-body"><div class="mb-3"><label for="supplier-id" class="form-label">Nhà cung cấp</label><select id="supplier-id" class="form-control"><?php if(empty($suppliers)): ?><option value="0">Không có NCC</option><?php else: ?><option value="0">-- Bỏ qua / Không chọn --</option><?php foreach($suppliers as $supplier): ?><option value="<?php echo $supplier['ID']; ?>"><?php echo htmlspecialchars($supplier['supplier_name']); ?></option><?php endforeach; ?><?php endif; ?></select></div><div class="mb-3"><label for="input_date" class="form-label">Ngày nhập</label><input type="datetime-local" id="input_date" class="form-control"></div><div class="mb-3"><label for="notes" class="form-label">Ghi chú</label><textarea id="notes" class="form-control" rows="3"></textarea></div></div></div>
                <div class="card shadow"><div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Thanh toán</h6></div><div class="card-body"><div class="d-flex justify-content-between mb-2"><span>Tổng tiền hàng:</span><span id="total-price">0</span></div><div class="d-flex justify-content-between mb-2 fs-5"><strong>Tổng cộng:</strong><strong id="final-total" class="text-danger">0</strong></div><div class="d-flex justify-content-between align-items-center mb-2"><label for="payed" class="form-label mb-0">Thanh toán:</label><input type="text" id="payed" class="form-control form-control-sm w-50 text-end" value="0"></div><div class="d-flex justify-content-between"><strong>Còn nợ:</strong><strong id="lack" class="text-danger">0</strong></div></div></div>
            </div>
        </div>
    </form>
</div>

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

<script>
$(document).ready(function() {
    let productList = [];
    const slipData = <?php echo $slip_data_for_js; ?>;

    function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }
    function parseNumber(str) { return parseFloat(String(str).replace(/\./g, '').replace(/,/g, '.')) || 0; }
    
    function updateTotals(isManualPay = false) {
        let finalTotal = productList.reduce((sum, p) => {
            let lineTotal = (p.quantity || 0) * (p.price || 0);
            let discount = lineTotal * (parseFloat(p.discount_percent) || 0) / 100;
            return sum + (lineTotal - discount);
        }, 0);
        
        $('#total-price').text(formatNumber(finalTotal));
        $('#final-total').text(formatNumber(finalTotal));
        
        if (!isManualPay) {
            $('#payed').val(formatNumber(finalTotal));
        }
        
        let payed = parseNumber($('#payed').val());
        let lack = finalTotal - payed;
        $('#lack').text(formatNumber(lack));
    }

    function renderTable() {
        const tbody = $('#product-table tbody');
        tbody.empty();
        if(productList.length === 0) {
            tbody.html('<tr><td colspan="8" class="text-center p-5">Chưa có sản phẩm</td></tr>');
            updateTotals();
            return;
        }
        productList.forEach((p, index) => {
            let lineTotal = (p.quantity || 0) * (p.price || 0);
            let discount = lineTotal * (parseFloat(p.discount_percent) || 0) / 100;
            let finalLineTotal = lineTotal - discount;
            const row = `<tr data-index="${index}">
                            <td>${index + 1}</td>
                            <td>${p.name || 'N/A'}<br><small class="text-muted">${p.code || ''}</small></td>
                            <td class="text-center">${p.unit || 'N/A'}</td>
                            <td><input type="number" class="form-control form-control-sm quantity-input" value="${p.quantity}" min="1"></td>
                            <td><input type="text" class="form-control form-control-sm price-input text-end" value="${formatNumber(p.price)}"></td>
                            <td><input type="number" class="form-control form-control-sm discount-input text-end" value="${p.discount_percent || 0}" min="0" max="100"></td>
                            <td class="text-end fw-bold">${formatNumber(finalLineTotal)}</td>
                            <td class="text-center"><button type="button" class="btn btn-danger btn-sm remove-item-btn">&times;</button></td>
                         </tr>`;
            tbody.append(row);
        });
        updateTotals();
    }

    function addProductToTable(product) {
        const existingProduct = productList.find(p => p.id === product.id);
        if (existingProduct) {
            existingProduct.quantity = (parseInt(existingProduct.quantity) || 0) + 1;
        } else {
            productList.push({ 
                id: product.id, 
                name: product.name, 
                code: product.code, 
                unit: product.unit, 
                quantity: 1, 
                price: product.price || 0, 
                discount_percent: 0 
            });
        }
        renderTable();
    }

    $("#product_search").autocomplete({
        source: (request, response) => $.getJSON("/quanlybanhang/ajax/imports_ajax.php", { action: 'search_products', term: request.term }, response),
        minLength: 1,
        select: (event, ui) => { 
            addProductToTable(ui.item); 
            $(event.target).val(''); 
            return false; 
        }
    });

    $('#product-table').on('input', '.quantity-input, .price-input, .discount-input', function() {
        const row = $(this).closest('tr');
        const index = row.data('index');
        if (index === undefined || !productList[index]) return;
        
        productList[index].quantity = parseInt(row.find('.quantity-input').val()) || 1;
        productList[index].price = parseNumber(row.find('.price-input').val());
        productList[index].discount_percent = parseFloat(row.find('.discount-input').val()) || 0;
        
        let lineTotal = productList[index].quantity * productList[index].price;
        let discount = lineTotal * (productList[index].discount_percent / 100);
        let finalLineTotal = lineTotal - discount;

        row.find('td:nth-last-child(2)').text(formatNumber(finalLineTotal));
        
        updateTotals();
    });

    $('#payed').on('input', function() {
        updateTotals(true);
    }).on('blur', function() { 
        const val = parseNumber($(this).val());
        $(this).val(formatNumber(val));
    });
    
    $('#product-table').on('click', '.remove-item-btn', function() { 
        productList.splice($(this).closest('tr').data('index'), 1); 
        renderTable(); 
    });

    $('#import-form').on('submit', function(e) {
        e.preventDefault();
        const payload = {
            action: 'save_slip', 
            slip_id: $('#slip_id').val(),
            supplier_id: $('#supplier-id').val(), 
            input_date: $('#input_date').val(),
            notes: $('#notes').val(), 
            payed: parseNumber($('#payed').val()),
            products_list: JSON.stringify(productList)
        };
        if (productList.length === 0) { 
            alert('Vui lòng thêm ít nhất một sản phẩm.'); 
            return; 
        }

        $.post('/quanlybanhang/ajax/imports_ajax.php', payload, (res) => {
            if (res.status === 'success') {
                alert(res.message);
                window.location.href = `danhsach_phieunhap.php?v=${new Date().getTime()}`;
            } else { 
                alert('Lỗi: ' + (res.message || 'Không xác định')); 
            }
        }, 'json').fail(() => alert('Lỗi kết nối máy chủ. Vui lòng thử lại.'));
    });

    if(slipData) {
        $('#supplier-id').val(slipData.supplier_id);
        if (slipData.input_date) {
            const date = new Date(slipData.input_date);
            date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
            $('#input_date').val(date.toISOString().slice(0,16));
        }
        $('#notes').val(slipData.notes);
        
        if(slipData.detail_input && Array.isArray(slipData.detail_input)) { 
            productList = slipData.detail_input; 
        }
        
        renderTable();

        if ($('#slip_id').val() > 0) {
            $('#payed').val(formatNumber(slipData.payed));
            updateTotals(true);
        }

    } else {
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        $('#input_date').val(now.toISOString().slice(0,16));
        renderTable();
    }
});
</script>