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

if (!isset($_SESSION['user_id'])) {
    echo '<div class="alert alert-danger m-3">Không có quyền truy cập.</div>';
    exit();
}

$user_id = $_SESSION['user_id'];
$group_id = $_SESSION['group_id'] ?? 0;
$current_date = date('Y-m-d');

// --- Dữ liệu cho báo cáo tháng ---
$first_day_of_month = date('Y-m-01');

$month_params = [];
$month_types = "";
$month_where_conditions = ["o.sell_date BETWEEN ? AND ?", "o.deleted = 0", "o.order_status > 0"];
$month_params[] = $first_day_of_month . " 00:00:00";
$month_params[] = $current_date . " 23:59:59";
$month_types .= "ss";

// SỬA LẠI LOGIC: Chỉ Admin (group 1) mới xem được của tất cả mọi người
if ($group_id != 1) {
    $month_where_conditions[] = "o.user_init = ?";
    $month_params[] = $user_id;
    $month_types .= "i";
}
$month_sql_where = " WHERE " . implode(" AND ", $month_where_conditions);

// Lấy chỉ số tháng
$month_revenue = 0;
$month_profit = 0;
$month_orders = 0;
$month_products_sold = 0;

$sql_month_summary = "SELECT 
                        COUNT(ID) as total_orders, 
                        SUM(total_money) as total_revenue,
                        SUM(total_money - total_origin_price) as total_profit
                    FROM cms_orders o " . $month_sql_where;
$stmt_month_summary = $conn->prepare($sql_month_summary);
if ($stmt_month_summary) {
    if (!empty($month_types)) $stmt_month_summary->bind_param($month_types, ...$month_params);
    $stmt_month_summary->execute();
    $summary_result = $stmt_month_summary->get_result()->fetch_assoc();
    $stmt_month_summary->close();

    $month_revenue = $summary_result['total_revenue'] ?? 0;
    $month_profit = $summary_result['total_profit'] ?? 0;
    $month_orders = $summary_result['total_orders'] ?? 0;
}

$sql_month_products = "SELECT detail_order FROM cms_orders o " . $month_sql_where;
$stmt_month_products = $conn->prepare($sql_month_products);
if ($stmt_month_products) {
    if (!empty($month_types)) $stmt_month_products->bind_param($month_types, ...$month_params);
    $stmt_month_products->execute();
    $product_result = $stmt_month_products->get_result();
    while ($row = $product_result->fetch_assoc()) {
        if (!empty($row['detail_order'])) {
            $products = json_decode($row['detail_order'], true);
            if (is_array($products)) {
                foreach ($products as $product) {
                    $month_products_sold += (int)($product['quantity'] ?? 0);
                }
            }
        }
    }
    $stmt_month_products->close();
}

// --- Dữ liệu cho báo cáo hôm nay ---
$today_params = [];
$today_types = "";
$today_where_conditions = ["DATE(o.sell_date) = ?", "o.deleted = 0", "o.order_status > 0"];
$today_params[] = $current_date;
$today_types .= "s";

// SỬA LẠI LOGIC: Chỉ Admin (group 1) mới xem được của tất cả mọi người
if ($group_id != 1) {
    $today_where_conditions[] = "o.user_init = ?";
    $today_params[] = $user_id;
    $today_types .= "i";
}
$today_sql_where = " WHERE " . implode(" AND ", $today_where_conditions);

$today_revenue = 0;
$today_orders = 0;

$sql_today_summary = "SELECT COUNT(ID) as total_orders, SUM(total_money) as total_revenue FROM cms_orders o " . $today_sql_where;
$stmt_today_summary = $conn->prepare($sql_today_summary);
if ($stmt_today_summary) {
    if (!empty($today_types)) $stmt_today_summary->bind_param($today_types, ...$today_params);
    $stmt_today_summary->execute();
    $today_summary_result = $stmt_today_summary->get_result()->fetch_assoc();
    $stmt_today_summary->close();

    $today_revenue = $today_summary_result['total_revenue'] ?? 0;
    $today_orders = $today_summary_result['total_orders'] ?? 0;
}
?>

<div class="container-fluid pt-3 pb-5">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="mb-0">Tổng quan tháng</h4>
        <span class="text-muted small fw-bold"><?php echo date('d/m/Y'); ?></span>
    </div>
    <div class="row g-3">
        <div class="col-6">
            <div class="overview-card">
                <div class="card-icon icon-revenue"><i class="fas fa-chart-bar"></i></div>
                <div class="card-details">
                    <div class="card-label">DOANH SỐ THÁNG</div>
                    <div class="card-value"><?php echo number_format($month_revenue); ?> đ</div>
                </div>
            </div>
        </div>
        <div class="col-6">
             <div class="overview-card">
                <div class="card-icon icon-revenue-today"><i class="fas fa-coins"></i></div>
                <div class="card-details">
                    <div class="card-label">DOANH SỐ HÔM NAY</div>
                    <div class="card-value"><?php echo number_format($today_revenue); ?> đ</div>
                </div>
            </div>
        </div>
        <div class="col-6">
            <div class="overview-card">
                <div class="card-icon icon-profit"><i class="fas fa-wallet"></i></div>
                <div class="card-details">
                    <div class="card-label">LỢI NHUẬN THÁNG</div>
                    <div class="card-value"><?php echo number_format($month_profit); ?> đ</div>
                </div>
            </div>
        </div>
        <div class="col-6">
            <div class="overview-card">
                <div class="card-icon icon-products"><i class="fas fa-box"></i></div>
                <div class="card-details">
                    <div class="card-label">SẢN PHẨM BÁN (THÁNG)</div>
                    <div class="card-value"><?php echo number_format($month_products_sold); ?></div>
                </div>
            </div>
        </div>
         <div class="col-6">
            <div class="overview-card">
                <div class="card-icon icon-orders"><i class="fas fa-receipt"></i></div>
                <div class="card-details">
                    <div class="card-label">ĐƠN HÀNG THÁNG</div>
                    <div class="card-value"><?php echo number_format($month_orders); ?></div>
                </div>
            </div>
        </div>
        <div class="col-6">
            <div class="overview-card">
                <div class="card-icon icon-orders-today"><i class="fas fa-file-invoice-dollar"></i></div>
                <div class="card-details">
                    <div class="card-label">ĐƠN HÀNG HÔM NAY</div>
                    <div class="card-value"><?php echo number_format($today_orders); ?></div>
                </div>
            </div>
        </div>
    </div>
</div>