<?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:1px solid #e3e6f0; border-radius:0.75rem; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; }
    .summary-card .card-body { padding:1.5rem; }
    .summary-card .value { font-size:1.75rem; font-weight:700; }
    .summary-card .label { font-size:0.8rem; font-weight:700; text-transform:uppercase; }
    .filter-card { background-color: #fff; border:1px solid #e3e6f0; border-radius:0.75rem; padding: 1.25rem; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; }
    #reportTable thead th { background-color: #4e73df !important; color: #ffffff !important; }
    
    /* === BỔ SUNG CSS CHO SELECT2 === */
    .filter-card .form-control,
    .filter-card .form-select {
        height: 38px;
        font-size: 0.9rem;
        border-radius: 0.35rem;
        border-color: #d1d3e2;
    }
    .filter-card .select2-container--bootstrap-5 .select2-selection {
        height: 38px;
        padding: 0.375rem 0.75rem;
        font-size: 0.9rem;
        border-radius: 0.35rem;
        border-color: #d1d3e2;
    }
    .filter-card .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
        line-height: 1.5;
    }
    .filter-card .select2-container--bootstrap-5 .select2-selection--single .select2-selection__arrow {
        height: 36px;
    }
    .filter-card .form-control:focus,
    .filter-card .select2-container--bootstrap-5.select2-container--focus .select2-selection {
        border-color: #4e73df;
        box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
    }
</style>

<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">Báo cáo nhập kho</h1>
        <button class="btn btn-success shadow-sm" id="btn-export-excel"><i class="fas fa-file-excel fa-sm text-white-50"></i> Xuất Excel</button>
    </div>

    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card border-left-primary"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="label text-primary">Tổng số phiếu</div><div class="value" id="summary-total-slips">0</div></div><div class="col-auto"><i class="fas fa-calendar fa-2x text-gray-300"></i></div></div></div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card border-left-info"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="label text-info">Tổng số lượng SP</div><div class="value" id="summary-total-quantity">0</div></div><div class="col-auto"><i class="fas fa-box fa-2x text-gray-300"></i></div></div></div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card border-left-success"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="label text-success">Tổng chi</div><div class="value" id="summary-total-amount">0</div></div><div class="col-auto"><i class="fas fa-dollar-sign fa-2x text-gray-300"></i></div></div></div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card border-left-danger"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="label text-danger">Tổng nợ NCC</div><div class="value" id="summary-total-debt">0</div></div><div class="col-auto"><i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i></div></div></div></div>
        </div>
    </div>

    <div class="filter-card mb-4">
        <div class="row g-2 align-items-center">
            <div class="col-12 col-md-4">
                <div class="input-group">
                    <input type="text" id="filter-from-date" class="form-control" placeholder="Từ ngày">
                    <span class="input-group-text">to</span>
                    <input type="text" id="filter-to-date" class="form-control" placeholder="Đến ngày">
                </div>
            </div>
            <div class="col-12 col-md-3">
                <select id="filter-store" class="form-select"></select>
            </div>
            <div class="col-12 col-md-3">
                <select id="filter-supplier" class="form-select"></select>
            </div>
            <div class="col-12 col-md-2">
                <button class="btn btn-primary w-100" id="btn-filter"><i class="fas fa-search me-1"></i> Lọc báo cáo</button>
            </div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="reportTable" width="100%" cellspacing="0"></table>
            </div>
        </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() {
    const AJAX_URL = '/quanlybanhang/ajax/report_imports_ajax.php';
    const fp_config = { locale: "vn", altInput: true, altFormat: "d/m/Y", dateFormat: "Y-m-d", allowInput: true };
    flatpickr("#filter-from-date", fp_config);
    flatpickr("#filter-to-date", fp_config);

    function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }

    $('#filter-store').select2({
        theme: 'bootstrap-5',
        placeholder: 'Tất cả kho',
        allowClear: true,
        ajax: {
            url: AJAX_URL,
            dataType: 'json',
            data: params => ({ action: 'get_stores', term: params.term }),
            processResults: data => ({ results: data })
        }
    });

    $('#filter-supplier').select2({
        theme: 'bootstrap-5',
        placeholder: 'Tất cả nhà cung cấp',
        allowClear: true,
        ajax: {
            url: AJAX_URL,
            dataType: 'json',
            data: params => ({ action: 'get_suppliers', term: params.term }),
            processResults: data => ({ results: data })
        }
    });
    
    var table = $('#reportTable').DataTable({
        "processing": true,
        "serverSide": true,
        "searching": false,
        "ajax": {
            "url": AJAX_URL,
            "type": "POST",
            "data": function(d) {
                d.action = 'get_report_data';
                d.from = $('#filter-from-date').val();
                d.to = $('#filter-to-date').val();
                d.store_id = $('#filter-store').val();
                d.supplier_id = $('#filter-supplier').val();
            }
        },
        "columns": [
            { "data": "stt", "title": "STT", "orderable": false },
            { "data": "input_code", "title": "Mã PN" },
            { "data": "input_date", "title": "Ngày nhập" },
            { "data": "supplier_name", "title": "Nhà cung cấp" },
            { "data": "store_name", "title": "Kho" },
            { "data": "total_quantity", "title": "SL", "className": "text-center" },
            { "data": "total_money", "title": "Tổng tiền", "className": "text-end", "render": formatNumber },
            { "data": "payed", "title": "Đã trả", "className": "text-end", "render": formatNumber },
            { "data": "lack", "title": "Còn nợ", "className": "text-end text-danger fw-bold", "render": formatNumber }
        ],
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        "order": [[2, "desc"]],
        "dom": "t<'d-flex justify-content-between align-items-center mt-3'p>",
        "drawCallback": function(settings) {
            var json = this.api().ajax.json();
            if (json && json.summary) {
                let s = json.summary;
                $('#summary-total-slips').text(formatNumber(s.total_slips));
                $('#summary-total-quantity').text(formatNumber(s.total_quantity));
                $('#summary-total-amount').text(formatNumber(s.total_amount) + ' ₫');
                $('#summary-total-debt').text(formatNumber(s.total_debt) + ' ₫');
            }
        }
    });

    $('#btn-filter').on('click', function() {
        table.ajax.reload();
    });

    $('#btn-export-excel').on('click', function() {
        const params = {
            action: 'get_report_data',
            export: 'excel',
            from: $('#filter-from-date').val(),
            to: $('#filter-to-date').val(),
            store_id: $('#filter-store').val(),
            supplier_id: $('#filter-supplier').val()
        };
        window.location.href = AJAX_URL + '?' + $.param(params);
    });
});
</script>