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

$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 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 { border: none; border-radius: 0.5rem; box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); transition: all 0.3s ease-in-out; }
    .summary-card:hover { transform: translateY(-5px); box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15); }
    .summary-card .card-body { display: flex; align-items: center; justify-content: space-between; }
    .summary-card .icon-circle { display: inline-flex; align-items: center; justify-content: center; width: 3rem; height: 3rem; border-radius: 50%; color: #fff; }
    .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.5rem; font-weight: 700; }
    #reportTable th { text-align: center; vertical-align: middle; }
    #reportTable .text-right { text-align: right !important; }
    .select2-container--bootstrap-5 .select2-selection { padding-top: 0.5rem; padding-bottom: 0.5rem; min-height: calc(1.5em + 1rem + 2px); font-size: 1rem; }
    td.details-control { cursor: pointer; }
    tr.dt-hasChild td.details-control i { transform: rotate(90deg); }
    .child-row-container { padding: 1rem; background-color: #f8f9fc; border-left: 3px solid #4e73df; }
    .child-summary { margin-bottom: 1rem; font-size: 1rem; display: flex; flex-wrap: wrap; gap: 1.5rem; }
    .child-summary span { white-space: nowrap; }
    .child-summary strong { color: #000; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Báo cáo doanh thu</h1>
    <div class="card shadow mb-4">
        <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"><option value="">Tất cả</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"><option value="">Tất cả</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"><option value="">Tất cả</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"><option value="">Tất cả</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="date" 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="date" 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 me-2"></i>Tìm</button></div>
                </div>
            </form>
        </div>
    </div>
    
    <div id="summary-cards" class="row"></div>

    <div class="card shadow mb-4">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered 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/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' });

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

    function formatChildRow(data) {
        const summary = data.summary;
        const products = data.products;
        let summaryHtml = `<div class="child-row-container">
            <div class="child-summary">
                <span><i class="fas fa-box-open text-muted"></i> Số lượng SP: <strong>${formatNumber(summary.total_quantity)}</strong></span>
                <span><i class="fas fa-file-invoice text-muted"></i> Tiền hàng: <strong>${formatNumber(summary.total_price)}</strong></span>
                <span><i class="fas fa-tags text-muted"></i> Giảm giá: <strong>${formatNumber(summary.total_discount)}</strong></span>
                <span><i class="fas fa-dollar-sign text-muted"></i> Tổng tiền: <strong>${formatNumber(summary.total_money)}</strong></span>
                <span><i class="fas fa-exclamation-circle text-muted"></i> Còn nợ: <strong class="text-danger">${formatNumber(summary.lack)}</strong></span>
            </div>`;
        let productsHtml = `<table class="table table-sm table-bordered">
            <thead class="table-light"><tr><th>STT</th><th>Mã SP</th><th>Tên sản phẩm</th><th>SL</th><th class="text-right">Giá bán</th><th class="text-right">Thành tiền</th></tr></thead>
            <tbody>`;
        if(products.length > 0){
            products.forEach((p, index) => {
                productsHtml += `<tr>
                    <td>${index + 1}</td>
                    <td>${p.code || ''}</td>
                    <td>${p.name || ''}</td>
                    <td>${formatNumber(p.quantity)}</td>
                    <td class="text-right">${formatNumber(p.price)}</td>
                    <td class="text-right">${formatNumber(p.quantity * p.price)}</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 text-primary">Số đơn / Lượng SP</div><div class="value text-gray-800">${formatNumber(totals.total_orders)} / ${formatNumber(totals.total_qty)}</div></div><div class="icon-circle bg-primary"><i class="fas fa-file-invoice-dollar fa-lg"></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 text-warning">Chiết khấu</div><div class="value text-gray-800">${formatNumber(totals.total_discount)}</div></div><div class="icon-circle bg-warning"><i class="fas fa-tags fa-lg"></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 text-success">Doanh số</div><div class="value text-gray-800">${formatNumber(totals.total_revenue)}</div></div><div class="icon-circle bg-success"><i class="fas fa-dollar-sign fa-lg"></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 text-danger">Khách nợ</div><div class="value text-gray-800">${formatNumber(totals.total_debt)}</div></div><div class="icon-circle bg-danger"><i class="fas fa-exclamation-triangle fa-lg"></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>' },
            { 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">${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 {
            icon.removeClass('fa-plus-circle text-primary').addClass('fa-spinner fa-spin');
            const rowData = row.data();
            $.ajax({
                url: '/quanlybanhang/ajax/doanhso_ajax.php',
                type: 'GET',
                data: { action: 'get_order_details', order_id: rowData.id },
                dataType: 'json',
                success: function(res) {
                    if (res.status === 'success') {
                        row.child(formatChildRow(res.data)).show();
                        tr.addClass('dt-hasChild');
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-minus-circle text-danger');
                    } else {
                        alert('Lỗi: ' + res.message);
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                    }
                },
                error: function() {
                    alert('Lỗi kết nối đến máy chủ.');
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                }
            });
        }
    });
});
</script>