<?php
// File: /ajax/dashboard_ajax.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 = [];

    // --- SỬA LỖI: Thêm `AND deleted = 0` vào tất cả các truy vấn cms_orders ---

    // 1. Hoạt động hôm nay (FIXED)
    $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");
    $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();

    // Tính số đơn hàng trả lại trong ngày
    $stmt_return_today = $conn->prepare("SELECT COUNT(DISTINCT order_id) as return_count FROM cms_canreturn WHERE DATE(created) = ?");
    $stmt_return_today->bind_param('s', $today);
    $stmt_return_today->execute();
    $today_return_activity = $stmt_return_today->get_result()->fetch_assoc();
    $data['today_return_count'] = $today_return_activity['return_count'] ?? 0;
    $stmt_return_today->close();

    // 2. Thẻ tóm tắt "Hoạt động" (FIXED)
    $sales_activity_query = $conn->query("SELECT SUM(total_money) as total_sales, COUNT(ID) as total_orders, SUM(total_quantity) as total_qty FROM cms_orders WHERE deleted = 0");
    $sales_activity = $sales_activity_query->fetch_assoc();
    $data['summary_total_sales'] = $sales_activity['total_sales'] ?? 0;
    $data['summary_total_orders'] = $sales_activity['total_orders'] ?? 0;
    $data['summary_sales_qty'] = $sales_activity['total_qty'] ?? 0;

    $return_activity_query = $conn->query("SELECT COUNT(DISTINCT order_id) as total_returns, SUM(quantity) as return_qty FROM cms_canreturn");
    $return_activity = $return_activity_query->fetch_assoc();
    $data['summary_total_returns'] = $return_activity['total_returns'] ?? 0;
    $data['summary_return_qty'] = $return_activity['return_qty'] ?? 0;
    
    // 3. Thẻ tóm tắt "Thông tin kho"
    $data['warehouse_inventory'] = $conn->query("SELECT COUNT(*) FROM cms_products WHERE prd_inventory > 0 AND deleted = 0")->fetch_row()[0] ?? 0;
    $data['warehouse_out_of_stock'] = $conn->query("SELECT COUNT(*) FROM cms_products WHERE prd_inventory <= 0 AND deleted = 0")->fetch_row()[0] ?? 0;
    $data['warehouse_low_stock'] = $conn->query("SELECT COUNT(*) FROM cms_products WHERE prd_inventory > 0 AND prd_inventory < 10 AND deleted = 0")->fetch_row()[0] ?? 0;

    // 4. Thẻ tóm tắt "Thông tin sản phẩm"
    $product_info_query = $conn->query("SELECT COUNT(ID) as total_products, COUNT(DISTINCT prd_manufacture_id) as total_manufacturers FROM cms_products WHERE deleted = 0");
    $product_info_data = $product_info_query->fetch_assoc();
    $data['product_info_total'] = $product_info_data['total_products'] ?? 0;
    $data['product_info_manufacturers'] = $product_info_data['total_manufacturers'] ?? 0;
    $data['product_info_no_sell_price'] = $conn->query("SELECT COUNT(*) FROM cms_products WHERE (prd_sell_price IS NULL OR prd_sell_price = 0) AND deleted = 0")->fetch_row()[0] ?? 0;
    $data['product_info_no_import_price'] = $conn->query("SELECT COUNT(*) FROM cms_products WHERE (prd_origin_price IS NULL OR prd_origin_price = 0) AND deleted = 0")->fetch_row()[0] ?? 0;
    
    // 5. Biểu đồ doanh số 7 ngày gần nhất (FIXED)
    $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 GROUP BY DATE(sell_date) ORDER BY DATE(sell_date) ASC");
    $data['charts']['sales_by_day'] = $seven_days_sales_query->fetch_all(MYSQLI_ASSOC);

    // 6. Biểu đồ doanh số theo sản phẩm (FIXED)
    $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'];
    }

    $orders_details_result = $conn->query("SELECT detail_order FROM cms_orders WHERE detail_order IS NOT NULL AND detail_order != '' AND deleted = 0");
    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'];
                        $price = (float)($item['price'] ?? 0);
                        $quantity = (int)$item['quantity'];
                        if (!isset($product_sales[$pid])) {
                            $product_sales[$pid] = ['name' => $product_names[$pid], 'total' => 0];
                        }
                        $product_sales[$pid]['total'] += $price * $quantity;
                    }
                }
            }
        }
    }
    uasort($product_sales, function($a, $b) {
        return $b['total'] <=> $a['total'];
    });
    $data['charts']['sales_by_product'] = array_slice(array_values($product_sales), 0, 10);

    // 7. Dữ liệu biểu đồ doanh số theo nhân viên (FIXED)
    $employee_sales_query = $conn->query("SELECT u.display_name, SUM(o.total_money) as employee_total FROM cms_orders o JOIN cms_users u ON o.user_init = u.ID WHERE o.deleted = 0 GROUP BY u.ID ORDER BY employee_total DESC");
    $data['charts']['sales_by_employee'] = $employee_sales_query->fetch_all(MYSQLI_ASSOC);

    // 8. Top 3 khách hàng (FIXED)
    $top_customers_query = $conn->query("SELECT c.customer_name, SUM(o.total_money) as total_spent FROM cms_orders o JOIN cms_customers c ON o.customer_id = c.ID WHERE o.deleted = 0 AND o.customer_id IS NOT NULL GROUP BY c.ID ORDER BY total_spent DESC LIMIT 3");
    $data['tops']['customers'] = $top_customers_query->fetch_all(MYSQLI_ASSOC);

    // 9. Top 3 nhân viên (FIXED)
    $top_employees_query = $conn->query("SELECT u.display_name, SUM(o.total_money) as total_revenue, COUNT(o.ID) as total_orders FROM cms_orders o JOIN cms_users u ON o.user_init = u.ID WHERE o.deleted = 0 GROUP BY u.ID ORDER BY total_revenue DESC LIMIT 3");
    $data['tops']['employees'] = $top_employees_query->fetch_all(MYSQLI_ASSOC);

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

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