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

// PHẦN 1: LẤY DỮ LIỆU BỘ LỌC VÀ XÁC THỰC QUYỀN (giữ nguyên)
$logged_in_user_id = $_SESSION['user_id'] ?? 0;
$logged_in_group_id = 0;
if ($logged_in_user_id > 0) {
    $stmt_user = $conn->prepare("SELECT group_id FROM cms_users WHERE id = ?");
    $stmt_user->bind_param('i', $logged_in_user_id);
    $stmt_user->execute();
    $user_result = $stmt_user->get_result()->fetch_assoc();
    if ($user_result) { $logged_in_group_id = $user_result['group_id']; }
    $stmt_user->close();
}
$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);
$group_by = $_GET['group_by'] ?? 'employee';
if ($logged_in_group_id != 1 && $group_by === 'employee') { $group_by = 'order'; }
$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);

// PHẦN 2: TRUY VẤN DỮ LIỆU (giữ nguyên logic)
$whereClauses = ["o.deleted = 0", "o.order_status > 0"];
$params = [];
$types = '';
if ($logged_in_group_id != 1) {
    $whereClauses[] = "o.user_init = ?";
    $params[] = $logged_in_user_id;
    $types .= 'i';
}
$whereClauses[] = "o.sell_date BETWEEN ? AND ?";
$params[] = $from_date . ' 00:00:00';
$params[] = $to_date . ' 23:59:59';
$types .= 'ss';
if ($customer_id > 0) { $whereClauses[] = "o.customer_id = ?"; $params[] = $customer_id; $types .= 'i'; }
if ($store_id > 0) { $whereClauses[] = "o.store_id = ?"; $params[] = $store_id; $types .= 'i'; }
if ($logged_in_group_id == 1 && $user_id_from_get !== '' && is_numeric($user_id_from_get)) {
    $whereClauses[] = "o.user_init = ?";
    $params[] = intval($user_id_from_get);
    $types .= 'i';
}
$orderWhereSql = " WHERE " . implode(' AND ', $whereClauses);
function refValues($arr){ $refs = []; foreach($arr as $key => $value) $refs[$key] = &$arr[$key]; return $refs; }
function bind_dynamic_params($stmt, $types, $params) { if (empty($types) || empty($params)) return; call_user_func_array([$stmt, 'bind_param'], refValues(array_merge([$types], $params)));}

$total_revenue_card = 0; $total_cost_card = 0; $gross_profit_card = 0;
$sql_summary = "SELECT SUM(total_money) as total_revenue, SUM(total_origin_price) as total_cost FROM cms_orders o" . $orderWhereSql;
$stmt_summary = $conn->prepare($sql_summary);
if ($stmt_summary) {
    bind_dynamic_params($stmt_summary, $types, $params);
    $stmt_summary->execute();
    $summary_result = $stmt_summary->get_result()->fetch_assoc();
    $total_revenue_card = $summary_result['total_revenue'] ?? 0;
    $total_cost_card = $summary_result['total_cost'] ?? 0;
    $gross_profit_card = $total_revenue_card - $total_cost_card;
    $stmt_summary->close();
}
$report_data = []; $table_headers = []; $sql_report = '';
switch ($group_by) {
    case 'customer':
        $table_headers = ['Tên khách hàng', 'Tổng số đơn', 'Doanh số', 'Tiền vốn', 'Lợi nhuận'];
        $sql_report = "SELECT c.ID as customer_id, c.customer_name as group_name, COUNT(o.id) as order_count, SUM(o.total_money) as revenue, SUM(o.total_origin_price) as cost, (SUM(o.total_money) - SUM(o.total_origin_price)) as profit FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID" . $orderWhereSql . " GROUP BY c.ID, c.customer_name ORDER BY profit DESC";
        break;
    case 'order':
        $table_headers = ['', 'Mã đơn hàng', 'Khách hàng', 'Doanh số', 'Tiền vốn', 'Lợi nhuận'];
        $sql_report = "SELECT o.id as order_id, o.output_code as group_name, c.ID as customer_id, c.customer_name, o.total_money as revenue, o.total_origin_price as cost, (o.total_money - o.total_origin_price) as profit FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID" . $orderWhereSql . " ORDER BY o.id DESC";
        break;
    case 'employee': default:
        $table_headers = ['Tên nhân viên', 'Tổng số đơn', 'Doanh số', 'Tiền vốn', 'Lợi nhuận'];
        $sql_report = "SELECT u.display_name as group_name, COUNT(o.id) as order_count, SUM(o.total_money) as revenue, SUM(o.total_origin_price) as cost, (SUM(o.total_money) - SUM(o.total_origin_price)) as profit FROM cms_orders o LEFT JOIN cms_users u ON o.user_init = u.id" . $orderWhereSql . " GROUP BY u.display_name ORDER BY profit DESC";
        break;
}
if (!empty($sql_report)) {
    $stmt_report = $conn->prepare($sql_report);
    if($stmt_report) {
        bind_dynamic_params($stmt_report, $types, $params);
        $stmt_report->execute();
        $report_data = $stmt_report->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt_report->close();
    }
}
$total_orders_sum = 0; $total_revenue_sum = 0; $total_cost_sum = 0; $total_profit_sum = 0;
if (!empty($report_data)) {
    if ($group_by != 'order') { $total_orders_sum = array_sum(array_column($report_data, 'order_count')); }
    $total_revenue_sum = array_sum(array_column($report_data, 'revenue'));
    $total_cost_sum = array_sum(array_column($report_data, 'cost'));
    $total_profit_sum = array_sum(array_column($report_data, 'profit'));
}
?>

<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-profit { 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-profit:hover { transform: translateY(-5px); }
    .summary-card-profit .card-body { padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; }
    .summary-card-profit .text-content .label { font-size:0.8rem; font-weight:700; text-transform:uppercase; margin-bottom:0.25rem; }
    .summary-card-profit .text-content .value { font-size:1.75rem; font-weight:700; }
    .summary-card-profit .icon-circle { width:50px; height:50px; border-radius:50%; display:flex; align-items:center; justify-content:center; color:white; font-size:1.5rem; }
    .filter-title { font-size: 1.1rem; font-weight: 600; color: #4e73df; margin-bottom: 1rem; }
    .btn-group-toggle .btn { font-weight: 500; }
    .select2-container--bootstrap-5 .select2-dropdown .select2-results__option--highlighted { background-color: #4e73df; color: white; }
    .select2-container--bootstrap-5 .select2-dropdown .select2-results__option { font-size: 1rem; padding: .6rem .75rem; }
    #dataTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    .details-control { cursor: pointer; width: 25px; }
    tr.dt-hasChild .details-control i { transform: rotate(90deg); }
    #dataTable tbody tr { border-bottom: 1px solid #e3e6f0; }
    #dataTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #dataTable tbody tr:hover { background-color: #eaecf4; }
    .total-row { background-color: #f1f3f8 !important; font-size: 1.1rem !important; }
    .total-row td { font-weight: bold; }
    .profit-cell { background-color: #e7f5ec; color: #155724; font-weight: bold !important; }
    .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; }
    #dataTable .table-sm > thead { background-color:#4e73df; color:white; border-color:#4e73df; }
    #dataTable .table-sm > thead th { font-weight:600; }
    #dataTable .table-sm > tbody > tr:hover { background-color:#eaecf4; }
    #dataTable .table-sm > tbody td:last-child { font-weight:700; color:#2e59d9; }
</style>

<div class="container-fluid">
   <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 lợi nhuận gộp</h1>
        <a href="net_profit_report.php" class="btn btn-lg btn-success shadow-sm"><i class="fas fa-chart-pie fa-sm text-white-50"></i> Báo cáo lợi nhuận ròng</a>
    </div>
    
    <div class="row">
        <div class="col-xl-4 col-md-6 mb-4"><div class="card summary-card-profit"><div class="card-body"><div class="text-content"><div class="label" style="color:#36b9cc;">Doanh số</div><div class="value text-gray-800"><?php echo number_format($total_revenue_card); ?></div></div><div class="icon-circle" style="background-color:#36b9cc;"><i class="fas fa-chart-line"></i></div></div></div></div>
        <div class="col-xl-4 col-md-6 mb-4"><div class="card summary-card-profit"><div class="card-body"><div class="text-content"><div class="label" style="color:#f6c23e;">Tiền vốn</div><div class="value text-gray-800"><?php echo number_format($total_cost_card); ?></div></div><div class="icon-circle" style="background-color:#f6c23e;"><i class="fas fa-cubes"></i></div></div></div></div>
        <div class="col-xl-4 col-md-6 mb-4"><div class="card summary-card-profit"><div class="card-body"><div class="text-content"><div class="label" style="color:#1cc88a;">Lợi nhuận</div><div class="value font-weight-bold" style="color:#1cc88a;"><?php echo number_format($gross_profit_card); ?></div></div><div class="icon-circle" style="background-color:#1cc88a;"><i class="fas fa-wallet"></i></div></div></div></div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-body">
            <form method="GET">
                <div class="filter-title">Thống kê lợi nhuận theo:</div>
                <div class="btn-group btn-group-toggle mb-4" data-toggle="buttons">
                    <?php if ($logged_in_group_id == 1): ?><label class="btn btn-outline-primary <?php echo ($group_by == 'employee') ? 'active' : ''; ?>"><input type="radio" name="group_by" value="employee" <?php echo ($group_by == 'employee') ? 'checked' : ''; ?>> Nhân viên</label><?php endif; ?>
                    <label class="btn btn-outline-primary <?php echo ($group_by == 'customer') ? 'active' : ''; ?>"><input type="radio" name="group_by" value="customer" <?php echo ($group_by == 'customer') ? 'checked' : ''; ?>> Khách hàng</label>
                    <label class="btn btn-outline-primary <?php echo ($group_by == 'order') ? 'active' : ''; ?>"><input type="radio" name="group_by" value="order" <?php echo ($group_by == 'order') ? 'checked' : ''; ?>> Đơn hàng</label>
                </div>
                <div class="row align-items-end">
                    <div class="col-md-2 mb-3"><select class="form-control" name="customer_id" data-placeholder="-- Khách hàng --"><option value=""></option><?php foreach($customers as $c) { echo "<option value='{$c['ID']}' ".($customer_id == $c['ID'] ? 'selected' : '').">".htmlspecialchars($c['customer_name'])."</option>"; } ?></select></div>
                    <?php if ($logged_in_group_id == 1): ?><div class="col-md-2 mb-3"><select class="form-control" name="user_id" data-placeholder="-- NV bán hàng --"><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><?php endif; ?>
                    <div class="col-md-2 mb-3"><select class="form-control" name="store_id" data-placeholder="-- Cửa hàng --"><option value=""></option><?php foreach($stores as $s) { echo "<option value='{$s['id']}' ".($store_id == $s['id'] ? 'selected' : '').">".htmlspecialchars($s['store_name'])."</option>"; } ?></select></div>
                    <div class="col-md-2 mb-3"><input type="text" class="form-control" name="from" placeholder="Từ ngày" value="<?php echo htmlspecialchars($from_date); ?>"></div>
                    <div class="col-md-2 mb-3"><input type="text" class="form-control" name="to" placeholder="Đến ngày" value="<?php echo htmlspecialchars($to_date); ?>"></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>Tìm kiế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-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <?php
                            $header_alignments = [];
                            if ($group_by == 'order') {
                                $header_alignments = ['text-center', 'text-left', 'text-left', 'text-right', 'text-right', 'text-right'];
                            } else {
                                $header_alignments = ['text-left', 'text-center', 'text-right', 'text-right', 'text-right'];
                            }
                            foreach ($table_headers as $index => $header):
                                $align_class = $header_alignments[$index] ?? 'text-left';
                            ?>
                                <th class="text-nowrap <?php echo $align_class; ?>"><?php echo $header; ?></th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($report_data)): ?>
                            <tr><td colspan="<?php echo count($table_headers); ?>" class="text-center">Không có dữ liệu.</td></tr>
                        <?php else: ?>
                            <tr class="total-row">
                                <?php if ($group_by == 'order'): ?>
                                    <td></td>
                                    <td class="text-left" colspan="2">TỔNG CỘNG</td>
                                    <td class="text-right"><?php echo number_format($total_revenue_sum); ?></td>
                                    <td class="text-right"><?php echo number_format($total_cost_sum); ?></td>
                                    <td class="text-right text-success"><?php echo number_format($total_profit_sum); ?></td>
                                <?php else: ?>
                                    <td class="text-left">TỔNG CỘNG</td>
                                    <td class="text-center"><?php echo number_format($total_orders_sum); ?></td>
                                    <td class="text-right"><?php echo number_format($total_revenue_sum); ?></td>
                                    <td class="text-right"><?php echo number_format($total_cost_sum); ?></td>
                                    <td class="text-right text-success"><?php echo number_format($total_profit_sum); ?></td>
                                <?php endif; ?>
                            </tr>
                            <?php foreach($report_data as $row): ?>
                                <tr data-order-id="<?php echo $row['order_id'] ?? ''; ?>">
                                    <?php if ($group_by == 'order'): ?>
                                        <td class="details-control text-center"><i class="fas fa-plus-circle text-primary"></i></td>
                                    <?php endif; ?>
                                    <td class="text-left">
                                        <?php if ($group_by == 'customer' && !empty($row['customer_id'])): ?>
                                            <a href="/quanlybanhang/modules/customers/chi_tiet_khach_hang.php?id=<?php echo $row['customer_id']; ?>"><?php echo htmlspecialchars($row['group_name']); ?></a>
                                        <?php else: echo htmlspecialchars($row['group_name']); endif; ?>
                                    </td>
                                    <?php if ($group_by == 'order'): ?>
                                        <td class="text-left">
                                            <?php if (!empty($row['customer_id'])): ?>
                                                <a href="/quanlybanhang/modules/customers/chi_tiet_khach_hang.php?id=<?php echo $row['customer_id']; ?>"><?php echo htmlspecialchars($row['customer_name'] ?? 'N/A'); ?></a>
                                            <?php else: echo htmlspecialchars($row['customer_name'] ?? 'N/A'); endif; ?>
                                        </td>
                                    <?php else: ?>
                                        <td class="text-center"><?php echo number_format($row['order_count']); ?></td>
                                    <?php endif; ?>
                                    <td class="text-right"><?php echo number_format($row['revenue']); ?></td>
                                    <td class="text-right text-muted"><?php echo number_format($row['cost']); ?></td>
                                    <td class="text-right profit-cell"><?php echo number_format($row['profit']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </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() {
    // Kích hoạt các thư viện
    $('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; ?>" });
    
    // Tự động submit form khi đổi chế độ xem
    $('input[name="group_by"]').on('change', function() { $(this).closest('form').submit(); });

    // Hàm tạo giao diện chi tiết đơn hàng
    function formatDetails(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-bordered"><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((item, index) => {
                let lineTotal = (item.quantity || 0) * (item.price || 0);
                productsHtml += `<tr><td>${index + 1}</td><td>${item.code || 'N/A'}</td><td>${item.name || 'N/A'}</td><td>${formatVNCurrency(item.quantity)}</td><td>${formatVNCurrency(item.price)}</td><td>${formatVNCurrency(lineTotal)}</td></tr>`;
            });
        } else {
            productsHtml += `<tr><td colspan="6" class="text-center">Đơn hàng không có sản phẩm.</td></tr>`;
        }
        productsHtml += '</tbody></table></div>';
        return summaryHtml + productsHtml;
    }

    // === SCRIPT MỚI: XỬ LÝ CLICK MỞ/ĐÓNG CHI TIẾT ĐƠN HÀNG ===
    $('#dataTable tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var icon = $(this).find('i');
        var orderId = tr.data('order-id');
        var colCount = tr.prop('cells').length;

        // Kiểm tra xem dòng đang click có đang mở hay không
        var is_open = tr.next().hasClass('child-row');

        // Luôn đóng tất cả các dòng chi tiết khác trước
        $('#dataTable tbody tr.child-row').remove();
        $('#dataTable tbody td.details-control i').removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');
        
        // Nếu là hành động đóng, thì chỉ cần dừng lại ở đây
        if (is_open) {
            return;
        }
        
        // Nếu là hành động mở
        if (!orderId) return;

        icon.removeClass('fa-plus-circle text-primary').addClass('fa-spinner fa-spin');
        
        var loadingRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center">Đang tải chi tiết...</div></td></tr>');
        tr.after(loadingRow);
        
        $.ajax({
            url: '/quanlybanhang/ajax/orders_ajax.php',
            type: 'POST',
            dataType: 'json',
            data: { action: 'get_order_details', order_id: orderId },
            success: function(response) {
                loadingRow.remove();
                if (response.status === 'success') {
                    var detailHtml = formatDetails(response);
                    var detailRow = $('<tr class="child-row"><td colspan="' + colCount + '">' + detailHtml + '</td></tr>');
                    tr.after(detailRow);
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-minus-circle text-danger');
                } else {
                    var errorRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center text-danger">Lỗi: ' + response.message + '</div></td></tr>');
                    tr.after(errorRow);
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                }
            },
            error: function() {
                loadingRow.remove();
                var errorRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center text-danger">Lỗi kết nối.</div></td></tr>');
                tr.after(errorRow);
                icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
            }
        });
    });
});
</script>