<?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) {
        echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy thông tin kho làm việc.']);
        exit;
    }

    $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 = !empty($_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)) {
        echo json_encode(['status' => 'error', 'message' => 'Đơn hàng phải có ít nhất một sản phẩm.']);
        exit;
    }

    $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 = [];

        $product_ids = array_column($items, 'id');
        $products_info_map = [];
        if (!empty($product_ids)) {
            $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
            $types = str_repeat('i', count($product_ids));
            $sql_p = "SELECT ID, prd_origin_price, prd_sls, prd_name, prd_code, prd_image_url, prd_size, prd_color FROM cms_products WHERE ID IN ($ids_placeholder)";
            $stmt_p = $conn->prepare($sql_p);
            if ($stmt_p) {
                $stmt_p->bind_param($types, ...$product_ids);
                $stmt_p->execute();
                $res_p = $stmt_p->get_result();
                while ($row = $res_p->fetch_assoc()) {
                    $products_info_map[$row['ID']] = $row;
                }
                $stmt_p->close();
            }
        }

        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'] ?? '');

            $prod_info = $products_info_map[$p_id] ?? null;
            if (!$prod_info) { throw new Exception("Sản phẩm ID $p_id không tồn tại."); }

            $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'] . "' thấp hơn giá vốn."); }

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

            if ($p_qty_new > $inventory_available) { throw new Exception("Sản phẩm '" . $prod_info['prd_name'] . "' không đủ tồn kho."); }
            
            $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'],
                'image' => $prod_info['prd_image_url'] ?? '',
                'size' => $prod_info['prd_size'] ?? '',
                'color' => $prod_info['prd_color'] ?? '',
                '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;
        
        // --- LOGIC TIỀN KHÁCH ĐƯA ---
        $customer_pay_input = $_POST['customer_pay'] ?? '';
        $customer_pay_provided = ($customer_pay_input !== '' && $customer_pay_input !== null);
        
        if (!$customer_pay_provided) {
            // Mặc định là 0 để tính nợ -> Hiện QR
            $customer_pay = 0; 
        } else {
            $customer_pay = floatval(str_replace('.', '', $customer_pay_input));
        }

        $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_res = $conn->query("SELECT id FROM cms_orders ORDER BY id DESC LIMIT 1");
            $last_id = ($last_id_res && $last_id_res->num_rows > 0) ? $last_id_res->fetch_row()[0] : 0;
            $output_code = 'PXK' . str_pad($last_id + 1, 6, '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);
            if (!$stmt_order) { throw new Exception("Lỗi chuẩn bị SQL: " . $conn->error); }
            $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()) { throw new Exception("Lỗi 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();
            }
        }

        // --- CẬP NHẬT BẢNG HIỂN THỊ (MÀN HÌNH KHÁCH) ---
        // Nếu còn nợ -> Waiting (Hiện QR). Nếu hết nợ -> Paid (Cám ơn).
        $display_status = ($lack > 0) ? 'waiting' : 'paid';

        $stmt_display = $conn->prepare("UPDATE cms_payment_display SET order_id=?, order_code=?, customer_name=?, customer_phone=?, total_amount=?, payment_status=? WHERE id=1");
        if ($stmt_display) {
            $stmt_display->bind_param("isssds", $order_id, $output_code_for_display, $customer_name, $customer_phone, $final_total_money, $display_status);
            $stmt_display->execute();
            $stmt_display->close();
        }
        
        $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()]);
    }
}

// ... (Các hàm handle_search_products, search_customers, add_customer GIỮ NGUYÊN NHƯ CŨ) ...
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, p.prd_image_url, p.prd_size, p.prd_color, 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'], 
            'image' => $row['prd_image_url'], 'size' => $row['prd_size'], 'color' => $row['prd_color'], '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; }
    $res = $conn->query("SELECT id FROM cms_customers ORDER BY id DESC LIMIT 1");
    $last_id = ($res->fetch_row()[0] ?? 0) + 1;
    $code = 'KH' . str_pad($last_id, 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", $code, $name, $phone, $address);
    if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Thêm khách hàng thành công!', 'customer' => ['id' => $stmt->insert_id, 'name' => $name, 'phone' => $phone, 'address' => $address, 'code' => $code, 'customer_group' => 1]]);
    } else { echo json_encode(['status' => 'error', 'message' => 'Lỗi DB: ' . $stmt->error]); }
    $stmt->close();
}

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;
}
?>