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

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<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" />
<style>
    .summary-card { background-color:#fff; border:none; border-radius:0.75rem; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; transition:all .2s ease-in-out; }
    .summary-card:hover { transform: translateY(-5px); }
    .summary-card .card-body { padding: 1.5rem; }
    .summary-card .label { font-size:0.8rem; font-weight:700; text-transform:uppercase; margin-bottom:0.25rem; }
    .summary-card .value { font-size:1.75rem; font-weight:700; }
    #transfers-table thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý Chuyển kho</h1>

    <div class="row">
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="label" style="color:#4e73df;">Tổng số phiếu</div>
                <div class="value text-gray-800" id="summary-total-transfers">0</div>
            </div></div>
        </div>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="label" style="color:#f6c23e;">Đang chuyển</div>
                <div class="value text-warning" id="summary-pending">0</div>
            </div></div>
        </div>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="label" style="color:#1cc88a;">Hoàn thành</div>
                <div class="value text-success" id="summary-completed">0</div>
            </div></div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">Danh sách phiếu chuyển</h6>
            <a href="create.php" class="btn btn-primary"><i class="fas fa-plus fa-sm mr-2"></i>Tạo phiếu chuyển</a>
        </div>
        <div class="card-body">
            <form id="filter-form" class="mb-4">
                <div class="row align-items-end">
                    <div class="col-md-3 mb-3"><input type="text" class="form-control" id="search_term" placeholder="Nhập mã phiếu..."></div>
                    <div class="col-md-3 mb-3">
                        <select id="status_filter" data-placeholder="-- Trạng thái --">
                            <option value=""></option>
                            <option value="0">Đang chuyển</option>
                            <option value="1">Hoàn thành</option>
                        </select>
                    </div>
                    <div class="col-md-2 mb-3"><input type="text" id="start_date" class="form-control" placeholder="Từ ngày"></div>
                    <div class="col-md-2 mb-3"><input type="text" id="end_date" class="form-control" placeholder="Đến ngày"></div>
                    <div class="col-md-2 mb-3"><button type="submit" class="btn btn-primary w-100"><i class="fas fa-search fa-sm mr-2"></i>Lọc</button></div>
                </div>
            </form>

            <table id="transfers-table" class="table table-bordered table-hover" width="100%">
                <thead>
                    <tr>
                        <th>Mã phiếu</th><th>Kho xuất</th><th>Kho nhập</th><th>Số lượng</th>
                        <th>Tình trạng</th><th>Ngày chuyển</th><th>Người chuyển</th>
                        <th>Ngày nhận</th><th>Người nhận</th><th>Hành động</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/vn.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('#status_filter').select2({ theme: "bootstrap-5", allowClear: true, minimumResultsForSearch: Infinity });
    const fp_config = { locale: "vn", altInput: true, altFormat: "d/m/Y", dateFormat: "Y-m-d" };
    flatpickr('#start_date', fp_config);
    flatpickr('#end_date', fp_config);
    
    var current_store_id = <?php echo $_SESSION['store_id'] ?? 0; ?>;

    var table = $('#transfers-table').DataTable({
        processing: true, serverSide: true,
        ajax: {
            url: '/quanlybanhang/ajax/transfers_ajax.php', type: 'POST',
            data: d => {
                d.action = 'get_transfers';
                d.search_term = $('#search_term').val();
                d.status = $('#status_filter').val();
                d.start_date = $('#start_date').val();
                d.end_date = $('#end_date').val();
            }
        },
        columns: [
            { data: 'transfer_code' }, { data: 'from_store_name' }, { data: 'to_store_name' },
            { data: 'total_quantity', className: 'text-center' },
            { data: 'transfer_status', className: 'text-center', render: data => {
                if (data == '1') return '<span class="badge bg-success">Hoàn thành</span>';
                return '<span class="badge bg-warning">Đang chuyển</span>';
            }},
            { data: 'transfer_date' }, { data: 'creator_name' },
            { data: 'received_date' }, { data: 'confirmer_name' },
            { data: 'id', className: 'text-center', orderable: false, render: (data, type, row) => {
                let buttons = `<a href="print.php?id=${data}" target="_blank" class="btn btn-info btn-sm" title="In phiếu"><i class="fas fa-print"></i></a> `;
                if (row.transfer_status == '0' && row.to_store == current_store_id) {
                    buttons += `<button class="btn btn-success btn-sm btn-confirm" data-id="${data}" title="Xác nhận đã nhận hàng"><i class="fas fa-check-circle"></i></button>`;
                }
                return buttons;
            }}
        ],
        language: { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        drawCallback: function (settings) {
            var summary = settings.json.summary;
            if (summary) {
                $('#summary-total-transfers').text(settings.json.recordsFiltered);
                $('#summary-pending').text(summary.pending);
                $('#summary-completed').text(summary.completed);
            }
        }
    });

    $('#filter-form').on('submit', e => { e.preventDefault(); table.ajax.reload(); });

    $('#transfers-table').on('click', '.btn-confirm', function() {
        var id = $(this).data('id');
        if (confirm('Bạn chắc chắn muốn xác nhận đã nhận đủ hàng cho phiếu này? Thao tác này sẽ cập nhật tồn kho và không thể hoàn tác.')) {
            $.post('/quanlybanhang/ajax/transfers_ajax.php', { action: 'confirm_transfer', id: id }, res => {
                alert(res.message);
                if(res.status === 'success') table.ajax.reload();
            }, 'json');
        }
    });
});
</script>