<?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
$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, 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);

$group_by = $_GET['group_by'] ?? 'employee';
if ($logged_in_group_id != 1 && $group_by === 'employee') {
    $group_by = 'order'; // Mặc định về xem theo đơn hàng cho nhân viên
}
$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: XÂY DỰNG MỆNH ĐỀ WHERE
$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)));
}

// PHẦN 3: TRUY VẤN DỮ LIỆU
$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.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.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.output_code as group_name, 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.username 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.username 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'));
}
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Báo cáo lợi nhuận</h1>
    
    <div class="row">
        <div class="col-xl-4 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">Doanh số</div><div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($total_revenue_card); ?></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-4 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">Tiền vốn</div><div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($total_cost_card); ?></div></div><div class="col-auto"><i class="fas fa-clipboard-list fa-2x text-gray-300"></i></div></div></div></div></div>
        <div class="col-xl-4 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">Lợi nhuận</div><div class="h4 mb-0 font-weight-bold text-gray-800"><?php echo number_format($gross_profit_card); ?></div></div><div class="col-auto"><i class="fas fa-dollar-sign fa-2x text-gray-300"></i></div></div></div></div></div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-body">
            <form method="GET">
                <div class="row mb-3"><div class="col-md-12"><strong>Thống kê lợi nhuận theo:</strong><div class="btn-group btn-group-toggle ml-3" 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></div>
                <div class="row align-items-end">
                    <div class="col-md-2 mb-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']}' ".($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-2"><select class="form-control" name="user_id"><option value="">-- NV bán hàng --</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 mb-2"><select class="form-control" name="store_id"><option value="">-- Cửa hàng --</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-2"><input type="date" class="form-control" name="from" value="<?php echo htmlspecialchars($from_date); ?>"></div>
                    <div class="col-md-2 mb-2"><input type="date" class="form-control" name="to" value="<?php echo htmlspecialchars($to_date); ?>"></div>
                    <div class="col-md-2 mb-2"><button type="submit" class="btn btn-primary btn-block">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>
                            <th class="text-left"><?php echo $table_headers[0]; ?></th>
                            <th class="<?php echo ($group_by == 'order') ? 'text-left' : 'text-center'; ?>"><?php echo $table_headers[1]; ?></th>
                            <th class="text-right"><?php echo $table_headers[2]; ?></th>
                            <th class="text-right"><?php echo $table_headers[3]; ?></th>
                            <th class="text-right"><?php echo $table_headers[4]; ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($report_data)): ?>
                            <tr><td colspan="5" class="text-center">Không có dữ liệu phù hợp với bộ lọc.</td></tr>
                        <?php else: ?>
                            <tr class="table-light font-weight-bold" style="font-size: 1rem;">
                                <td class="text-left" colspan="<?php echo ($group_by == 'order') ? '2' : '1'; ?>">TỔNG CỘNG</td>
                                <?php if ($group_by != 'order'): ?>
                                    <td class="text-center"><?php echo number_format($total_orders_sum); ?></td>
                                <?php endif; ?>
                                <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>
                            </tr>
                            <?php foreach($report_data as $row): ?>
                                <tr>
                                    <td class="text-left"><?php echo htmlspecialchars($row['group_name']); ?></td>
                                    <?php if ($group_by == 'order'): ?>
                                        <td class="text-left"><?php echo htmlspecialchars($row['customer_name'] ?? 'N/A'); ?></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 font-weight-bold text-success" style="font-size: 1.05em;"><?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>
$(document).ready(function() {
    $('#dataTable').DataTable({ 
        "ordering": false,
        "pageLength": 25, 
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" } 
    });
    
    $('input[name="group_by"]').on('change', function() { 
        $(this).closest('form').submit(); 
    });
});
</script>