<?php
require_once __DIR__ . '/../../core/init.php';

$month_str = $_GET['month'] ?? date('Y-m');
$user_id = $_GET['user_id'] ?? 'all';
list($year, $month) = explode('-', $month_str);

// (Logic lấy dữ liệu tương tự như file ajax, copy lại đoạn logic query)
$user_cond = ($user_id != 'all') ? "AND id = ".intval($user_id) : "";
$users = $conn->query("SELECT * FROM cms_users WHERE user_status = 1 $user_cond")->fetch_all(MYSQLI_ASSOC);

$data_rows = "";
$total_all = 0;

foreach ($users as $u) {
    $sql_sales = "SELECT SUM(total_money) as total_sales, SUM(total_origin_price) as total_cost 
                  FROM cms_orders WHERE user_init = {$u['id']} AND order_status = 1 
                  AND MONTH(sell_date) = $month AND YEAR(sell_date) = $year";
    $sales = $conn->query($sql_sales)->fetch_assoc();
    
    $doanh_so = floatval($sales['total_sales']);
    $von = floatval($sales['total_cost']);
    $loi_nhuan = max(0, $doanh_so - $von);
    $hoa_hong = $loi_nhuan * ($u['commission'] / 100);
    $thuc_linh = $u['salary_base'] + $u['allowance'] + $hoa_hong;
    $total_all += $thuc_linh;

    $data_rows .= "<tr>
        <td>{$u['display_name']}</td>
        <td>{$u['bank_name']} - {$u['bank_account']}</td>
        <td>".number_format($u['salary_base'])."</td>
        <td>".number_format($u['allowance'])."</td>
        <td>".number_format($doanh_so)."</td>
        <td>".number_format($loi_nhuan)."</td>
        <td>{$u['commission']}%</td>
        <td>".number_format($hoa_hong)."</td>
        <td style='font-weight:bold; color:red;'>".number_format($thuc_linh)."</td>
    </tr>";
}

// XUẤT HEADER EXCEL
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=Bang_Luong_Thang_{$month}_{$year}.xls");
header("Pragma: no-cache");
header("Expires: 0");

echo "<meta charset='UTF-8'>";
echo "<table border='1'>";
echo "<thead>
        <tr style='background-color:#f0f0f0; font-weight:bold;'>
            <th>Nhân viên</th>
            <th>Thông tin NH</th>
            <th>Lương cứng</th>
            <th>Phụ cấp</th>
            <th>Doanh số</th>
            <th>Lợi nhuận</th>
            <th>% Hoa hồng</th>
            <th>Tiền Hoa hồng</th>
            <th>THỰC LĨNH</th>
        </tr>
      </thead>";
echo "<tbody>" . $data_rows . "</tbody>";
echo "<tfoot><tr><td colspan='8' align='right'><b>TỔNG CỘNG:</b></td><td><b>".number_format($total_all)."</b></td></tr></tfoot>";
echo "</table>";
exit;
?>