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

// --- PHP LOGIC (Giữ nguyên) ---
$customers = $conn->query("SELECT ID, customer_name FROM cms_customers ORDER BY customer_name ASC")->fetch_all(MYSQLI_ASSOC);
$users = $conn->query("SELECT id, display_name FROM cms_users WHERE user_status = 1 ORDER BY display_name ASC")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT id, store_name FROM cms_stores ORDER BY store_name ASC")->fetch_all(MYSQLI_ASSOC);

$from_date = $_GET['from'] ?? date('Y-m-01');
$to_date = $_GET['to'] ?? date('Y-m-d');
$customer_id = intval($_GET['customer_id'] ?? 0);
$user_id_from_get = $_GET['user_id'] ?? '';
$store_id = intval($_GET['store_id'] ?? 0);
$logged_in_group_id = $_SESSION['group_id'] ?? 0;
?>

<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; transition:all .2s ease-in-out; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; }
    .summary-card:hover { transform: translateY(-5px); }
    .summary-card .card-body { padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; }
    .summary-card .text-content .label { font-size:0.8rem; font-weight:700; text-transform:uppercase; margin-bottom:0.25rem; }
    .summary-card .text-content .value { font-size:1.75rem; font-weight:700; color:#3a3b45; }
    .summary-card .icon-circle { width:50px; height:50px; border-radius:50%; display:flex; align-items:center; justify-content:center; color:white; font-size:1.5rem; }
    .filter-card { border-left:4px solid #4e73df; }
    .select2-container--bootstrap-5 .select2-dropdown .select2-results__option--highlighted { background-color: #4e73df; color: white; }
    .flatpickr-calendar { font-family:"Nunito",sans-serif; box-shadow:0 0.5rem 1rem rgba(0,0,0,0.15); border-radius:0.5rem; }
    .flatpickr-day.selected { background:#4e73df; border-color:#4e73df; }
    input.form-control[readonly] { background-color:#fff !important; cursor:pointer; }
    #reportTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #reportTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #reportTable tbody tr:hover { background-color: #eaecf4; }
    .details-control { cursor: pointer; width: 25px; }
    .child-row-container { padding:1rem; background-color:#f8f9fc; border-left:3px solid #4e73df; margin:5px 0; }
    .child-summary { margin-bottom:1rem; display:flex; flex-wrap:wrap; gap:8px; }
    .child-summary span { padding:6px 12px; border-radius:16px; color:white; font-size:.9em; font-weight:500; display:inline-flex; align-items:center; box-shadow:0 2px 4px rgba(0,0,0,.1); white-space:nowrap; }
    .child-summary strong { color:white; margin-left:4px; }
    .child-summary span:nth-child(1) { background-color:#4e73df; }
    .child-summary span:nth-child(2) { background-color:#1cc88a; }
    .child-summary span:nth-child(3) { background-color:#f6c23e; }
    .child-summary span:nth-child(4) { background-color:#36b9cc; }
    .child-summary span:nth-child(5) { background-color:#e74a3b; }
    #reportTable .table-sm > thead { background-color:#4e73df; color:white; border-color:#4e73df; }
    #reportTable .table-sm > thead th { font-weight:600; }
    #reportTable .table-sm > tbody > tr:hover { background-color:#eaecf4; }
    #reportTable .table-sm > tbody td:last-child { font-weight:700; color:#2e59d9; }
    tr.dt-child > td { padding: 0 !important; }
    /* SỬA LỖI CANH LỀ BẢNG CHI TIẾT TRONG BÁO CÁO DOANH THU */
#reportTable .table-sm th, 
#reportTable .table-sm td {
    vertical-align: middle;
}

#reportTable .table-sm th:nth-child(1),
#reportTable .table-sm td:nth-child(1) {
    text-align: center;
}

#reportTable .table-sm th:nth-child(4),
#reportTable .table-sm td:nth-child(4),
#reportTable .table-sm th:nth-child(5),
#reportTable .table-sm td:nth-child(5),
#reportTable .table-sm th:nth-child(6),
#reportTable .table-sm td:nth-child(6) {
    text-align: right;
}
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Báo cáo doanh thu</h1>
    <div id="summary-cards" class="row mb-4"></div>
    <div class="card shadow mb-4 filter-card">
        <div class="card-header py-3"><h6 class="m-0 font-weight-bold"><i class="fas fa-filter mr-2"></i>Bộ lọc và Tìm kiếm</h6></div>
        <div class="card-body">
            <form id="filter-form">
                <div class="row g-3 mb-3">
                    <div class="col-md-4"><label class="form-label">Khách hàng</label><select class="form-control" name="customer_id" data-placeholder="Tất cả khách hàng"><option value=""></option><?php foreach($customers as $c) { echo "<option value='{$c['ID']}' ".($c['ID'] == $customer_id ? 'selected' : '').">".htmlspecialchars($c['customer_name'])."</option>"; } ?></select></div>
                    <?php if ($logged_in_group_id == 1): ?>
                    <div class="col-md-4"><label class="form-label">Thu ngân</label><select class="form-control" name="user_id" data-placeholder="Tất cả thu ngân"><option value=""></option><?php foreach($users as $u) { echo "<option value='{$u['id']}' ".($u['id'] == $user_id_from_get ? 'selected' : '').">".htmlspecialchars($u['display_name'])."</option>"; } ?></select></div>
                    <div class="col-md-4"><label class="form-label">Kho</label><select class="form-control" name="store_id" data-placeholder="Tất cả các kho"><option value=""></option><?php foreach($stores as $s) { echo "<option value='{$s['id']}' ".($s['id'] == $store_id ? 'selected' : '').">".htmlspecialchars($s['store_name'])."</option>"; } ?></select></div>
                    <?php else: ?>
                    <div class="col-md-8"><label class="form-label">Kho</label><select class="form-control" name="store_id" data-placeholder="Tất cả các kho"><option value=""></option><?php foreach($stores as $s) { echo "<option value='{$s['id']}' ".($s['id'] == $store_id ? 'selected' : '').">".htmlspecialchars($s['store_name'])."</option>"; } ?></select></div>
                    <?php endif; ?>
                </div>
                <div class="row g-3 align-items-end">
                    <div class="col-md-4"><label class="form-label">Từ ngày</label><input type="text" class="form-control" name="from" value="<?php echo htmlspecialchars($from_date); ?>"></div>
                    <div class="col-md-4"><label class="form-label">Đến ngày</label><input type="text" class="form-control" name="to" value="<?php echo htmlspecialchars($to_date); ?>"></div>
                    <div class="col-md-4 d-grid"><button type="submit" class="btn btn-primary"><i class="fas fa-search fa-sm mr-2"></i>Tìm</button></div>
                </div>
            </form>
        </div>
    </div>
    <div class="card shadow mb-4">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" 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() {
    $('select[name="customer_id"], select[name="user_id"], select[name="store_id"]').select2({ theme: "bootstrap-5", allowClear: true });
    const fp_config = { locale: "vn", altInput: true, altFormat: "d/m/Y", dateFormat: "Y-m-d" };
    flatpickr('input[name="from"]', { ...fp_config, defaultDate: "<?php echo $from_date; ?>" });
    flatpickr('input[name="to"]', { ...fp_config, defaultDate: "<?php echo $to_date; ?>" });

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

    // SỬA LỖI 1: Cập nhật hàm formatChildRow để đọc dữ liệu từ response của orders_ajax.php
    function formatChildRow(response) {
        const order = response.order;
        const items = response.items;
        if (!order || !items) return '<div class="p-3 text-center text-muted">Không có dữ liệu chi tiết.</div>';
        
        const totalDiscount = (parseFloat(order.total_discount) || 0) + (parseFloat(order.discount_item) || 0);
        const formatVNCurrency = (num) => (num || 0).toLocaleString('vi-VN');

        let summaryHtml = `<div class="child-row-container"><div class="child-summary"><span>Số lượng SP: <strong>${formatVNCurrency(order.total_quantity)}</strong></span><span>Tiền hàng: <strong>${formatVNCurrency(order.total_price)}</strong></span><span>Giảm giá: <strong>${formatVNCurrency(totalDiscount)}</strong></span><span>Tổng tiền: <strong>${formatVNCurrency(order.total_money)}</strong></span><span>Còn nợ: <strong>${formatVNCurrency(order.lack)}</strong></span></div>`;
        let productsHtml = `<table class="table table-sm table-hover"><thead><tr><th>STT</th><th>Mã SP</th><th>Tên sản phẩm</th><th>SL</th><th>Đơn giá</th><th>Thành tiền</th></tr></thead><tbody>`;
        if(items.length > 0){
            items.forEach((p, index) => {
                let lineTotal = (p.quantity || 0) * (p.price || 0);
                productsHtml += `<tr><td>${index + 1}</td><td>${p.code || 'N/A'}</td><td>${p.name || 'N/A'}</td><td class="text-right">${formatNumber(p.quantity)}</td><td class="text-right">${formatNumber(p.price)}</td><td class="text-right">${formatNumber(lineTotal)}</td></tr>`;
            });
        } else {
            productsHtml += `<tr><td colspan="6" class="text-center">Không có chi tiết sản phẩm.</td></tr>`;
        }
        productsHtml += '</tbody></table></div>';
        return summaryHtml + productsHtml;
    }

    let table = $('#reportTable').DataTable({
        processing: true, serverSide: true,
        ajax: {
            url: '/quanlybanhang/ajax/doanhso_ajax.php', type: 'GET',
            data: function(d) {
                d.action = 'get_revenue_data';
                $('#filter-form').serializeArray().forEach(item => { d[item.name] = item.value; });
            },
            dataSrc: function(json) {
                const totals = json.totals;
                const summaryHtml = `
                    <div class="col-xl-3 col-md-6 mb-4"><div class="card summary-card"><div class="card-body"><div class="text-content"><div class="label" style="color:#4e73df;">Số đơn / Lượng SP</div><div class="value">${formatNumber(totals.total_orders)} / ${formatNumber(totals.total_qty)}</div></div><div class="icon-circle" style="background-color:#4e73df;"><i class="fas fa-file-invoice-dollar"></i></div></div></div></div>
                    <div class="col-xl-3 col-md-6 mb-4"><div class="card summary-card"><div class="card-body"><div class="text-content"><div class="label" style="color:#f6c23e;">Chiết khấu</div><div class="value">${formatNumber(totals.total_discount)}</div></div><div class="icon-circle" style="background-color:#f6c23e;"><i class="fas fa-tags"></i></div></div></div></div>
                    <div class="col-xl-3 col-md-6 mb-4"><div class="card summary-card"><div class="card-body"><div class="text-content"><div class="label" style="color:#1cc88a;">Doanh số</div><div class="value">${formatNumber(totals.total_revenue)}</div></div><div class="icon-circle" style="background-color:#1cc88a;"><i class="fas fa-dollar-sign"></i></div></div></div></div>
                    <div class="col-xl-3 col-md-6 mb-4"><div class="card summary-card"><div class="card-body"><div class="text-content"><div class="label" style="color:#e74a3b;">Khách nợ</div><div class="value">${formatNumber(totals.total_debt)}</div></div><div class="icon-circle" style="background-color:#e74a3b;"><i class="fas fa-exclamation-triangle"></i></div></div></div></div>`;
                $('#summary-cards').html(summaryHtml);
                return json.data;
            }
        },
        columns: [
            { className: 'details-control text-center', orderable: false, data: null, defaultContent: '<i class="fas fa-plus-circle text-primary"></i>', title:'' },
            { data: "output_code", title: "Mã đơn hàng", render: (data, type, row) => `<a href="/quanlybanhang/modules/pos/pos.php?edit_order_id=${row.id}" target="_blank" class="fw-bold">${data}</a>`},
            { data: "warehouse", title: "Kho xuất" },
            { data: "sell_date", title: "Ngày bán" },
            { data: "cashier", title: "Thu ngân" },
            { data: "customer_name", title: "Khách hàng" },
            { data: "total_quantity", title: "SL", className: 'text-center' },
            { data: "discount_amount", title: "Chiết khấu", className: 'text-right' },
            { data: "total_money", title: "Tổng tiền", className: 'text-right fw-bold text-success' },
            { data: "lack", title: "Nợ", className: 'text-right fw-bold text-danger' }
        ],
        columnDefs: [ { targets: [6, 7, 8, 9], render: (data) => formatNumber(data) } ],
        order: [[3, "desc"]], pageLength: 25,
        language: { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
    });
    
    $('#filter-form').on('submit', function(e) { e.preventDefault(); table.ajax.reload(); });

    $('#reportTable tbody').on('click', 'td.details-control', function() {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        var icon = $(this).find('i');
        
        if (row.child.isShown()) {
            row.child.hide();
            tr.removeClass('dt-hasChild');
            icon.removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');
        } else {
            table.rows().every(function(){
                if(this.child.isShown()){
                    this.child.hide();
                    $(this.node()).removeClass('dt-hasChild');
                    $(this.node()).find('td.details-control i').removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');
                }
            });

            icon.removeClass('fa-plus-circle text-primary').addClass('fa-spinner fa-spin');
            const rowData = row.data();

            // SỬA LỖI 2: Thay đổi AJAX call để gọi đến file orders_ajax.php ổn định
            $.ajax({
                url: '/quanlybanhang/ajax/orders_ajax.php',
                type: 'POST', // orders_ajax dùng phương thức POST
                dataType: 'json',
                data: { action: 'get_order_details', order_id: rowData.id },
                success: function(res) {
                    if (res.status === 'success') {
                        row.child(formatChildRow(res), 'dt-child').show(); // Truyền vào cả object res
                        tr.addClass('dt-hasChild');
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-minus-circle text-danger');
                    } else {
                        row.child('<div class="p-3 text-center text-danger">Lỗi: ' + res.message + '</div>').show();
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                    }
                },
                error: function() {
                    row.child('<div class="p-3 text-center text-danger">Lỗi kết nối đến máy chủ.</div>').show();
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                }
            });
        }
    });
});
</script>