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

header('Content-Type: application/json; charset=utf-8');

$response = ['status' => 'error', 'message' => 'Hành động không hợp lệ.'];
$action = $_REQUEST['action'] ?? '';

if ($action == 'get_dashboard_data') {
    $today = date('Y-m-d');
    $data = [];

    // Thống kê hôm nay
    $stmt_today = $conn->prepare("SELECT COUNT(ID) as order_count, SUM(total_money) as total_revenue FROM cms_orders WHERE DATE(sell_date) = ? AND deleted = 0 AND order_status > 0");
    $stmt_today->bind_param('s', $today);
    $stmt_today->execute();
    $today_activity = $stmt_today->get_result()->fetch_assoc();
    $data['today_sales_amount'] = $today_activity['total_revenue'] ?? 0;
    $data['today_order_count'] = $today_activity['order_count'] ?? 0;
    $stmt_today->close();

    // Thống kê kho
    $stmt_warehouse = $conn->prepare("SELECT 
        SUM(prd_sls) as total_inventory,
        COUNT(CASE WHEN prd_sls <= 0 THEN 1 END) as out_of_stock,
        COUNT(CASE WHEN prd_sls > 0 AND prd_sls < 10 THEN 1 END) as low_stock,
        COUNT(ID) as total_products
        FROM cms_products WHERE deleted = 0");
    $stmt_warehouse->execute();
    $warehouse_data = $stmt_warehouse->get_result()->fetch_assoc();
    $data['warehouse_inventory'] = $warehouse_data['total_inventory'] ?? 0;
    $data['warehouse_out_of_stock'] = $warehouse_data['out_of_stock'] ?? 0;
    $data['warehouse_low_stock'] = $warehouse_data['low_stock'] ?? 0;
    $data['product_info_total'] = $warehouse_data['total_products'] ?? 0;
    $stmt_warehouse->close();
    
    // Biểu đồ doanh số 7 ngày gần nhất
    $seven_days_sales_query = $conn->query("SELECT DATE_FORMAT(sell_date, '%d/%m') as sale_day, SUM(total_money) as daily_total FROM cms_orders WHERE sell_date >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) AND sell_date <= NOW() AND deleted = 0 AND order_status > 0 GROUP BY DATE(sell_date) ORDER BY DATE(sell_date) ASC");
    $data['charts']['sales_by_day'] = $seven_days_sales_query->fetch_all(MYSQLI_ASSOC);

    // Biểu đồ top 10 sản phẩm bán chạy (theo số lượng)
    $product_sales = [];
    $product_names = [];
    $all_products_query = $conn->query("SELECT ID, prd_name FROM cms_products WHERE deleted = 0");
    while($p = $all_products_query->fetch_assoc()) {
        $product_names[$p['ID']] = $p['prd_name'];
    }

    $start_month = date('Y-m-01 00:00:00');
    $end_month = date('Y-m-t 23:59:59');
    $stmt_chart_product = $conn->prepare("SELECT detail_order FROM cms_orders WHERE deleted = 0 AND order_status > 0 AND sell_date BETWEEN ? AND ?");
    $stmt_chart_product->bind_param('ss', $start_month, $end_month);
    $stmt_chart_product->execute();
    $orders_details_result = $stmt_chart_product->get_result();
    
    if ($orders_details_result) {
        while ($row = $orders_details_result->fetch_assoc()) {
            $details = json_decode($row['detail_order'], true);
            if (is_array($details)) {
                foreach ($details as $item) {
                    if (isset($item['id'], $item['quantity'], $product_names[$item['id']])) {
                        $pid = $item['id'];
                        $quantity = (float)$item['quantity'];
                        if (!isset($product_sales[$pid])) {
                            $product_sales[$pid] = ['name' => $product_names[$pid], 'total' => 0];
                        }
                        $product_sales[$pid]['total'] += $quantity;
                    }
                }
            }
        }
    }
    $stmt_chart_product->close();
    
    uasort($product_sales, function($a, $b) {
        return $b['total'] <=> $a['total'];
    });
    $data['charts']['sales_by_product'] = array_slice($product_sales, 0, 10, true);

    $response = ['status' => 'success', 'data' => $data];
}

echo json_encode($response, JSON_NUMERIC_CHECK);
$conn->close();
?>