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

require_once __DIR__ . '/../config/database.php';
header('Content-Type: application/json; charset=utf-8');

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

$user_id = $_SESSION['user_id'] ?? 0;
$action = $_POST['action'] ?? $_GET['action'] ?? '';

function process_order_saving($conn, $user_id, $is_edit = false)
{
    $store_id = 0;
    if (isset($_SESSION['store_id'])) {
        $store_id = intval($_SESSION['store_id']);
    } elseif ($user_id > 0) {
        $stmt_user = $conn->prepare("SELECT store_id FROM cms_users WHERE id = ?");
        $stmt_user->bind_param("i", $user_id);
        $stmt_user->execute();
        $user_result = $stmt_user->get_result();
        if ($user_row = $user_result->fetch_assoc()) {
            $store_id = intval($user_row['store_id']);
            $_SESSION['store_id'] = $store_id;
        }
        $stmt_user->close();
    }

    if ($store_id <= 0) {
        throw new Exception("Không tìm thấy thông tin kho làm việc của nhân viên. Vui lòng kiểm tra lại tài khoản.");
    }

    $order_id = intval($_POST['order_id'] ?? 0);
    $customer_id = intval($_POST['customer_id'] ?? 1);
    $notes = trim($_POST['notes'] ?? '');
    $items_json = $_POST['items'] ?? '[]';
    $items = json_decode($items_json, true);
    $discount_value = floatval(str_replace(',', '.', $_POST['discount_value'] ?? 0));
    $discount_type = $_POST['discount_type'] ?? 'percent';
    $vat_percent = intval($_POST['vat'] ?? 0);
    $payment_method = intval($_POST['payment_method'] ?? 1);
    $sell_date = $_POST['sale_date'] ? date('Y-m-d H:i:s', strtotime($_POST['sale_date'])) : date('Y-m-d H:i:s');


    if (empty($items) || !is_array($items)) {
        throw new Exception("Đơn hàng phải có ít nhất một sản phẩm.");
    }

    $conn->begin_transaction();
    try {
        $old_items_map = [];
        if ($is_edit && $order_id > 0) {
            $stmt_old = $conn->prepare("SELECT detail_order FROM cms_orders WHERE ID = ? FOR UPDATE");
            $stmt_old->bind_param("i", $order_id);
            $stmt_old->execute();
            $old_order_data = $stmt_old->get_result()->fetch_assoc();
            $stmt_old->close();
            if ($old_order_data && !empty($old_order_data['detail_order'])) {
                $old_items = json_decode($old_order_data['detail_order'], true);
                if (is_array($old_items)) {
                    foreach ($old_items as $item) {
                        $old_items_map[intval($item['id'])] = intval($item['quantity']);
                    }
                }
            }
        }

        $total_price_before_discount = 0;
        $total_price_after_item_discount = 0;
        $total_origin_price_for_db = 0;
        $total_quantity = 0;
        $total_discount_on_items = 0;
        $items_to_save = [];
        $stock_changes = [];

        foreach ($items as $item) {
            $p_id = intval($item['id']);
            $p_qty_new = intval($item['quantity']);
            $p_price = floatval($item['price']);
            $p_discount_percent = floatval($item['percent'] ?? 0);
            $p_note = trim($item['note'] ?? '');

            $stmt_prod_info = $conn->prepare("SELECT prd_origin_price, prd_sls, prd_name, prd_code FROM cms_products WHERE ID = ? FOR UPDATE");
            $stmt_prod_info->bind_param("i", $p_id);
            $stmt_prod_info->execute();
            $prod_info = $stmt_prod_info->get_result()->fetch_assoc();
            $stmt_prod_info->close();

            $p_cost = floatval($prod_info['prd_origin_price'] ?? 0);
            $current_inventory = intval($prod_info['prd_sls'] ?? 0);

            if ($p_price < $p_cost) {
                throw new Exception("Giá bán của sản phẩm '" . ($prod_info['prd_name'] ?? $p_id) . "' không được thấp hơn giá vốn.");
            }

            $p_qty_old = $old_items_map[$p_id] ?? 0;
            $inventory_available_for_this_transaction = $current_inventory + $p_qty_old;

            if ($p_qty_new > $inventory_available_for_this_transaction) {
                throw new Exception("Số lượng bán (" . $p_qty_new . ") của sản phẩm '" . ($prod_info['prd_name'] ?? $p_id) . "' vượt quá tồn kho (" . $inventory_available_for_this_transaction . ").");
            }
            $stock_changes[$p_id] = $p_qty_old - $p_qty_new;

            $line_original_price = $p_qty_new * $p_price;
            $line_item_discount_amount = $line_original_price * ($p_discount_percent / 100);
            $line_final_price = $line_original_price - $line_item_discount_amount;

            $total_price_before_discount += $line_original_price;
            $total_price_after_item_discount += $line_final_price;
            $total_discount_on_items += $line_item_discount_amount;
            $total_origin_price_for_db += ($p_qty_new * $p_cost);
            $total_quantity += $p_qty_new;

            $items_to_save[] = [
                'id' => $p_id,
                'code' => $prod_info['prd_code'] ?? 'N/A',
                'name' => $item['name'] ?? $prod_info['prd_name'],
                'quantity' => $p_qty_new,
                'price' => $p_price,
                'origin_price' => $p_cost,
                'percent' => $p_discount_percent,
                'discount' => $line_item_discount_amount,
                'note' => $p_note
            ];
        }

        foreach ($old_items_map as $p_id => $p_qty) {
            if (!isset($stock_changes[$p_id])) {
                $stock_changes[$p_id] = $p_qty;
            }
        }

        if(!empty($stock_changes)) {
            $stmt_stock = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls + ? WHERE ID = ?");
            foreach ($stock_changes as $p_id => $qty_change) {
                if ($qty_change != 0) {
                    $stmt_stock->bind_param("ii", $qty_change, $p_id);
                    $stmt_stock->execute();
                }
            }
            $stmt_stock->close();
        }

        $discount_order_amount = ($discount_type === 'fixed') ? $discount_value : ($total_price_after_item_discount * ($discount_value / 100));
        $discount_order_percent = ($discount_type === 'percent') ? $discount_value : 0;
        
        $price_after_order_discount = $total_price_after_item_discount - $discount_order_amount;
        $vat_money = $price_after_order_discount * ($vat_percent / 100);
        $final_total_money = $price_after_order_discount + $vat_money;
        
        // --- START SỬA LỖI ---
        $customer_pay_provided = ($_POST['customer_pay'] !== '' && $_POST['customer_pay'] !== null);
    
        if (!$customer_pay_provided) {
            if ($payment_method == 2) { // Giả định 2 là Chuyển khoản/QR
                $customer_pay = 0; // Gán bằng 0 để tạo nợ và hiển thị QR
            } else {
                $customer_pay = $final_total_money; // Giữ logic cũ cho tiền mặt
            }
        } else {
            $customer_pay = floatval(str_replace('.', '', $_POST['customer_pay'] ?? ''));
        }
        // --- END SỬA LỖI ---

        $lack = $final_total_money - $customer_pay;
        $detail_order_json = json_encode($items_to_save, JSON_UNESCAPED_UNICODE);
        
        $output_code_for_display = '';

        if ($is_edit && $order_id > 0) {
            $sql_order = "UPDATE cms_orders SET customer_id=?, store_id=?, sell_date=?, notes=?, total_price=?, total_origin_price=?, total_quantity=?, total_money=?, total_discount=?, discount_item=?, discount_percent=?, vat=?, customer_pay=?, lack=?, detail_order=?, user_upd=?, payment_method=?, order_status=1 WHERE ID=?";
            $stmt_order = $conn->prepare($sql_order);
            $stmt_order->bind_param("iissddiddddiddsiii", $customer_id, $store_id, $sell_date, $notes, $total_price_after_item_discount, $total_origin_price_for_db, $total_quantity, $final_total_money, $discount_order_amount, $total_discount_on_items, $discount_order_percent, $vat_percent, $customer_pay, $lack, $detail_order_json, $user_id, $payment_method, $order_id);
        } else {
            $last_id_result = $conn->query("SELECT id FROM cms_orders ORDER BY id DESC LIMIT 1");
            $last_id = $last_id_result->fetch_row()[0] ?? 0;
            $output_code = 'PXK' . str_pad($last_id + 1, 7, '0', STR_PAD_LEFT);
            $output_code_for_display = $output_code;
            $sql_order = "INSERT INTO cms_orders (output_code, customer_id, store_id, sell_date, notes, total_price, total_origin_price, total_quantity, total_money, total_discount, discount_item, discount_percent, vat, customer_pay, lack, detail_order, user_init, created, order_status, payment_method) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), 1, ?)";
            $stmt_order = $conn->prepare($sql_order);
            $stmt_order->bind_param("siissddiddddiddsii", $output_code, $customer_id, $store_id, $sell_date, $notes, $total_price_after_item_discount, $total_origin_price_for_db, $total_quantity, $final_total_money, $discount_order_amount, $total_discount_on_items, $discount_order_percent, $vat_percent, $customer_pay, $lack, $detail_order_json, $user_id, $payment_method);
        }

        if ($stmt_order->execute() === false) {
            throw new Exception("Lỗi CSDL khi lưu đơn hàng: " . $stmt_order->error);
        }

        if (!$is_edit) $order_id = $conn->insert_id;
        $stmt_order->close();

        $customer_name = 'Khách lẻ';
        $customer_phone = '';
        if ($customer_id > 1) {
            $stmt_cust = $conn->prepare("SELECT customer_name, customer_phone FROM cms_customers WHERE ID = ?");
            if ($stmt_cust) {
                $stmt_cust->bind_param("i", $customer_id);
                $stmt_cust->execute();
                $cust_result = $stmt_cust->get_result()->fetch_assoc();
                if ($cust_result) {
                    $customer_name = $cust_result['customer_name'];
                    $customer_phone = $cust_result['customer_phone'];
                }
                $stmt_cust->close();
            }
        }

        if ($is_edit) {
            $stmt_code = $conn->prepare("SELECT output_code FROM cms_orders WHERE ID = ?");
            if($stmt_code) {
                $stmt_code->bind_param("i", $order_id);
                $stmt_code->execute();
                $code_result = $stmt_code->get_result()->fetch_assoc();
                if($code_result) {
                    $output_code_for_display = $code_result['output_code'];
                }
                $stmt_code->close();
            }
        }

        // --- SỬA LỖI SQL (xóa ký tự lạ) ---
        $stmt_display_update = $conn->prepare("UPDATE cms_payment_display SET
            order_id = ?,
            order_code = ?,
            customer_name = ?,
            customer_phone = ?,
            total_amount = ?,
            payment_status = 'waiting'
        WHERE id = 1");
        
        if ($stmt_display_update) {
            $stmt_display_update->bind_param(
                "isssd",
                $order_id,
                $output_code_for_display,
                $customer_name,
                $customer_phone,
                $final_total_money
            );
            if (!$stmt_display_update->execute()) {
                throw new Exception("Lỗi khi cập nhật bảng hiển thị: " . $stmt_display_update->error);
            }
            $stmt_display_update->close();
        } else {
            throw new Exception("Lỗi khi chuẩn bị câu lệnh cập nhật hiển thị: " . $conn->error);
        }
        
        $conn->commit();
        $message = $is_edit ? "Cập nhật đơn hàng thành công!" : "Lưu đơn hàng thành công!";
        echo json_encode(['status' => 'success', 'message' => $message, 'order_id' => $order_id]);
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Lỗi: ' . $e->getMessage()]);
    }
}

function handle_search_products($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $sql = "SELECT p.ID, p.prd_name, p.prd_code, 
                    p.prd_sell_price, 
                    p.prd_sell_price2,
                    p.prd_sls, 
                    p.prd_origin_price, 
                    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 20";
    
    $stmt = $conn->prepare($sql);
    $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'], 
            'price_retail' => $row['prd_sell_price'], 
            'price_wholesale' => $row['prd_sell_price2'],
            'inventory' => $row['prd_sls'], 
            'origin_price' => $row['prd_origin_price'], 
            'unit' => $row['prd_unit_name']
        ];
    }
    $stmt->close();
    echo json_encode($products);
}

function handle_search_customers($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $sql = "SELECT c.ID, c.customer_name, c.customer_phone, c.customer_code, c.customer_group,
                    COUNT(o.ID) AS order_count, 
                    SUM(o.total_money) AS total_spent, 
                    SUM(o.lack) AS total_debt 
            FROM cms_customers c 
            LEFT JOIN cms_orders o ON c.ID = o.customer_id AND o.deleted = 0 
            WHERE (c.customer_name LIKE ? OR c.customer_phone LIKE ? OR c.customer_code LIKE ?) 
            GROUP BY c.ID, c.customer_name, c.customer_phone, c.customer_code, c.customer_group 
            LIMIT 15";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sss", $term, $term, $term);
    $stmt->execute();
    $result = $stmt->get_result();
    $customers = [];
    while ($row = $result->fetch_assoc()) {
        $customers[] = [
            'id' => $row['ID'], 
            'name' => $row['customer_name'], 
            'phone' => $row['customer_phone'], 
            'code' => $row['customer_code'], 
            'customer_group' => $row['customer_group'],
            'order_count' => $row['order_count'], 
            'total_spent' => $row['total_spent'] ?? 0, 
            'total_debt' => $row['total_debt'] ?? 0
        ];
    }
    $stmt->close();
    echo json_encode($customers);
}

function handle_add_customer($conn) {
    $name = trim($_POST['customer_name'] ?? '');
    $phone = trim($_POST['customer_phone'] ?? '');
    $address = trim($_POST['customer_address'] ?? '');

    if (empty($name)) {
        echo json_encode(['status' => 'error', 'message' => 'Tên khách hàng là bắt buộc.']);
        return;
    }

    $conn->begin_transaction();
    try {
        $last_id_result = $conn->query("SELECT id FROM cms_customers ORDER BY id DESC LIMIT 1");
        $last_id = $last_id_result->fetch_row()[0] ?? 0;
        $customer_code = 'KH' . str_pad($last_id + 1, 5, '0', STR_PAD_LEFT);

        $stmt = $conn->prepare("INSERT INTO cms_customers (customer_code, customer_name, customer_phone, customer_addr, created, customer_group) VALUES (?, ?, ?, ?, NOW(), 1)");
        $stmt->bind_param("ssss", $customer_code, $name, $phone, $address);
        
        if ($stmt->execute()) {
            $new_customer_id = $conn->insert_id;
            $conn->commit();
            echo json_encode([
                'status' => 'success',
                'message' => 'Thêm khách hàng thành công!',
                'customer' => [
                    'id' => $new_customer_id,
                    'name' => $name,
                    'phone' => $phone,
                    'address' => $address,
                    'code' => $customer_code,
                    'customer_group' => 1
                ]
            ]);
        } else {
            throw new Exception("Không thể lưu khách hàng vào CSDL.");
        }
        $stmt->close();
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Lỗi: ' . $e->getMessage()]);
    }
}

switch ($action) {
    case 'save_order':
        process_order_saving($conn, $user_id, false);
        break;
    case 'edit_order':
        process_order_saving($conn, $user_id, true);
        break;
    case 'search_products':
        handle_search_products($conn);
        break;
    case 'search_customers':
        handle_search_customers($conn);
        break;
    case 'add_customer':
        handle_add_customer($conn);
        break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}
?>