<?php
require_once __DIR__ . '/../../templates/header.php';
// Lấy danh sách kho khác kho hiện tại để chọn
$current_store_id = $_SESSION['store_id'] ?? 1;
$stores = $conn->query("SELECT id, store_name FROM cms_stores WHERE id != " . $current_store_id)->fetch_all(MYSQLI_ASSOC);
$current_store_name = $conn->query("SELECT store_name FROM cms_stores WHERE id = " . $current_store_id)->fetch_assoc()['store_name'];
?>
<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/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />

<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Tạo Phiếu Chuyển Kho</h1>
        <a href="list.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left fa-sm"></i> Quay lại danh sách</a>
    </div>

    <form id="transfer-form">
        <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">Chọn sản phẩm cần chuyển</h6></div>
                    <div class="card-body">
                        <select id="product-search" class="form-control mb-3" data-placeholder="Nhập tên hoặc mã sản phẩm để tìm..."></select>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead><tr><th>Tên sản phẩm</th><th>Tồn kho</th><th style="width: 120px;">Số lượng</th><th style="width: 50px;">Xóa</th></tr></thead>
                                <tbody id="transfer-items"></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 phiếu</h6></div>
                    <div class="card-body">
                        <div class="form-group mb-3"><label>Từ kho:</label><input type="text" class="form-control" value="<?php echo htmlspecialchars($current_store_name); ?>" readonly></div>
                        <div class="form-group mb-3"><label for="to_store_id">Chuyển đến kho:</label>
                            <select id="to_store_id" class="form-control" required>
                                <option value="">-- Chọn kho nhận --</option>
                                <?php foreach($stores as $store): ?>
                                    <option value="<?php echo $store['id']; ?>"><?php echo htmlspecialchars($store['store_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group"><label for="notes">Ghi chú:</label><textarea id="notes" class="form-control" rows="5"></textarea></div>
                    </div>
                    <div class="card-footer text-right">
                         <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Lưu & Chuyển</button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</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() {
    let transferItems = [];

    $('#product-search').select2({
        theme: 'bootstrap-5',
        ajax: {
            url: '/quanlybanhang/ajax/transfers_ajax.php',
            dataType: 'json', delay: 250,
            data: (params) => ({ action: 'search_products_in_store', term: params.term }),
            processResults: (data) => ({ results: $.map(data, (item) => ({ id: item.id, text: `[${item.prd_code}] ${item.prd_name}`, product: item }))})
        }
    });

    $('#product-search').on('select2:select', function(e) {
        const product = e.params.data.product;
        if (!transferItems.find(item => item.id === product.id)) {
            transferItems.push({id: product.id, name: product.prd_name, inventory: product.inventory, quantity: 1});
            renderItems();
        }
        $(this).val(null).trigger('change');
    });

    function renderItems() {
        const tbody = $('#transfer-items');
        tbody.empty();
        transferItems.forEach((item, index) => {
            tbody.append(`<tr data-index="${index}">
                <td>${item.name}</td>
                <td>${item.inventory}</td>
                <td><input type="number" class="form-control quantity-input" value="${item.quantity}" min="1" max="${item.inventory}"></td>
                <td><button type="button" class="btn btn-danger btn-sm btn-remove-item">&times;</button></td>
            </tr>`);
        });
    }

    $('#transfer-items').on('change', '.quantity-input', function() {
        const index = $(this).closest('tr').data('index');
        let newQty = parseInt($(this).val());
        if(newQty > transferItems[index].inventory) {
            alert('Số lượng chuyển không được vượt quá tồn kho!');
            newQty = transferItems[index].inventory;
            $(this).val(newQty);
        }
        transferItems[index].quantity = newQty;
    });
    
    $('#transfer-items').on('click', '.btn-remove-item', function() {
        transferItems.splice($(this).closest('tr').data('index'), 1);
        renderItems();
    });

    $('#transfer-form').on('submit', function(e) {
        e.preventDefault();
        const data = {
            action: 'create_transfer',
            to_store_id: $('#to_store_id').val(),
            notes: $('#notes').val(),
            products: JSON.stringify(transferItems.map(item => ({id: item.id, name: item.name, quantity: item.quantity})))
        };

        if(transferItems.length === 0 || !data.to_store_id) {
            alert('Vui lòng chọn sản phẩm và kho nhận.');
            return;
        }

        const button = $(this).find('button[type="submit"]');
        button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Đang xử lý...');

        $.post('/quanlybanhang/ajax/transfers_ajax.php', data, function(response) {
            alert(response.message);
            if (response.status === 'success') { window.location.href = 'list.php'; }
        }, 'json').fail(() => alert('Có lỗi xảy ra, vui lòng thử lại.'))
        .always(() => button.prop('disabled', false).html('<i class="fas fa-save"></i> Lưu & Chuyển'));
    });
});
</script>