<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
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'] ?? 1;
$action = $_REQUEST['action'] ?? '';

switch ($action) {
    case 'search_products':
        handle_search_products($conn);
        break;
    case 'search_suppliers':
        handle_search_suppliers($conn);
        break;
    case 'save_slip':
        handle_save_slip($conn, $user_id, $store_id);
        break;
    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;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}

function handle_search_products($conn)
{
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $sql = "SELECT p.ID, p.prd_name, p.prd_code, p.prd_sls, u.prd_unit_name, p.prd_origin_price 
            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 20";
    
    $stmt = $conn->prepare($sql);
    if ($stmt === false) { echo json_encode([]); exit(); }
    $stmt->bind_param("ss", $term, $term);
    $stmt->execute();
    $result = $stmt->get_result();
    $products = [];
    while ($row = $result->fetch_assoc()) {
        $products[] = [
            'id' => $row['ID'], 'name' => $row['prd_name'], 'code' => $row['prd_code'],
            'inventory' => $row['prd_sls'], 'unit' => $row['prd_unit_name'], 'price' => $row['prd_origin_price'] ?? 0
        ];
    }
    $stmt->close();
    echo json_encode($products);
}

function handle_search_suppliers($conn)
{
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $sql = "SELECT s.ID, s.supplier_name, s.supplier_phone, COUNT(i.id) AS slip_count, SUM(i.total_money) AS total_spent
            FROM cms_suppliers s
            LEFT JOIN cms_input i ON s.ID = i.supplier_id AND i.deleted = 0
            WHERE (s.supplier_name LIKE ? OR s.supplier_phone LIKE ?)
            GROUP BY s.ID, s.supplier_name, s.supplier_phone LIMIT 15";
    $stmt = $conn->prepare($sql);
    if ($stmt === false) { echo json_encode([]); exit(); }
    $stmt->bind_param("ss", $term, $term);
    $stmt->execute();
    $stmt->bind_result($id, $name, $phone, $slip_count, $total_spent);
    $suppliers = [];
    while ($stmt->fetch()) {
        $suppliers[] = [
            'id' => $id, 'name' => $name, 'phone' => $phone, 'slip_count' => $slip_count, 'total_spent' => $total_spent ?? 0
        ];
    }
    $stmt->close();
    echo json_encode($suppliers);
}

function handle_save_slip($conn, $user_id, $store_id)
{
    $conn->begin_transaction();
    try {
        $slip_id = intval($_POST['slip_id'] ?? 0);
        $supplier_id = intval($_POST['supplier_id'] ?? 0);
        $products_list = json_decode($_POST['products_list'] ?? '[]', true);
        if (empty($products_list) || !is_array($products_list)) { throw new Exception("Vui lòng thêm sản phẩm."); }
        $notes = trim($_POST['notes'] ?? '');
        $input_date = date('Y-m-d H:i:s', strtotime($_POST['input_date'] ?? date('Y-m-d H:i:s')));
        $payed = floatval($_POST['payed'] ?? 0);
        $order_discount_percent = floatval($_POST['order_discount_percent'] ?? 0);

        $sub_total_after_item_discount = 0;
        $total_quantity = 0;
        foreach ($products_list as $p) {
            $line_total = (floatval($p['quantity'] ?? 0) * floatval($p['price'] ?? 0));
            $item_discount = $line_total * (floatval($p['discount_percent'] ?? 0) / 100);
            $sub_total_after_item_discount += ($line_total - $item_discount);
            $total_quantity += floatval($p['quantity'] ?? 0);
        }
        
        $order_discount_amount = $sub_total_after_item_discount * ($order_discount_percent / 100);
        $total_money = $sub_total_after_item_discount - $order_discount_amount;
        $lack = $total_money - $payed;
        $detail_input_json = json_encode($products_list);
        
        if ($slip_id > 0) {
            $stmt_old = $conn->prepare("SELECT detail_input FROM cms_input WHERE id = ? FOR UPDATE");
            $stmt_old->bind_param("i", $slip_id); $stmt_old->execute();
            $old_slip = $stmt_old->get_result()->fetch_assoc(); $stmt_old->close();
            if ($old_slip) {
                $old_products = json_decode($old_slip['detail_input'], true);
                if (is_array($old_products)) {
                    $stmt_revert = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls - ? WHERE id = ?");
                    foreach ($old_products as $item) { $stmt_revert->bind_param("di", $item['quantity'], $item['id']); $stmt_revert->execute(); }
                    $stmt_revert->close();
                }
            }
            $sql = "UPDATE cms_input SET supplier_id=?, store_id=?, input_date=?, notes=?, total_money=?, total_quantity=?, payed=?, lack=?, discount=?, detail_input=?, user_upd=?, updated=NOW() WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("iissdddddssi", $supplier_id, $store_id, $input_date, $notes, $total_money, $total_quantity, $payed, $lack, $order_discount_percent, $detail_input_json, $user_id, $slip_id);
            $message = "Cập nhật phiếu nhập thành công!";
        } else {
            $last_id_res = $conn->query("SELECT id FROM cms_input ORDER BY id DESC LIMIT 1");
            $input_code = 'PN' . str_pad(($last_id_res->fetch_row()[0] ?? 0) + 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, discount, detail_input, user_init, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("siissddddssi", $input_code, $supplier_id, $store_id, $input_date, $notes, $total_money, $total_quantity, $payed, $lack, $order_discount_percent, $detail_input_json, $user_id);
            $message = "Tạo phiếu nhập mới thành công!";
        }
        if ($stmt->execute() === false) { throw new Exception("Lỗi CSDL khi lưu phiếu: " . $stmt->error); }
        $stmt->close();
        
        $stmt_update = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls + ?, prd_origin_price = ? WHERE id = ?");
        foreach ($products_list as $p) { $stmt_update->bind_param("ddi", $p['quantity'], $p['price'], $p['id']); $stmt_update->execute(); }
        $stmt_update->close();
        
        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => $message]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Lỗi: ' . $e->getMessage()]);
    }
}

function handle_get_imports_list($conn) {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    $order_by_column_index = $_POST['order'][0]['column'] ?? 3;
    $order_by_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 = $columns[$order_by_column_index] ?? 'i.id';
    
    $base_query = "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_clauses = [];
    $params = [];
    $types = "";

    switch ($_POST['view_mode'] ?? 'all') {
        case 'debt': 
            $where_clauses[] = "i.lack > 0";
            $where_clauses[] = "i.deleted = 0";
            break;
        case 'deleted': 
            $where_clauses[] = "i.deleted = 1"; 
            break;
        default: 
            $where_clauses[] = "i.deleted = 0"; 
            break;
    }
    
    if (!empty($_POST['ma_phieu'])) {
        $where_clauses[] = "i.input_code LIKE ?";
        $params[] = "%" . $_POST['ma_phieu'] . "%";
        $types .= "s";
    }
    if (!empty($_POST['tu_ngay'])) {
        $where_clauses[] = "i.input_date >= ?";
        $params[] = $_POST['tu_ngay'] . " 00:00:00";
        $types .= "s";
    }
    if (!empty($_POST['den_ngay'])) {
        $where_clauses[] = "i.input_date <= ?";
        $params[] = $_POST['den_ngay'] . " 23:59:59";
        $types .= "s";
    }
    
    $where_sql = count($where_clauses) > 0 ? "WHERE " . implode(" AND ", $where_clauses) : "";
    
    $summary_sql = "SELECT 
                        COUNT(i.id) as total_slips, 
                        SUM(i.total_money) as total_amount, 
                        SUM(i.lack) as total_debt,
                        SUM(CASE WHEN DATE(i.input_date) = CURDATE() THEN 1 ELSE 0 END) as slips_today
                    $base_query $where_sql";
    
    $stmt_summary = $conn->prepare($summary_sql);
    if (!empty($types)) { $stmt_summary->bind_param($types, ...$params); }
    $stmt_summary->execute();
    $summary_data = $stmt_summary->get_result()->fetch_assoc();
    $stmt_summary->close();

    $total_records_res = $conn->query("SELECT COUNT(id) FROM cms_input WHERE deleted = 0");
    $recordsTotal = $total_records_res ? $total_records_res->fetch_row()[0] : 0;
    
    $stmt_filtered = $conn->prepare("SELECT COUNT(i.id) $base_query $where_sql");
    if (!empty($types)) { $stmt_filtered->bind_param($types, ...$params); }
    $stmt_filtered->execute();
    $recordsFiltered = $stmt_filtered->get_result()->fetch_row()[0];
    $stmt_filtered->close();
    
    $sql_data = "SELECT i.id, i.input_code, i.input_status, i.input_date, i.total_money, i.lack, i.deleted, u.display_name AS user_name, s.store_name $base_query $where_sql ORDER BY $order_by $order_by_dir LIMIT ?, ?";
    $stmt_data = $conn->prepare($sql_data);
    $limit_params = array_merge($params, [$start, $length]);
    $limit_types = $types . 'ii';
    if (!empty($limit_types)) { $stmt_data->bind_param($limit_types, ...$limit_params); }
    $stmt_data->execute();
    $data = $stmt_data->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_data->close();
    
    echo json_encode([
        "draw" => $draw, 
        "recordsTotal" => $recordsTotal, 
        "recordsFiltered" => $recordsFiltered, 
        "data" => $data,
        "summary" => $summary_data
    ]);
}

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 = json_decode($slip['detail_input'], true);
    if (!is_array($slip_items) || empty($slip_items)) { echo json_encode(['status' => 'success', 'data' => []]); exit(); }

    $product_ids = array_map(function($item){ return intval($item['id']); }, $slip_items);
    $products_master_data = [];

    if (!empty($product_ids)) {
        $placeholders = 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 ($placeholders)";
        $stmt_products = $conn->prepare($sql_products);
        $stmt_products->bind_param($types, ...$product_ids);
        $stmt_products->execute();
        $result = $stmt_products->get_result();
        while($row = $result->fetch_assoc()) {
            $products_master_data[$row['id']] = $row;
        }
        $stmt_products->close();
    }
    
    $response_data = [];
    foreach($slip_items as $item) {
        $product_id = intval($item['id']);
        $master_data = $products_master_data[$product_id] ?? ['prd_code' => 'Lỗi', 'prd_name' => 'Không tìm thấy'];
        
        $response_data[] = [
            'code' => $item['code'] ?? $master_data['prd_code'],
            'name' => $item['name'] ?? $master_data['prd_name'],
            'quantity' => $item['quantity'] ?? 0,
            'price' => $item['price'] ?? 0,
            'discount_percent' => $item['discount_percent'] ?? 0
        ];
    }
    
    echo json_encode(['status' => 'success', 'data' => $response_data]);
}

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 = $conn->prepare("SELECT detail_input FROM cms_input WHERE id = ? AND deleted = 0 FOR UPDATE");
        $stmt_old->bind_param("i", $slip_id);
        $stmt_old->execute();
        $old_slip = $stmt_old->get_result()->fetch_assoc();
        $stmt_old->close();

        if (!$old_slip) { throw new Exception("Không tìm thấy phiếu nhập hoặc phiếu đã được xóa trước đó."); }
        
        $old_products = json_decode($old_slip['detail_input'], true);
        if (is_array($old_products) && !empty($old_products)) {
            $stmt_revert = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls - ? WHERE id = ?");
            foreach ($old_products as $item) {
                $stmt_revert->bind_param("di", $item['quantity'], $item['id']);
                $stmt_revert->execute();
            }
            $stmt_revert->close();
        }

        $stmt_delete = $conn->prepare("UPDATE cms_input SET deleted = 1, user_upd = ?, updated = NOW() WHERE id = ?");
        $stmt_delete->bind_param("ii", $user_id, $slip_id);
        $stmt_delete->execute();
        $stmt_delete->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' => 'Lỗi: ' . $e->getMessage()]);
    }
}
?>