<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

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;
$store_id = $_SESSION['store_id'] ?? 0;
$action = $_REQUEST['action'] ?? '';

function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0) {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}

switch ($action) {
    case 'get_imports_list':
        handle_get_imports_list($conn);
        break;
    case 'get_import_details':
        handle_get_import_details($conn);
        break;
    case 'delete_import_slip':
        handle_delete_import_slip($conn, $user_id);
        break;
    case 'search_products':
        handle_search_products($conn);
        break;
    case 'save_slip':
        handle_save_slip($conn, $user_id, $store_id);
        break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}

function handle_delete_import_slip($conn, $user_id)
{
    $slip_id = intval($_POST['slip_id'] ?? 0);

    if ($slip_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'ID phiếu nhập không hợp lệ.']);
        exit();
    }

    $conn->begin_transaction();
    try {
        $stmt_old_slip = $conn->prepare("SELECT detail_input FROM cms_input WHERE id = ? AND deleted = 0 FOR UPDATE");
        $stmt_old_slip->bind_param("i", $slip_id);
        $stmt_old_slip->execute();
        $old_slip_data = $stmt_old_slip->get_result()->fetch_assoc();
        $stmt_old_slip->close();

        if (!$old_slip_data) {
            throw new Exception("Phiếu nhập không tồn tại hoặc đã bị xóa.");
        }

        $old_products = json_decode($old_slip_data['detail_input'], true);
        $products_to_recalc = [];

        if (is_array($old_products) && !empty($old_products)) {
            
            // --- KIỂM TRA NGHIÊM NGẶT (STRICT CHECK) ---
            $slip_quantities = [];
            $slip_values = [];
            
            foreach ($old_products as $item) {
                $pid = intval($item['id'] ?? 0);
                $qty = floatval($item['quantity'] ?? 0);
                $price = floatval($item['price'] ?? 0);
                
                if ($pid > 0 && $qty > 0) {
                    $slip_quantities[$pid] = ($slip_quantities[$pid] ?? 0) + $qty;
                    $slip_values[$pid] = ($slip_values[$pid] ?? 0) + ($qty * $price);
                }
            }

            if (!empty($slip_quantities)) {
                $product_ids = array_keys($slip_quantities);
                $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
                $types = str_repeat('i', count($product_ids));
                
                // Lấy dữ liệu kho hiện tại (QUAN TRỌNG: Dùng 'ID as id' để thống nhất tên cột)
                $sql_get_stock = "SELECT ID as id, prd_name, prd_sls, prd_total_value FROM cms_products WHERE ID IN ($ids_placeholder) FOR UPDATE";
                $stmt_get_stock = $conn->prepare($sql_get_stock);
                $stmt_get_stock->bind_param($types, ...$product_ids);
                $stmt_get_stock->execute();
                $stock_result = $stmt_get_stock->get_result();
                
                $current_stocks = [];
                while($row = $stock_result->fetch_assoc()) {
                    $current_stocks[$row['id']] = $row;
                }
                $stmt_get_stock->close();

                foreach ($slip_quantities as $pid => $qty_to_remove) {
                    if (!isset($current_stocks[$pid])) continue;

                    $curr_qty = floatval($current_stocks[$pid]['prd_sls'] ?? 0);
                    $curr_val = floatval($current_stocks[$pid]['prd_total_value'] ?? 0);
                    $p_name = $current_stocks[$pid]['prd_name'] ?? "SP ID $pid";
                    $val_to_remove = $slip_values[$pid] ?? 0;
                    
                    // 1. Kiểm tra Tồn kho (Sai số cho phép 0.001)
                    if ($curr_qty < ($qty_to_remove - 0.001)) {
                        throw new Exception("CHẶN XÓA: Sản phẩm '$p_name' không đủ hàng để trả lại! (Tồn kho: $curr_qty < Lượng phiếu nhập: $qty_to_remove).");
                    }
                    
                    // 2. Kiểm tra Giá trị kho (Quan trọng để bảo vệ giá vốn)
                    // Nếu giá trị kho hiện tại < giá trị phiếu nhập -> Nghĩa là đã bán mất phần giá trị này rồi -> CHẶN
                    if ($curr_val < ($val_to_remove - 100)) { // Sai số cho phép 100 đồng
                         throw new Exception("CHẶN XÓA: Sản phẩm '$p_name' đã được tính giá vốn và xuất bán. Việc xóa phiếu này sẽ làm sai lệch giá trị kho (Âm tiền). Vui lòng hủy các phiếu xuất liên quan trước.");
                    }

                    // 3. Kiểm tra Biến động Giá vốn (Chốt chặn cuối cùng)
                    $remaining_qty = $curr_qty - $qty_to_remove;
                    $remaining_val = $curr_val - $val_to_remove;
                    
                    if ($remaining_qty > 0) {
                        $current_avg = ($curr_qty > 0) ? $curr_val / $curr_qty : 0;
                        $new_avg = $remaining_val / $remaining_qty;
                        
                        // Tính % thay đổi giá vốn
                        $percent_change = ($current_avg > 0) ? abs($new_avg - $current_avg) / $current_avg : 0;

                        // Nếu giá vốn thay đổi > 5% sau khi xóa -> CHẶN (Vì chứng tỏ cơ cấu giá vốn đã bị thay đổi lớn do bán hàng)
                        if ($percent_change > 0.05) {
                             throw new Exception("CHẶN XÓA BẢO VỆ GIÁ VỐN: Việc xóa phiếu này sẽ làm giá vốn sản phẩm '$p_name' biến động bất thường (" . round($percent_change * 100, 2) . "%). Điều này cho thấy đã có giao dịch xuất hàng ảnh hưởng. Vui lòng kiểm tra lại.");
                        }
                    }
                }
            }
            // --- HẾT KIỂM TRA ---

            $stmt_revert_stock = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls - ?, prd_total_value = prd_total_value - ? WHERE id = ?");
            foreach ($old_products as $item) {
                $product_id = intval($item['id'] ?? 0);
                $quantity = floatval($item['quantity'] ?? 0);
                $price = floatval($item['price'] ?? 0);
                $value_to_revert = $quantity * $price;

                if ($product_id > 0 && $quantity > 0) {
                    $stmt_revert_stock->bind_param("ddi", $quantity, $value_to_revert, $product_id);
                    $stmt_revert_stock->execute();
                    $products_to_recalc[] = $product_id;
                }
            }
            $stmt_revert_stock->close();
        }

        if (!empty($products_to_recalc)) {
            $sql_recalc = "UPDATE cms_products SET prd_average_cost = IF(prd_sls > 0, prd_total_value / prd_sls, 0) WHERE id = ?";
            $stmt_recalc_avg_cost = $conn->prepare($sql_recalc);
            foreach (array_unique($products_to_recalc) as $pid) {
                $stmt_recalc_avg_cost->bind_param("i", $pid);
                $stmt_recalc_avg_cost->execute();
            }
            $stmt_recalc_avg_cost->close();
        }

        $stmt_delete_slip = $conn->prepare("UPDATE cms_input SET deleted = 1, user_upd = ?, updated = NOW() WHERE id = ?");
        $stmt_delete_slip->bind_param("ii", $user_id, $slip_id);
        $stmt_delete_slip->execute();
        $stmt_delete_slip->close();

        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Xóa phiếu nhập thành công. Đã hoàn lại tồn kho.']);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit();
}

// --- CÁC HÀM KHÁC GIỮ NGUYÊN ---
function handle_save_slip($conn, $user_id, $store_id) { /* ... Code cũ ... */
    // Copy lại hàm handle_save_slip từ file trước
    $conn->begin_transaction();
    try {
        $slip_id = intval($_POST['slip_id'] ?? 0);
        $supplier_id = intval($_POST['supplier_id'] ?? 0);
        $products_list_json = $_POST['products_list'] ?? '[]';
        $products_list = json_decode($products_list_json, true);

        if (empty($products_list) || !is_array($products_list)) {
            throw new Exception("Vui lòng thêm ít nhất một sản phẩm vào phiếu nhập.");
        }

        $notes = trim($_POST['notes'] ?? '');
        $input_date_str = $_POST['input_date'] ?? date('Y-m-d H:i:s');
        $input_date = date('Y-m-d H:i:s', strtotime($input_date_str));
        $payed = floatval(str_replace([','], '', $_POST['payed'] ?? 0));

        $total_money = 0;
        $total_quantity = 0;
        $new_items_map = []; 

        foreach ($products_list as $product) {
            $qty = floatval($product['quantity'] ?? 0);
            $price = floatval($product['price'] ?? 0);
            $pid = intval($product['id'] ?? 0);

            $total_money += ($qty * $price);
            $total_quantity += $qty;
            
            if ($pid > 0) {
                if (!isset($new_items_map[$pid])) {
                    $new_items_map[$pid] = ['qty' => 0, 'price' => 0];
                }
                $new_items_map[$pid]['qty'] += $qty;
                $new_items_map[$pid]['price'] = $price; 
            }
        }
        $lack = $total_money - $payed;
        $detail_input_json = json_encode($products_list);
        $products_to_recalc = [];

        if ($slip_id > 0) {
            $stmt_old_slip = $conn->prepare("SELECT detail_input FROM cms_input WHERE id = ? FOR UPDATE");
            $stmt_old_slip->bind_param("i", $slip_id);
            $stmt_old_slip->execute();
            $old_slip_data = $stmt_old_slip->get_result()->fetch_assoc();
            $stmt_old_slip->close();

            if (!$old_slip_data) {
                throw new Exception("Không tìm thấy phiếu nhập cần sửa.");
            }

            $old_products = json_decode($old_slip_data['detail_input'], true);
            $old_items_map = [];
            foreach ($old_products as $item) {
                $pid = intval($item['id']);
                $qty = floatval($item['quantity']);
                $price = floatval($item['price']);
                if ($pid > 0) {
                    if (!isset($old_items_map[$pid])) $old_items_map[$pid] = ['qty' => 0, 'val' => 0];
                    $old_items_map[$pid]['qty'] += $qty;
                    $old_items_map[$pid]['val'] += ($qty * $price);
                }
            }

            $delta_map = []; 
            $all_pids = array_unique(array_merge(array_keys($new_items_map), array_keys($old_items_map)));

            foreach ($all_pids as $pid) {
                $old_qty = $old_items_map[$pid]['qty'] ?? 0;
                $old_val = $old_items_map[$pid]['val'] ?? 0;
                
                $new_qty = $new_items_map[$pid]['qty'] ?? 0;
                $new_price = $new_items_map[$pid]['price'] ?? 0;
                $new_val = $new_qty * $new_price;

                $qty_diff = $new_qty - $old_qty;
                $val_diff = $new_val - $old_val;

                if ($qty_diff != 0 || $val_diff != 0) {
                    $delta_map[$pid] = ['qty' => $qty_diff, 'val' => $val_diff];
                }
            }

            if (!empty($delta_map)) {
                $check_pids = [];
                foreach ($delta_map as $pid => $delta) {
                    if ($delta['qty'] < 0) { 
                        $check_pids[] = $pid;
                    }
                }

                if (!empty($check_pids)) {
                    $ids_ph = implode(',', array_fill(0, count($check_pids), '?'));
                    $types_ph = str_repeat('i', count($check_pids));
                    $sql_stock = "SELECT id, prd_name, prd_sls FROM cms_products WHERE id IN ($ids_ph) FOR UPDATE";
                    $stmt_stock = $conn->prepare($sql_stock);
                    $stmt_stock->bind_param($types_ph, ...$check_pids);
                    $stmt_stock->execute();
                    $res_stock = $stmt_stock->get_result();
                    while ($row = $res_stock->fetch_assoc()) {
                        $pid = $row['id'];
                        $current_stock = floatval($row['prd_sls']);
                        $reduce_amount = abs($delta_map[$pid]['qty']); 

                        if ($current_stock < $reduce_amount) {
                            throw new Exception("Không thể giảm số lượng! Sản phẩm '{$row['prd_name']}' tồn kho còn $current_stock, không đủ để giảm $reduce_amount.");
                        }
                    }
                    $stmt_stock->close();
                }
            }

            $sql_update_prod = "UPDATE cms_products SET prd_sls = prd_sls + ?, prd_total_value = prd_total_value + ? WHERE id = ?";
            $stmt_upd = $conn->prepare($sql_update_prod);
            
            foreach ($delta_map as $pid => $delta) {
                $stmt_upd->bind_param("ddi", $delta['qty'], $delta['val'], $pid);
                $stmt_upd->execute();
                $products_to_recalc[] = $pid;
            }
            $stmt_upd->close();

            $sql = "UPDATE cms_input SET supplier_id = ?, store_id = ?, input_date = ?, notes = ?, total_money = ?, total_quantity = ?, payed = ?, lack = ?, detail_input = ?, user_upd = ?, updated = NOW() WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("iissdddssii", $supplier_id, $store_id, $input_date, $notes, $total_money, $total_quantity, $payed, $lack, $detail_input_json, $user_id, $slip_id);
            $stmt->execute();
            $stmt->close();
            $message = "Cập nhật phiếu nhập thành công!";

        } else {
            $last_id_result = $conn->query("SELECT id FROM cms_input ORDER BY id DESC LIMIT 1");
            $last_id = $last_id_result ? ($last_id_result->fetch_row()[0] ?? 0) : 0;
            $input_code = 'PN' . str_pad($last_id + 1, 6, '0', STR_PAD_LEFT);
            
            $sql = "INSERT INTO cms_input (input_code, supplier_id, store_id, input_date, notes, total_money, total_quantity, payed, lack, detail_input, user_init, input_status, deleted, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 0, NOW())";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("siissddddsi", $input_code, $supplier_id, $store_id, $input_date, $notes, $total_money, $total_quantity, $payed, $lack, $detail_input_json, $user_id);
            $stmt->execute();
            $slip_id = $conn->insert_id;
            $stmt->close();

            $sql_update_stock = "UPDATE cms_products SET prd_sls = prd_sls + ?, prd_total_value = prd_total_value + ?, prd_origin_price = IF(ISNULL(prd_origin_price) OR prd_origin_price = 0, ?, prd_origin_price) WHERE id = ?";
            $stmt_update_stock = $conn->prepare($sql_update_stock);
            
            foreach ($new_items_map as $pid => $data) {
                $val_add = $data['qty'] * $data['price'];
                $stmt_update_stock->bind_param("dddi", $data['qty'], $val_add, $data['price'], $pid);
                $stmt_update_stock->execute();
                $products_to_recalc[] = $pid;
            }
            $stmt_update_stock->close();
            $message = "Tạo phiếu nhập mới thành công!";
        }

        if (!empty($products_to_recalc)) {
            $stmt_recalc = $conn->prepare("UPDATE cms_products SET prd_average_cost = IF(prd_sls > 0, prd_total_value / prd_sls, 0) WHERE id = ?");
            foreach (array_unique($products_to_recalc) as $pid) {
                $stmt_recalc->bind_param("i", $pid);
                $stmt_recalc->execute();
            }
            $stmt_recalc->close();
        }
        
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => $message, 'slip_id' => $slip_id]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Lỗi: ' . $e->getMessage()]);
    }
    exit();
}

function handle_get_imports_list($conn) {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    $order_column_index = intval($_POST['order'][0]['column'] ?? 3);
    $order_dir = $_POST['order'][0]['dir'] ?? 'desc';
    $columns = [1 => 'i.input_code', 2 => 's.store_name', 3 => 'i.input_date', 4 => 'u.display_name', 5 => 'i.total_money', 6 => 'i.lack'];
    $order_by_column = $columns[$order_column_index] ?? 'i.id';
    $baseQuery = "FROM cms_input i LEFT JOIN cms_users u ON i.user_init = u.id LEFT JOIN cms_stores s ON i.store_id = s.id";
    $whereClauses = ["i.deleted = 0"];
    $params = [];
    $types = "";
    if (!empty($_POST['ma_phieu'])) {
        $whereClauses[] = "i.input_code LIKE ?";
        $params[] = "%" . $_POST['ma_phieu'] . "%";
        $types .= "s";
    }
    $whereSql = " WHERE " . implode(" AND ", $whereClauses);
    $totalRecordsResult = $conn->query("SELECT COUNT(id) FROM cms_input WHERE deleted = 0");
    $recordsTotal = $totalRecordsResult ? intval($totalRecordsResult->fetch_row()[0]) : 0;
    $sqlFiltered = "SELECT COUNT(i.id) " . $baseQuery . $whereSql;
    $stmtFiltered = $conn->prepare($sqlFiltered);
    if (!empty($types)) {
        $stmtFiltered->bind_param($types, ...$params);
    }
    $stmtFiltered->execute();
    $recordsFiltered = $stmtFiltered->get_result()->fetch_row()[0] ?? 0;
    $stmtFiltered->close();
    $dataQuery = "SELECT i.id, i.input_code, i.input_status, i.input_date, i.total_money, i.lack, u.display_name AS user_name, s.store_name, i.deleted " . $baseQuery . $whereSql . " ORDER BY $order_by_column $order_dir LIMIT ?, ?";
    $limit_params = $params;
    $limit_params[] = $start;
    $limit_params[] = $length;
    $limit_types = $types . 'ii';
    $stmtData = $conn->prepare($dataQuery);
    if ($stmtData) {
        call_user_func_array([$stmtData, 'bind_param'], refValues(array_merge([$limit_types], $limit_params)));
        $stmtData->execute();
        $result = $stmtData->get_result();
        $data = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
        $stmtData->close();
    } else {
        $data = [];
    }
    echo json_encode(["draw" => $draw, "recordsTotal" => $recordsTotal, "recordsFiltered" => $recordsFiltered, "data" => $data]);
    exit();
}

function handle_get_import_details($conn) {
    $import_id = intval($_REQUEST['import_id'] ?? 0);
    if ($import_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'ID không hợp lệ.']);
        exit();
    }
    $stmt = $conn->prepare("SELECT detail_input FROM cms_input WHERE id = ?");
    $stmt->bind_param("i", $import_id);
    $stmt->execute();
    $slip = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    if (!$slip || empty($slip['detail_input'])) {
        echo json_encode(['status' => 'success', 'data' => []]);
        exit();
    }
    $slip_items_raw = json_decode($slip['detail_input'], true);
    if (!is_array($slip_items_raw) || empty($slip_items_raw)) {
        echo json_encode(['status' => 'success', 'data' => []]);
        exit();
    }
    $product_ids = array_column($slip_items_raw, 'id');
    $products_info = [];
    if (!empty($product_ids)) {
        $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
        $types = str_repeat('i', count($product_ids));
        $sql_products = "SELECT id, prd_code, prd_name FROM cms_products WHERE id IN ($ids_placeholder)";
        $stmt_products = $conn->prepare($sql_products);
        $stmt_products->bind_param($types, ...$product_ids);
        $stmt_products->execute();
        $products_result = $stmt_products->get_result();
        while ($row = $products_result->fetch_assoc()) {
            $products_info[$row['id']] = $row;
        }
        $stmt_products->close();
    }
    $response_data = [];
    foreach ($slip_items_raw as $item) {
        $product_details = $products_info[$item['id']] ?? null;
        $response_data[] = ['code' => $product_details['prd_code'] ?? 'Lỗi', 'name' => $product_details['prd_name'] ?? 'Sản phẩm không tồn tại', 'quantity' => $item['quantity'] ?? 0, 'price' => $item['price'] ?? 0, ];
    }
    echo json_encode(['status' => 'success', 'data' => $response_data]);
    exit();
}

function handle_search_products($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $sql = "SELECT p.id, p.prd_name, p.prd_code, p.prd_origin_price, p.prd_sls, u.prd_unit_name FROM cms_products p LEFT JOIN cms_products_unit u ON p.prd_unit_id = u.id WHERE (p.prd_name LIKE ? OR p.prd_code LIKE ?) AND p.deleted = 0 AND p.prd_status = 1 LIMIT 15";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("ss", $term, $term);
        $stmt->execute();
        $result = $stmt->get_result();
        $products = [];
        while ($row = $result->fetch_assoc()) {
            $products[] = ['id' => $row['id'], 'label' => $row['prd_name'] . ' (Tồn kho: ' . ($row['prd_sls'] ?? 0) . ')', 'value' => $row['prd_name'], 'name' => $row['prd_name'], 'code' => $row['prd_code'], 'price' => $row['prd_origin_price'], 'unit' => $row['prd_unit_name'] ?? ''];
        }
        $stmt->close();
        echo json_encode($products);
    } else {
        echo json_encode([]);
    }
    exit();
} 
?>