<?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_result = $conn->query("SELECT id, store_name FROM cms_stores WHERE id != " . intval($current_store_id));
$stores = $stores_result ? $stores_result->fetch_all(MYSQLI_ASSOC) : [];
$current_store_name_result = $conn->query("SELECT store_name FROM cms_stores WHERE id = " . intval($current_store_id));
$current_store_name = $current_store_name_result ? $current_store_name_result->fetch_assoc()['store_name'] : 'Kho không xác định';
?>
<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"><a href="list.php" class="text-dark me-2" title="Quay lại"><i class="fas fa-arrow-left"></i></a> Tạo Phiếu Chuyển Kho</h1>
    </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..."></select>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead class="table-light">
                                    <tr>
                                        <th>Tên sản phẩm</th>
                                        <th class="text-center">Tồn kho</th>
                                        <th style="width: 120px;" class="text-center">Số lượng</th>
                                        <th style="width: 50px;"></th>
                                    </tr>
                                </thead>
                                <tbody id="transfer-items">
                                    <tr><td colspan="4" class="text-center p-5 text-muted">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 phiếu</h6></div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Từ kho:</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($current_store_name); ?>" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="to_store_id" class="form-label fw-bold">Chuyển đến kho:</label>
                            <select id="to_store_id" class="form-select" data-placeholder="-- Chọn kho nhận --" required>
                                <option></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="mb-3">
                            <label for="receiver_id" class="form-label fw-bold">Người nhận:</label>
                            <select id="receiver_id" class="form-select" data-placeholder="-- Chọn người nhận --" disabled required></select>
                        </div>
                        <div class="mb-3">
                            <label for="notes" class="form-label fw-bold">Ghi chú:</label>
                            <textarea id="notes" class="form-control" rows="5"></textarea>
                        </div>
                    </div>
                    <div class="card-footer text-right">
                         <a href="list.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 & 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 = [];

    // SỬA LẠI: Thêm width: '100%' để kéo dài các ô dropdown
    $('#to_store_id, #receiver_id').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });
    
    $('#product-search').select2({
        theme: 'bootstrap-5',
        width: '100%',
        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 }))})
        }
    });

    $('#to_store_id').on('change', function() {
        const storeId = $(this).val();
        const receiverSelect = $('#receiver_id');
        
        receiverSelect.empty().val(null).trigger('change');

        if (storeId) {
            receiverSelect.prop('disabled', false).select2({
                theme: 'bootstrap-5',
                width: '100%', // Thêm width ở đây
                ajax: {
                    url: '/quanlybanhang/ajax/transfers_ajax.php',
                    dataType: 'json',
                    data: params => ({ action: 'get_users_by_store', store_id: storeId, term: params.term }),
                    processResults: data => ({ results: data })
                }
            });
        } else {
            receiverSelect.prop('disabled', true);
        }
    });

    $('#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, code: product.prd_code, inventory: product.inventory, quantity: 1});
            renderItems();
        }
        $(this).val(null).trigger('change');
    });

    function renderItems() {
        const tbody = $('#transfer-items');
        tbody.empty();
        if (transferItems.length === 0) {
            tbody.html('<tr><td colspan="4" class="text-center p-5 text-muted">Chưa có sản phẩm</td></tr>');
            return;
        }
        transferItems.forEach((item, index) => {
            tbody.append(`<tr data-index="${index}">
                <td><div class="fw-bold">${item.name}</div><div class="small text-muted">Mã: ${item.code}</div></td>
                <td class="text-center align-middle">${item.inventory}</td>
                <td class="align-middle"><input type="number" class="form-control quantity-input" value="${item.quantity}" min="1" max="${item.inventory}"></td>
                <td class="text-center align-middle"><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 > 0 ? newQty : 1;
    });
    
    $('#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(),
            receiver_id: $('#receiver_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 || !data.receiver_id) {
            alert('Vui lòng chọn sản phẩm, kho nhận và người 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, res => {
            alert(res.message);
            if (res.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 me-2"></i> Lưu & Chuyển'));
    });
});
</script>