<?php
require_once __DIR__ . '/../core/init.php';
header('Content-Type: application/json; charset=utf-8');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$user_id = $_SESSION['user_id'] ?? 0;
$group_id = $_SESSION['group_id'] ?? 0;
$action = $_REQUEST['action'] ?? '';

switch ($action) {
    case 'get_revenue_data':
        handle_get_revenue_data($conn, $user_id, $group_id);
        break;
    case 'get_order_details':
        handle_get_order_details($conn);
        break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}

function handle_get_revenue_data($conn, $user_id, $group_id) {
    $draw = intval($_GET['draw'] ?? 0);
    $start = intval($_GET['start'] ?? 0);
    $length = intval($_GET['length'] ?? 10);
    
    $base_sql = "FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID LEFT JOIN cms_users u ON o.user_init = u.id LEFT JOIN cms_stores s ON o.store_id = s.id";
    $params = [];
    $types = "";
    $where_conditions = ["o.deleted = 0"];

    if (!empty($_GET['from'])) { $where_conditions[] = "o.sell_date >= ?"; $params[] = "{$_GET['from']} 00:00:00"; $types .= "s"; }
    if (!empty($_GET['to'])) { $where_conditions[] = "o.sell_date <= ?"; $params[] = "{$_GET['to']} 23:59:59"; $types .= "s"; }
    if (!empty($_GET['customer_id'])) { $where_conditions[] = "o.customer_id = ?"; $params[] = $_GET['customer_id']; $types .= "i"; }
    if (!empty($_GET['user_id'])) { $where_conditions[] = "o.user_init = ?"; $params[] = $_GET['user_id']; $types .= "i"; }
    if (!empty($_GET['store_id'])) { $where_conditions[] = "o.store_id = ?"; $params[] = $_GET['store_id']; $types .= "i"; }

    if ($group_id != 1) {
        $where_conditions[] = "o.user_init = ?";
        $params[] = $user_id;
        $types .= "i";
    }

    $where_sql = " WHERE " . implode(" AND ", $where_conditions);
    $discount_case_sql = "CASE WHEN o.output_code LIKE 'PXK%' THEN (o.total_discount + o.discount_item) ELSE o.total_discount END";
    $sql_totals = "SELECT COUNT(o.id) as total_orders, SUM(o.total_quantity) as total_qty, SUM({$discount_case_sql}) as total_discount, SUM(o.total_money) as total_revenue, SUM(o.lack) as total_debt " . $base_sql . $where_sql;
    $stmt_totals = $conn->prepare($sql_totals);
    if ($types) { $stmt_totals->bind_param($types, ...$params); }
    $stmt_totals->execute();
    $totals = $stmt_totals->get_result()->fetch_assoc();
    $stmt_totals->close();

    $recordsFiltered = intval($totals['total_orders'] ?? 0);
    $recordsTotal = $conn->query("SELECT COUNT(ID) FROM cms_orders WHERE deleted = 0")->fetch_row()[0] ?? 0;
    
    $sql_data = "SELECT o.ID as id, o.output_code, o.sell_date, o.total_money, o.lack, o.total_quantity, ({$discount_case_sql}) as discount_amount, COALESCE(c.customer_name, 'Khách lẻ') as customer_name, u.display_name as cashier, s.store_name as warehouse " . $base_sql . $where_sql . " ORDER BY o.sell_date DESC, o.ID DESC LIMIT ?, ?";
    
    $data_params = $params;
    $data_params[] = $start;
    $data_params[] = $length;
    $data_types = $types . 'ii';

    $stmt_data = $conn->prepare($sql_data);
    $stmt_data->bind_param($data_types, ...$data_params);
    $stmt_data->execute();
    $data_rows = $stmt_data->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_data->close();
    
    echo json_encode(["draw" => $draw, "recordsTotal" => $recordsTotal, "recordsFiltered" => $recordsFiltered, "data" => $data_rows, "totals" => ["total_orders" => $totals['total_orders'] ?? 0, "total_qty" => $totals['total_qty'] ?? 0, "total_discount" => $totals['total_discount'] ?? 0, "total_revenue" => $totals['total_revenue'] ?? 0, "total_debt" => $totals['total_debt'] ?? 0]], JSON_NUMERIC_CHECK);
}

function handle_get_order_details($conn) {
    $order_id = intval($_GET['order_id'] ?? 0);
    if ($order_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'ID đơn hàng không hợp lệ.']); exit();
    }
    
    $stmt_order = $conn->prepare("SELECT * FROM cms_orders WHERE id = ?");
    $stmt_order->bind_param("i", $order_id);
    $stmt_order->execute();
    $order_record = $stmt_order->get_result()->fetch_assoc();
    $stmt_order->close();

    if (!$order_record) {
        echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy đơn hàng.']); exit();
    }

    $items_from_db = [];
    $product_ids_to_fetch = [];
    if (!empty($order_record['detail_order'])) {
        $decoded_items = json_decode($order_record['detail_order'], true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded_items)) {
            $items_from_db = $decoded_items;
            foreach ($items_from_db as $item) {
                if ((!isset($item['name']) || !isset($item['code'])) && isset($item['id'])) {
                    $product_ids_to_fetch[intval($item['id'])] = intval($item['id']);
                }
            }
        }
    }

    if (!empty($product_ids_to_fetch)) {
        $ids_placeholder = implode(',', array_fill(0, count($product_ids_to_fetch), '?'));
        $types = str_repeat('i', count($product_ids_to_fetch));
        
        $stmt_products = $conn->prepare("SELECT ID, prd_name, prd_code FROM cms_products WHERE ID IN ($ids_placeholder)");
        $stmt_products->bind_param($types, ...$product_ids_to_fetch);
        $stmt_products->execute();
        $products_result = $stmt_products->get_result();
        
        $product_info_map = [];
        while ($row = $products_result->fetch_assoc()) {
            $product_info_map[$row['ID']] = $row;
        }
        $stmt_products->close();
        
        foreach ($items_from_db as &$item) {
            $p_id = intval($item['id']);
            if (isset($product_info_map[$p_id])) {
                if (!isset($item['name'])) $item['name'] = $product_info_map[$p_id]['prd_name'];
                if (!isset($item['code'])) $item['code'] = $product_info_map[$p_id]['prd_code'];
            }
        }
        unset($item);
    }

    $total_discount_correct = 0;
    if (strpos($order_record['output_code'], 'PXK') === 0) {
        $total_discount_correct = floatval($order_record['total_discount']) + floatval($order_record['discount_item']);
    } else {
        $total_discount_correct = floatval($order_record['total_discount']);
    }

    $response_data = [
        'summary' => [
            'total_quantity' => $order_record['total_quantity'],
            'total_price' => $order_record['total_price'],
            'total_discount' => $total_discount_correct,
            'total_money' => $order_record['total_money'],
            'lack' => $order_record['lack']
        ],
        'products' => $items_from_db
    ];
    
    echo json_encode(['status' => 'success', 'data' => $response_data], JSON_NUMERIC_CHECK);
    exit();
}
?>