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

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

switch ($action) {
    case 'get_imports_list':
        handle_get_imports_list($conn, $group_id, $store_id);
        break;
    case 'get_import_details':
        handle_get_import_details($conn);
        break;
    case 'delete_import_slip':
        handle_delete_import_slip($conn);
        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_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';

    // Sửa lại ánh xạ cột cho đúng với bảng hiển thị (cột 0 là nút '+')
    $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';

    $base_sql = "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";
    $where_conditions = [];
    $params = [];
    $types = "";

    $view_mode = $_POST['view_mode'] ?? 'all';
    switch ($view_mode) {
        case 'deleted': $where_conditions[] = "i.deleted = 1"; break;
        case 'debt': $where_conditions[] = "i.deleted = 0 AND i.lack > 0"; break;
        default: $where_conditions[] = "i.deleted = 0"; break;
    }
    
    if (!empty($_POST['ma_phieu'])) { $where_conditions[] = "i.input_code LIKE ?"; $params[] = "%{$_POST['ma_phieu']}%"; $types .= "s"; }
    if (!empty($_POST['tu_ngay'])) { $where_conditions[] = "i.input_date >= ?"; $params[] = "{$_POST['tu_ngay']} 00:00:00"; $types .= "s"; }
    if (!empty($_POST['den_ngay'])) { $where_conditions[] = "i.input_date <= ?"; $params[] = "{$_POST['den_ngay']} 23:59:59"; $types .= "s"; }
    
    $where_sql = " WHERE " . implode(" AND ", $where_conditions);

    // Đếm tổng số phiếu và tính toán tóm tắt
    $sql_summary = "SELECT COUNT(i.id) as total_slips, SUM(i.total_money) as total_amount, SUM(i.lack) as total_debt " . $base_sql . $where_sql;
    $stmt_summary = $conn->prepare($sql_summary);
    if ($types) $stmt_summary->bind_param($types, ...$params);
    $stmt_summary->execute();
    $summary_row = $stmt_summary->get_result()->fetch_assoc();
    $stmt_summary->close();
    $recordsFiltered = intval($summary_row['total_slips'] ?? 0);
    $recordsTotal = $recordsFiltered; // Cho 2 giá trị này bằng nhau để không gây nhầm lẫn

    // SỬA LỖI Ở ĐÂY: Lấy đầy đủ các cột cần thiết
    $sql_data = "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 " . $base_sql . $where_sql . " ORDER BY $order_by_column $order_dir LIMIT ?, ?";
    $data_params = $params; array_push($data_params, $start, $length);
    $data_types = $types . 'ii';
    
    $stmt_data = $conn->prepare($sql_data);
    if ($stmt_data === false) { die("Lỗi SQL (DATA): " . $conn->error); }
    $stmt_data->bind_param($data_types, ...$data_params);
    $stmt_data->execute();
    $data = $stmt_data->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_data->close();
    
    array_walk_recursive($data, function (&$item) { if (is_string($item)) $item = mb_convert_encoding($item, 'UTF-8', 'UTF-8'); });

    echo json_encode(["draw" => $draw, "recordsTotal" => $recordsTotal, "recordsFiltered" => $recordsFiltered, "data" => $data, "summary" => ["total_slips" => $summary_row['total_slips'] ?? 0, "total_amount" => $summary_row['total_amount'] ?? 0, "total_debt" => $summary_row['total_debt'] ?? 0]], JSON_NUMERIC_CHECK | JSON_INVALID_UTF8_SUBSTITUTE);
    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'])) {
        $products_in_slip = json_decode($slip['detail_input'], true);
        if (is_array($products_in_slip)) {
            $product_ids = array_filter(array_column($products_in_slip, 'id'));
            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_info_result = $stmt_products->get_result();
                $products_info = [];
                while($row = $products_info_result->fetch_assoc()) { $products_info[$row['id']] = $row; }
                $stmt_products->close();
                foreach($products_in_slip as &$item) {
                    if (isset($products_info[$item['id']])) {
                        $item['name'] = $item['name'] ?? $products_info[$item['id']]['prd_name'];
                        $item['code'] = $item['code'] ?? $products_info[$item['id']]['prd_code'];
                    }
                }
            }
        }
        echo json_encode(['status' => 'success', 'data' => $products_in_slip]);
    } else { echo json_encode(['status' => 'success', 'data' => []]); }
    exit();
}

function handle_delete_import_slip($conn) {
    $slip_id = intval($_POST['slip_id'] ?? 0);
    if ($slip_id <= 0) { echo json_encode(['status' => 'error', 'message' => 'ID phiếu không hợp lệ.']); exit(); }
    $conn->begin_transaction();
    try {
        $stmt_get = $conn->prepare("SELECT detail_input, input_status FROM cms_input WHERE id = ? AND deleted = 0");
        $stmt_get->bind_param("i", $slip_id); $stmt_get->execute();
        $slip = $stmt_get->get_result()->fetch_assoc(); $stmt_get->close();
        if (!$slip || $slip['input_status'] == 2) { throw new Exception("Phiếu nhập không tồn tại hoặc đã được hủy trước đó."); }
        if (!empty($slip['detail_input'])) {
            $products_in_slip = json_decode($slip['detail_input'], true);
            if(is_array($products_in_slip)) {
                $stmt_revert_stock = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls - ? WHERE id = ?");
                foreach ($products_in_slip as $item) {
                    $quantity = floatval($item['quantity'] ?? 0); $product_id = intval($item['id'] ?? 0);
                    if ($product_id > 0 && $quantity > 0) {
                        $stmt_revert_stock->bind_param("di", $quantity, $product_id);
                        $stmt_revert_stock->execute();
                    }
                }
                $stmt_revert_stock->close();
            }
        }
        $stmt_cancel = $conn->prepare("UPDATE cms_input SET deleted = 1, input_status = 2 WHERE id = ?");
        $stmt_cancel->bind_param("i", $slip_id); $stmt_cancel->execute(); $stmt_cancel->close();
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Hủy phiếu nhập và trả lại tồn kho thành công!']);
    } catch (Exception $e) { $conn->rollback(); echo json_encode(['status' => 'error', 'message' => 'Lỗi trong quá trình hủy phiếu: ' . $e->getMessage()]); }
    exit();
}

function handle_search_products($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $term_exact = $_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 = ?) AND p.deleted = 0 AND p.prd_status = 1 LIMIT 15";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("ss", $term, $term_exact);
        $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();
}

function handle_save_slip($conn, $user_id, $store_id) {
    $slip_id = intval($_POST['slip_id'] ?? 0);
    $supplier_id_raw = intval($_POST['supplier_id'] ?? 0);
    $supplier_id = ($supplier_id_raw > 0) ? $supplier_id_raw : null;
    $products_list = json_decode($_POST['products_list'] ?? '[]', true);
    if (empty($products_list) || !is_array($products_list)) { echo json_encode(['status' => 'error', 'message' => 'Vui lòng thêm ít nhất một sản phẩm.']); exit(); }
    $notes = trim($_POST['notes'] ?? '');
    $payed = floatval($_POST['payed'] ?? 0);
    $input_date = date('Y-m-d H:i:s');
    if (!empty($_POST['input_date'])) { try { $input_date = (new DateTime($_POST['input_date']))->format('Y-m-d H:i:s'); } catch (Exception $e) {} }
    $total_price = 0; $total_quantity = 0;
    foreach ($products_list as $p) {
        $quantity = floatval($p['quantity'] ?? 0);
        $price = floatval($p['price'] ?? 0);
        $discount_percent = floatval($p['discount_percent'] ?? 0);
        $line_total = $quantity * $price;
        $discount_amount = $line_total * ($discount_percent / 100);
        $total_price += $line_total - $discount_amount;
        $total_quantity += $quantity;
    }
    $discount = 0;
    $total_money = $total_price;
    $lack = $total_money - $payed;
    $detail_input_json = json_encode($products_list);
    $conn->begin_transaction();
    try {
        if ($slip_id > 0) {
            $sql = "UPDATE cms_input SET supplier_id=?, input_date=?, notes=?, total_price=?, total_quantity=?, discount=?, payed=?, lack=?, detail_input=?, user_upd=?, total_money=? WHERE id=?";
            $stmt = $conn->prepare($sql);
            if ($stmt === false) { throw new Exception("Lỗi SQL (UPDATE): " . $conn->error); }
            $stmt->bind_param("isdddddssidi", $supplier_id, $input_date, $notes, $total_price, $total_quantity, $discount, $payed, $lack, $detail_input_json, $user_id, $total_money, $slip_id);
            $stmt->execute();
            $new_slip_id = $slip_id;
        } 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_price, total_quantity, discount, payed, lack, detail_input, user_init, input_status, total_money) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)";
            $stmt = $conn->prepare($sql);
            if ($stmt === false) { throw new Exception("Lỗi SQL (INSERT): " . $conn->error); }
            $stmt->bind_param("siisddddddssi", $input_code, $supplier_id, $store_id, $input_date, $notes, $total_price, $total_quantity, $discount, $payed, $lack, $detail_input_json, $user_id, $total_money);
            $stmt->execute();
            $new_slip_id = $conn->insert_id;
            $stmt_update_stock = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls + ? WHERE id = ?");
            foreach ($products_list as $item) {
                $quantity = floatval($item['quantity'] ?? 0); $product_id = intval($item['id'] ?? 0);
                if($product_id > 0 && $quantity > 0) {
                    $stmt_update_stock->bind_param("di", $quantity, $product_id);
                    $stmt_update_stock->execute();
                }
            }
            $stmt_update_stock->close();
        }
        $stmt->close();
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Lưu phiếu nhập thành công!', 'slip_id' => $new_slip_id]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Lỗi khi lưu phiếu nhập: ' . $e->getMessage()]);
    }
    exit();
}
?>