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

// Hàm để dừng và trả về lỗi một cách an toàn
function terminate_with_error($message, $draw) {
    die(json_encode([
        'status' => 'error',
        'message' => $message,
        'data' => [],
        'draw' => $draw,
        'recordsTotal' => 0,
        'recordsFiltered' => 0
    ]));
}

// 1. ĐỌC VÀ XỬ LÝ CÁC THAM SỐ ĐẦU VÀO
$draw = intval($_POST['draw'] ?? 0);
$start = intval($_POST['start'] ?? 0);
$length = intval($_POST['length'] ?? 10);
$search_term = $_POST['q'] ?? '';
$category_id = intval($_POST['category'] ?? 0);
$manufacturer_id = intval($_POST['manufacturer'] ?? 0);
$store_id = intval($_POST['store'] ?? 1);
$from_date = $_POST['from'] ?? date('Y-m-01');
$to_date = $_POST['to'] ?? date('Y-m-t');

$from_datetime = $from_date . ' 00:00:00';
$to_datetime = $to_date . ' 23:59:59';

// 2. LẤY DANH SÁCH SẢN PHẨM CÙNG TỒN KHO HIỆN TẠI
$sql_products = "SELECT p.id, p.prd_code, p.prd_name, p.prd_origin_price, p.prd_sls 
                 FROM cms_products p";
$params_products = [];
$types_products = '';
$whereClauses = ["p.deleted = 0"];

if (!empty($search_term)) {
    $whereClauses[] = "(p.prd_name LIKE ? OR p.prd_code LIKE ?)";
    $search_like = "%{$search_term}%";
    array_push($params_products, $search_like, $search_like);
    $types_products .= 'ss';
}
if ($category_id > 0) { $whereClauses[] = "p.prd_group_id = ?"; $params_products[] = $category_id; $types_products .= 'i'; }
if ($manufacturer_id > 0) { $whereClauses[] = "p.prd_manufacture_id = ?"; $params_products[] = $manufacturer_id; $types_products .= 'i'; }
$sql_products .= " WHERE " . implode(' AND ', $whereClauses);

$stmt_products = $conn->prepare($sql_products);
if ($stmt_products === false) { terminate_with_error("Lỗi SQL khi lấy sản phẩm: " . $conn->error, $draw); }
if (!empty($types_products)) { $stmt_products->bind_param($types_products, ...$params_products); }
$stmt_products->execute();
$products_result = $stmt_products->get_result();
$all_products_map = [];
while($row = $products_result->fetch_assoc()) {
    $all_products_map[$row['id']] = $row;
}
$stmt_products->close();

if (empty($all_products_map)) {
    // Nếu không có sản phẩm nào khớp, trả về kết quả rỗng
    die(json_encode([
        "draw" => $draw, "recordsTotal" => 0, "recordsFiltered" => 0, "data" => [],
        "total_opening" => 0, "total_imported" => 0, "total_exported" => 0, "total_closing" => 0, "total_inventory_value" => 0
    ]));
}

// 3. TÍNH TOÁN CÁC GIAO DỊCH NHẬP/XUẤT
$product_ids = array_keys($all_products_map);
$placeholders = implode(',', array_fill(0, count($product_ids), '?'));
$types = str_repeat('i', count($product_ids));

$imports_in_period = []; $exports_in_period = [];
$imports_after_period = []; $exports_after_period = [];

// Hàm trợ giúp để tổng hợp số lượng từ chuỗi JSON
function sum_quantities_from_json($conn, $sql, $params, $types) {
    $stmt = $conn->prepare($sql);
    if (!$stmt) return [];
    if (!empty($types)) $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    $totals = [];
    while ($row = $result->fetch_assoc()) {
        $items = json_decode($row['details'], true);
        if (is_array($items)) {
            foreach ($items as $item) {
                $id = intval($item['id'] ?? 0);
                if ($id > 0) {
                    $qty = floatval($item['quantity'] ?? 0);
                    $totals[$id] = ($totals[$id] ?? 0) + $qty;
                }
            }
        }
    }
    $stmt->close();
    return $totals;
}

// Tính toán giao dịch TRONG KỲ
$imports_in_period = sum_quantities_from_json($conn, "SELECT detail_input as details FROM cms_input WHERE store_id = ? AND input_date BETWEEN ? AND ?", [$store_id, $from_datetime, $to_datetime], 'iss');
$exports_in_period = sum_quantities_from_json($conn, "SELECT detail_order as details FROM cms_orders WHERE store_id = ? AND deleted = 0 AND order_status > 0 AND sell_date BETWEEN ? AND ?", [$store_id, $from_datetime, $to_datetime], 'iss');

// Tính toán giao dịch SAU KỲ
$imports_after_period = sum_quantities_from_json($conn, "SELECT detail_input as details FROM cms_input WHERE store_id = ? AND input_date > ?", [$store_id, $to_datetime], 'is');
$exports_after_period = sum_quantities_from_json($conn, "SELECT detail_order as details FROM cms_orders WHERE store_id = ? AND deleted = 0 AND order_status > 0 AND sell_date > ?", [$store_id, $to_datetime], 'is');


// 4. TÍNH TOÁN BÁO CÁO DỰA TRÊN DỮ LIỆU ĐÃ THU THẬP
$full_data = [];
foreach ($all_products_map as $product_id => $product) {
    $cost_price = (float)($product['prd_origin_price'] ?? 0);
    $current_stock = (float)($product['prd_sls'] ?? 0);
    
    $imported_in_period_qty = (float)($imports_in_period[$product_id] ?? 0);
    $exported_in_period_qty = (float)($exports_in_period[$product_id] ?? 0);
    
    $imported_after_period_qty = (float)($imports_after_period[$product_id] ?? 0);
    $exported_after_period_qty = (float)($exports_after_period[$product_id] ?? 0);

    // Tính toán theo logic "tua ngược" từ tồn hiện tại
    $closing_stock_qty = $current_stock - $imported_after_period_qty + $exported_after_period_qty;
    $opening_stock_qty = $closing_stock_qty - $imported_in_period_qty + $exported_in_period_qty;
    
    // Chỉ thêm vào báo cáo nếu có hoạt động hoặc có tồn kho
    if ($opening_stock_qty != 0 || $imported_in_period_qty != 0 || $exported_in_period_qty != 0 || $closing_stock_qty != 0) {
        $full_data[] = [
            "id" => $product_id, // Thêm ID để tạo link
            "prd_code" => $product['prd_code'], 
            "prd_name" => $product['prd_name'],
            "opening_stock_qty" => $opening_stock_qty, "opening_stock_amount" => $opening_stock_qty * $cost_price,
            "imported_qty" => $imported_in_period_qty, "imported_amount" => $imported_in_period_qty * $cost_price,
            "exported_qty" => $exported_in_period_qty, "exported_amount" => $exported_in_period_qty * $cost_price,
            "closing_stock_qty" => $closing_stock_qty, "closing_stock_amount" => $closing_stock_qty * $cost_price,
        ];
    }
}

// 5. TÍNH TOÁN CÁC SỐ TÓM TẮT VÀ TRẢ VỀ JSON
$total_opening = array_sum(array_column($full_data, 'opening_stock_qty'));
$total_imported = array_sum(array_column($full_data, 'imported_qty'));
$total_exported = array_sum(array_column($full_data, 'exported_qty'));
$total_closing = array_sum(array_column($full_data, 'closing_stock_qty'));
$total_inventory_value = array_sum(array_column($full_data, 'closing_stock_amount')); // <-- TÍNH TỔNG GIÁ TRỊ TỒN KHO

$totalFiltered = count($full_data);
$data_for_page = array_slice($full_data, $start, $length); // Phân trang trong PHP

echo json_encode([
    "draw" => $draw,
    "recordsTotal" => $totalFiltered,
    "recordsFiltered" => $totalFiltered,
    "data" => $data_for_page,
    "total_opening" => $total_opening,
    "total_imported" => $total_imported,
    "total_exported" => $total_exported,
    "total_closing" => $total_closing,
    "total_inventory_value" => $total_inventory_value, // <-- TRẢ GIÁ TRỊ VỀ CHO GIAO DIỆN
]);
?>