<?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: #1cc88a !important; color: #ffffff !important; }
</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 xuất đơn hàng</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ố đơn</div><div class="value" id="summary-total-orders">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 doanh thu</div><div class="value" id="summary-total-revenue">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-warning"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="label text-warning">Tổng lợi nhuận</div><div class="value" id="summary-total-profit">0</div></div><div class="col-auto"><i class="fas fa-chart-line 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-customer" 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_orders_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-customer').select2({
        theme: 'bootstrap-5',
        placeholder: 'Tất cả khách hàng',
        allowClear: true,
        ajax: {
            url: AJAX_URL,
            dataType: 'json',
            data: params => ({ action: 'get_customers', 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.customer_id = $('#filter-customer').val();
            }
        },
        "columns": [
            { "data": "stt", "title": "STT", "orderable": false },
            { "data": "output_code", "title": "Mã ĐH" },
            { "data": "sell_date", "title": "Ngày bán" },
            { "data": "customer_name", "title": "Khách hàng" },
            { "data": "store_name", "title": "Kho" },
            { "data": "total_quantity", "title": "SL", "className": "text-center" },
            { "data": "total_money", "title": "Doanh thu", "className": "text-end", "render": formatNumber },
            { "data": "total_origin_price", "title": "Vốn", "className": "text-end", "render": formatNumber },
            { "data": "profit", "title": "Lợi nhuận", "className": "text-end 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'<'#summary-info.py-2 fw-bold'>p>",
        "drawCallback": function(settings) {
            var json = this.api().ajax.json();
            if (json && json.summary) {
                let s = json.summary;
                $('#summary-total-orders').text(formatNumber(s.total_orders));
                $('#summary-total-quantity').text(formatNumber(s.total_quantity));
                $('#summary-total-revenue').text(formatNumber(s.total_revenue) + ' ₫');
                $('#summary-total-profit').text(formatNumber(s.total_profit) + ' ₫');
            }
        }
    });

    $('#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(),
            customer_id: $('#filter-customer').val()
        };
        const queryString = $.param(params);
        window.location.href = AJAX_URL + '?' + queryString;
    });
});
</script>