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

// =================================================================
// PHẦN 1: LẤY DỮ LIỆU BỘ LỌC VÀ CÁC THAM SỐ
// =================================================================
$customers = $conn->query("SELECT ID, customer_name FROM cms_customers ORDER BY customer_name ASC")->fetch_all(MYSQLI_ASSOC);
$users = $conn->query("SELECT id, username FROM cms_users WHERE user_status = 1 ORDER BY username ASC")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT id, store_name FROM cms_stores ORDER BY store_name ASC")->fetch_all(MYSQLI_ASSOC);

// SỬA LẠI CÁCH LẤY SESSION ĐỂ TƯƠNG THÍCH HƠN
$logged_in_user_id = $_SESSION['user_id'] ?? ($_SESSION['user_info']['id'] ?? 0);
$logged_in_group_id = $_SESSION['group_id'] ?? ($_SESSION['user_info']['group_id'] ?? 0);

$group_by = $_GET['group_by'] ?? 'summary';
$from_date = $_GET['from'] ?? date('Y-m-01');
$to_date = $_GET['to'] ?? date('Y-m-t');
$customer_id = intval($_GET['customer_id'] ?? 0);
$user_id_from_get = $_GET['user_id'] ?? '';
$store_id = intval($_GET['store_id'] ?? 0);

// =================================================================
// PHẦN 2: XÂY DỰNG MỆNH ĐỀ WHERE (LOGIC PHÂN QUYỀN)
// =================================================================
$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';
}

if (!empty($from_date) && !empty($to_date)) {
    $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';
}
$whereSql = " WHERE " . implode(' AND ', $whereClauses);

// =================================================================
// PHẦN 3: TRUY VẤN DỮ LIỆU TỔNG QUAN
// =================================================================
$totals = ['total_orders' => 0, 'total_qty' => 0, 'total_discount' => 0, 'total_revenue' => 0, 'total_debt' => 0];
$sql_totals = "SELECT COUNT(o.id) as total_orders, SUM(o.total_quantity) as total_qty, SUM(o.discount_item) as total_discount, SUM(o.total_money) as total_revenue, SUM(o.lack) as total_debt FROM cms_orders o" . $whereSql;
$stmt_totals = $conn->prepare($sql_totals);
if ($stmt_totals) {
    if (!empty($types)) {
        call_user_func_array([$stmt_totals, 'bind_param'], refValues(array_merge([$types], $params)));
    }
    $stmt_totals->execute();
    $result = $stmt_totals->get_result()->fetch_assoc();
    if($result) $totals = $result;
    $stmt_totals->close();
}

// =================================================================
// PHẦN 4: TRUY VẤN DỮ LIỆU CHI TIẾT
// =================================================================
$report_data = [];
$table_headers = [];
$sql_report = '';

switch ($group_by) {
    case 'customer':
        $table_headers = ['Khách hàng', 'Số đơn', 'Tổng SL', 'Chiết khấu', 'Doanh số', 'Còn nợ'];
        $sql_report = "SELECT c.customer_name, COUNT(o.id) as order_count, SUM(o.total_quantity) as sum_qty, SUM(o.discount_item) as sum_discount, SUM(o.total_money) as sum_revenue, SUM(o.lack) as sum_debt FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID" . $whereSql . " GROUP BY o.customer_id ORDER BY sum_revenue DESC";
        break;
    case 'employee':
        $table_headers = ['Nhân viên', 'Số đơn', 'Tổng SL', 'Chiết khấu', 'Doanh số', 'Còn nợ'];
        $sql_report = "SELECT u.username, COUNT(o.id) as order_count, SUM(o.total_quantity) as sum_qty, SUM(o.discount_item) as sum_discount, SUM(o.total_money) as sum_revenue, SUM(o.lack) as sum_debt FROM cms_orders o LEFT JOIN cms_users u ON o.user_init = u.id" . $whereSql . " GROUP BY o.user_init ORDER BY sum_revenue DESC";
        break;
    case 'summary':
    default:
        $table_headers = ['Mã đơn hàng', 'Kho xuất', 'Ngày bán', 'Thu ngân', 'Khách hàng', 'SL', 'Chiết khấu', 'Tổng tiền', 'Nợ'];
        $sql_report = "SELECT o.id, o.output_code, s.store_name as warehouse, o.sell_date, u.username as cashier, c.customer_name, o.total_quantity, o.discount_item, o.total_money, o.lack FROM cms_orders o LEFT JOIN cms_stores s ON o.store_id = s.id LEFT JOIN cms_users u ON o.user_init = u.id LEFT JOIN cms_customers c ON o.customer_id = c.ID" . $whereSql . " ORDER BY o.id DESC";
        break;
}

if (!empty($sql_report)) {
    $stmt_report = $conn->prepare($sql_report);
    if ($stmt_report) {
        if (!empty($types)) {
            call_user_func_array([$stmt_report, 'bind_param'], refValues(array_merge([$types], $params)));
        }
        $stmt_report->execute();
        $report_data = $stmt_report->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt_report->close();
    }
}

function refValues($arr){
    $refs = [];
    foreach($arr as $key => $value)
        $refs[$key] = &$arr[$key];
    return $refs;
}
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Báo cáo doanh thu</h1>
    <div class="card shadow mb-4">
        <div class="card-body">
            <form method="GET" id="filter-form">
                <div class="row mb-3">
                    <div class="col-md-12">
                        <input type="hidden" name="group_by" value="<?php echo htmlspecialchars($group_by); ?>">
                        <div class="btn-group btn-group-toggle" data-toggle="buttons">
                           <label class="btn btn-outline-primary <?php if($group_by == 'summary') echo 'active'; ?>"><input type="radio" name="group_by_option" value="summary" <?php if($group_by == 'summary') echo 'checked'; ?>> Báo cáo tổng hợp</label>
                           <label class="btn btn-outline-primary <?php if($group_by == 'customer') echo 'active'; ?>"><input type="radio" name="group_by_option" value="customer" <?php if($group_by == 'customer') echo 'checked'; ?>> Theo khách hàng</label>
                           <?php if ($logged_in_group_id == 1): ?>
                           <label class="btn btn-outline-primary <?php if($group_by == 'employee') echo 'active'; ?>"><input type="radio" name="group_by_option" value="employee" <?php if($group_by == 'employee') echo 'checked'; ?>> Theo NV bán hàng</label>
                           <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-2"><select class="form-control" name="customer_id"><option value="">-- Khách hàng --</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-2"><select class="form-control" name="user_id"><option value="">-- Thu ngân --</option><?php foreach($users as $u) { echo "<option value='{$u['id']}' ".($u['id'] == $user_id_from_get ? 'selected' : '').">".htmlspecialchars($u['username'])."</option>"; } ?></select></div>
                    <?php endif; ?>

                    <div class="col-md-2"><select class="form-control" name="store_id"><option value="">-- Kho --</option><?php foreach($stores as $s) { echo "<option value='{$s['id']}' ".($s['id'] == $store_id ? 'selected' : '').">".htmlspecialchars($s['store_name'])."</option>"; } ?></select></div>
                    <div class="col-md-2"><input type="date" class="form-control" name="from" value="<?php echo htmlspecialchars($from_date); ?>"></div>
                    <div class="col-md-2"><input type="date" class="form-control" name="to" value="<?php echo htmlspecialchars($to_date); ?>"></div>
                    <div class="col-md-1"><button type="submit" class="btn btn-primary btn-block">Tìm</button></div>
                    <div class="col-md-1"><button type="button" class="btn btn-success btn-block" id="export-salary-btn">Báo cáo</button></div>
                </div>
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4"><div class="card border-left-primary shadow h-100 py-2"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Số đơn / Lượng SP</div><div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($totals['total_orders'] ?? 0); ?> / <?php echo number_format($totals['total_qty'] ?? 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 border-left-success shadow h-100 py-2"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-success text-uppercase mb-1">Chiết khấu</div><div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($totals['total_discount'] ?? 0, 0, ',', '.'); ?></div></div><div class="col-auto"><i class="fas fa-tags fa-2x text-gray-300"></i></div></div></div></div></div>
        <div class="col-xl-3 col-md-6 mb-4"><div class="card border-left-info shadow h-100 py-2"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-info text-uppercase mb-1">Doanh số</div><div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($totals['total_revenue'] ?? 0, 0, ',', '.'); ?></div></div><div class="col-auto"><i class="fas fa-sync-alt fa-2x text-gray-300"></i></div></div></div></div></div>
        <div class="col-xl-3 col-md-6 mb-4"><div class="card border-left-danger shadow h-100 py-2"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Khách nợ</div><div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($totals['total_debt'] ?? 0, 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="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 foreach ($table_headers as $header): ?>
                                <th><?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: ?>
                            <?php foreach($report_data as $row): ?>
                                <tr>
                                <?php if ($group_by == 'summary'): ?>
                                    <td><a href="/quanlybanhang/modules/orders/detail.php?id=<?php echo $row['id']; ?>"><?php echo htmlspecialchars($row['output_code']); ?></a></td>
                                    <td><?php echo htmlspecialchars($row['warehouse']); ?></td>
                                    <td><?php echo date('d/m/Y H:i', strtotime($row['sell_date'])); ?></td>
                                    <td><?php echo htmlspecialchars($row['cashier']); ?></td>
                                    <td><?php echo htmlspecialchars($row['customer_name']); ?></td>
                                    <td class="text-right"><?php echo number_format($row['total_quantity']); ?></td>
                                    <td class="text-right"><?php echo number_format($row['discount_item'], 0, ',', '.'); ?></td>
                                    <td class="text-right font-weight-bold"><?php echo number_format($row['total_money'], 0, ',', '.'); ?></td>
                                    <td class="text-right text-danger"><?php echo number_format($row['lack'], 0, ',', '.'); ?></td>
                                <?php elseif ($group_by == 'customer'): ?>
                                    <td><?php echo htmlspecialchars($row['customer_name']); ?></td>
                                    <td class="text-right"><?php echo number_format($row['order_count']); ?></td>
                                    <td class="text-right"><?php echo number_format($row['sum_qty']); ?></td>
                                    <td class="text-right"><?php echo number_format($row['sum_discount'], 0, ',', '.'); ?></td>
                                    <td class="text-right font-weight-bold"><?php echo number_format($row['sum_revenue'], 0, ',', '.'); ?></td>
                                    <td class="text-right text-danger"><?php echo number_format($row['sum_debt'], 0, ',', '.'); ?></td>
                                <?php elseif ($group_by == 'employee'): ?>
                                    <td><?php echo htmlspecialchars($row['username']); ?></td>
                                    <td class="text-right"><?php echo number_format($row['order_count']); ?></td>
                                    <td class="text-right"><?php echo number_format($row['sum_qty']); ?></td>
                                    <td class="text-right"><?php echo number_format($row['sum_discount'], 0, ',', '.'); ?></td>
                                    <td class="text-right font-weight-bold"><?php echo number_format($row['sum_revenue'], 0, ',', '.'); ?></td>
                                    <td class="text-right text-danger"><?php echo number_format($row['sum_debt'], 0, ',', '.'); ?></td>
                                <?php endif; ?>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php
require_once __DIR__ . '/../../templates/footer.php';
?>
<script>
$(document).ready(function() {
    $('#dataTable').DataTable({
        "order": [], 
        "pageLength": 25,
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" }
    });

    $('input[name="group_by_option"]').on('change', function() {
        $('input[name="group_by"]').val($(this).val());
        $(this).closest('form').submit();
    });

    $('#export-salary-btn').on('click', function(e) {
        e.preventDefault();
        
        const userGroupId = <?php echo $logged_in_group_id; ?>;
        const from = $('input[name="from"]').val();
        const to = $('input[name="to"]').val();
        let exportUrl = '';

        if (userGroupId == 1) { // Logic cho Ban Giám đốc
            const userId = $('select[name="user_id"]').val();
            if (userId === '') {
                alert('Vui lòng chọn một nhân viên để xuất báo cáo.');
                return;
            }
            exportUrl = `/quanlybanhang/modules/revenue/export_salary_report.php?user_id=${userId}&from=${from}&to=${to}`;
        } else { // Logic cho Nhân viên và các nhóm khác
            exportUrl = `/quanlybanhang/modules/revenue/export_my_revenue.php?from=${from}&to=${to}`;
        }
        
        window.location.href = exportUrl;
    });
});
</script>