<?php
// ajax/dashboard_ajax.php (Update: Thêm Chi phí)
require_once __DIR__ . '/../core/init.php';
date_default_timezone_set('Asia/Ho_Chi_Minh');
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');
    $start_month = date('Y-m-01');
    $end_month = date('Y-m-t');
    $data = [];

    // 1. THỐNG KÊ DOANH THU BÁN HÀNG (HÔM NAY)
    $sql_orders = "SELECT total_money, detail_order 
                   FROM cms_orders 
                   WHERE DATE(sell_date) = ? AND deleted = 0 AND order_status = 1";
    
    $stmt = $conn->prepare($sql_orders);
    $stmt->bind_param('s', $today);
    $stmt->execute();
    $res_orders = $stmt->get_result();
    
    $orders_data = [];
    $all_product_ids = [];
    $today_revenue = 0;
    $today_orders_count = 0;

    while ($row = $res_orders->fetch_assoc()) {
        $today_revenue += floatval($row['total_money']);
        $today_orders_count++;
        
        $items = json_decode($row['detail_order'], true);
        if (is_array($items)) {
            $row['parsed_items'] = $items;
            $orders_data[] = $row;
            foreach ($items as $item) {
                if(isset($item['id'])) $all_product_ids[] = intval($item['id']);
            }
        }
    }
    $stmt->close();

    // 2. LẤY THÔNG TIN VỐN CỦA SẢN PHẨM
    $product_info_map = [];
    if (!empty($all_product_ids)) {
        $ids_str = implode(',', array_unique($all_product_ids));
        $sql_p = "SELECT ID, prd_type, prd_origin_price, prd_est_cost_percent FROM cms_products WHERE ID IN ($ids_str)";
        $res_p = $conn->query($sql_p);
        while ($p = $res_p->fetch_assoc()) {
            $product_info_map[$p['ID']] = $p;
        }
    }

    // 3. TÍNH TOÁN GIÁ VỐN (COGS) & LỢI NHUẬN GỘP
    $total_cost = 0;
    foreach ($orders_data as $order) {
        foreach ($order['parsed_items'] as $item) {
            $pid = intval($item['id'] ?? 0);
            $qty = floatval($item['quantity'] ?? $item['qty'] ?? 0);
            $price = floatval($item['price'] ?? 0);

            if (isset($product_info_map[$pid])) {
                $info = $product_info_map[$pid];
                $cost_per_unit = 0;

                if ($info['prd_type'] == 1) { // Chế biến
                    $percent = floatval($info['prd_est_cost_percent']);
                    $cost_per_unit = $price * ($percent / 100);
                } else { // Hàng hóa
                    $cost_per_unit = floatval($info['prd_origin_price']);
                }
                $total_cost += ($qty * $cost_per_unit);
            }
        }
    }
    $today_profit = $today_revenue - $total_cost;

    // 4. TÍNH CHI PHÍ (TỪ BẢNG PHIẾU CHI - CMS_PAYMENT)
    // Chi hôm nay
    $sql_pay_today = "SELECT SUM(total_money) as total FROM cms_payment WHERE DATE(payment_date) = '$today' AND deleted = 0";
    $res_pay_today = $conn->query($sql_pay_today)->fetch_row();
    $today_expense = floatval($res_pay_today[0] ?? 0);

    // Chi tháng này
    $sql_pay_month = "SELECT SUM(total_money) as total FROM cms_payment WHERE DATE(payment_date) >= '$start_month' AND DATE(payment_date) <= '$end_month' AND deleted = 0";
    $res_pay_month = $conn->query($sql_pay_month)->fetch_row();
    $month_expense = floatval($res_pay_month[0] ?? 0);

    // --- GÁN DỮ LIỆU TRẢ VỀ ---
    $data['today_revenue'] = $today_revenue;
    $data['today_orders'] = $today_orders_count;
    $data['today_profit'] = $today_profit;
    $data['today_expense'] = $today_expense;   // <--- Mới thêm
    $data['month_expense'] = $month_expense;   // <--- Mới thêm

    // 5. CÁC THỐNG KÊ KHÁC (GIỮ NGUYÊN)
    $stmt_warehouse = $conn->prepare("SELECT SUM(CASE WHEN prd_type = 0 THEN prd_sls ELSE 0 END) as total_inventory, COUNT(ID) as total_products FROM cms_products WHERE deleted = 0 AND prd_status = 1");
    $stmt_warehouse->execute();
    $warehouse = $stmt_warehouse->get_result()->fetch_assoc();
    $data['total_inventory'] = $warehouse['total_inventory'] ?? 0;
    $data['total_products'] = $warehouse['total_products'] ?? 0;
    $stmt_warehouse->close();
    
    // Biểu đồ 7 ngày
    $seven_days_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 = 1 GROUP BY DATE(sell_date) ORDER BY DATE(sell_date) ASC");
    $data['charts']['sales_by_day'] = $seven_days_query->fetch_all(MYSQLI_ASSOC);

    // Biểu đồ Top SP
    $product_sales = [];
    $stmt_chart = $conn->prepare("SELECT detail_order FROM cms_orders WHERE deleted = 0 AND order_status = 1 AND sell_date BETWEEN ? AND ?");
    // Dùng lại biến start_month đã khai báo ở trên
    $end_month_full = date('Y-m-t 23:59:59'); 
    $start_month_full = date('Y-m-01 00:00:00');

    $stmt_chart->bind_param('ss', $start_month_full, $end_month_full);
    $stmt_chart->execute();
    $res_chart = $stmt_chart->get_result();

    while ($row = $res_chart->fetch_assoc()) {
        $details = json_decode($row['detail_order'], true);
        if (is_array($details)) {
            foreach ($details as $item) {
                $pid = $item['id'] ?? 0;
                $pname = $item['name'] ?? 'Unknown';
                $qty = floatval($item['quantity'] ?? $item['qty'] ?? 0);
                if (!isset($product_sales[$pid])) $product_sales[$pid] = ['name' => $pname, 'total' => 0];
                $product_sales[$pid]['total'] += $qty;
            }
        }
    }
    $stmt_chart->close();
    
    uasort($product_sales, function($a, $b) { return $b['total'] <=> $a['total']; });
    $data['charts']['top_products'] = array_slice($product_sales, 0, 10);

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

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