<?php
// File: /ajax/pos_mobile_ajax.php - FIX LỖI NAN & BỔ SUNG INFO

date_default_timezone_set('Asia/Ho_Chi_Minh');
ini_set('display_errors', 0);
error_reporting(E_ALL);

$root = dirname(__DIR__); 
if (file_exists($root . '/core/init.php')) { require_once $root . '/core/init.php'; } 
else { require_once $_SERVER['DOCUMENT_ROOT'] . '/quanlybanhang/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'] ?? '';

// --- CÁC HÀM XỬ LÝ ---

function handle_search_products($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $sql = "SELECT ID, prd_name, prd_code, prd_sell_price, prd_sell_price2, prd_sls, prd_origin_price, prd_image_url, prd_type 
            FROM cms_products WHERE (prd_name LIKE ? OR prd_code LIKE ?) AND deleted = 0 AND prd_status = 1 LIMIT 50";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $term, $term);
    $stmt->execute();
    $stmt->bind_result($id, $name, $code, $price, $price2, $inventory, $origin, $image, $type);
    $products = [];
    while ($stmt->fetch()) {
        $products[] = [
            'id' => $id, 'name' => $name, 'code' => $code, 'price_retail' => $price, 'price_wholesale' => $price2, 
            'inventory' => $inventory, 'origin_price' => $origin, 'image' => $image, 'type' => $type
        ];
    }
    echo json_encode(['status' => 'success', 'results' => $products]);
}

function handle_search_customers($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $sql = "SELECT ID, customer_name, customer_phone FROM cms_customers WHERE (customer_name LIKE ? OR customer_phone LIKE ?) LIMIT 20";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $term, $term);
    $stmt->execute();
    $stmt->bind_result($id, $name, $phone);
    $customers = [];
    while ($stmt->fetch()) {
        $customers[] = ['id' => $id, 'name' => $name, 'phone' => $phone];
    }
    echo json_encode(['status' => 'success', 'results' => $customers]);
}

function handle_save_quick_customer($conn) {
    $name = $_POST['customer_name'] ?? '';
    $phone = $_POST['customer_phone'] ?? '';
    if(empty($name)){ echo json_encode(['status' => 'error', 'message' => 'Tên bắt buộc']); return; }
    $stmt = $conn->prepare("INSERT INTO cms_customers (customer_name, customer_phone, created) VALUES (?, ?, NOW())");
    $stmt->bind_param("ss", $name, $phone);
    if ($stmt->execute()) { echo json_encode(['status' => 'success', 'customer_id' => $stmt->insert_id, 'customer_name' => $name]); } 
    else { echo json_encode(['status' => 'error', 'message' => $stmt->error]); }
}

function handle_create_temp_order($conn, $user_id, $store_id) {
    $order_id = intval($_POST['order_id'] ?? 0);
    $table_id = intval($_POST['table_id'] ?? 0);
    $customer_id = intval($_POST['customer_id'] ?? 1);
    $items = json_decode($_POST['items'] ?? '[]', true);
    
    if ($table_id == 0) { echo json_encode(['status' => 'error', 'message' => 'Chưa chọn bàn']); return; }
    if (empty($items)) { echo json_encode(['status' => 'error', 'message' => 'Giỏ hàng trống']); return; }

    $total_price = 0; $total_qty = 0; $detail_order = [];

    foreach ($items as $item) {
        $qty = floatval($item['qty'] ?? $item['quantity'] ?? 1);
        $price = floatval($item['price'] ?? 0);
        
        $total_price += ($price * $qty);
        $total_qty += $qty;

        $detail_order[] = [
            'id' => $item['id'], 
            'name' => $item['name'],
            'quantity' => $qty, 
            'price' => $price, 
            'note' => $item['note'] ?? '',
            'image' => $item['image'] ?? '',
            'type' => $item['type'] ?? 1,
            'code' => $item['code'] ?? ''
        ];
    }

    $detail_json = json_encode($detail_order, JSON_UNESCAPED_UNICODE);
    $lack = $total_price; // Tạm tính nợ = tổng tiền

    if ($order_id == 0) {
        // Check đơn cũ nếu có
        $chk = $conn->query("SELECT ID FROM cms_orders WHERE table_id=$table_id AND order_status=0 AND deleted=0 LIMIT 1");
        if ($chk->num_rows > 0) $order_id = $chk->fetch_row()[0];
    }

    if ($order_id > 0) {
        $sql = "UPDATE cms_orders SET customer_id=?, total_money=?, total_quantity=?, lack=?, detail_order=?, updated=NOW() WHERE ID=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ididsi", $customer_id, $total_price, $total_qty, $lack, $detail_json, $order_id);
        $msg = "Cập nhật thành công";
    } else {
        $code = 'DH' . time();
        $sql = "INSERT INTO cms_orders (output_code, store_id, customer_id, table_id, created, sell_date, user_init, total_money, total_quantity, lack, detail_order, order_status) VALUES (?, ?, ?, ?, NOW(), NOW(), ?, ?, ?, ?, ?, 0)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("siisiddds", $code, $store_id, $customer_id, $table_id, $user_id, $total_price, $total_qty, $lack, $detail_json);
        $msg = "Tạo đơn thành công";
    }

    if ($stmt->execute()) {
        $conn->query("UPDATE cms_tables SET table_status = 1 WHERE id = $table_id");
        echo json_encode(['status' => 'success', 'message' => $msg]);
    } else {
        echo json_encode(['status' => 'error', 'message' => $stmt->error]);
    }
}

// --- HÀM LẤY ĐƠN CŨ (QUAN TRỌNG: LẤY THÊM TÊN BÀN, KHU VỰC) ---
function handle_get_table_order($conn) {
    $table_id = intval($_GET['table_id']);
    
    // Lấy thông tin Đơn hàng + Khách hàng + Tên bàn + Tên khu vực
    $sql = "SELECT o.*, c.customer_name, c.customer_phone, t.table_name, a.area_name 
            FROM cms_orders o 
            LEFT JOIN cms_customers c ON o.customer_id = c.ID
            LEFT JOIN cms_tables t ON o.table_id = t.id
            LEFT JOIN cms_areas a ON t.area_id = a.id
            WHERE o.table_id = $table_id AND o.order_status = 0 AND o.deleted = 0 LIMIT 1";
            
    $res = $conn->query($sql);
    
    if($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        // Xử lý JSON để tránh lỗi NaN
        $items = json_decode($row['detail_order'], true);
        $clean_items = [];
        if (is_array($items)) {
            foreach ($items as $i) {
                $clean_items[] = [
                    'id' => intval($i['id']),
                    'name' => $i['name'],
                    'price' => floatval($i['price']),
                    'qty' => floatval($i['quantity'] ?? $i['qty']), // Đồng bộ tên biến
                    'note' => $i['note'] ?? '',
                    'image' => $i['image'] ?? '',
                    'type' => $i['type'] ?? 1
                ];
            }
        }
        $row['items'] = $clean_items;
        echo json_encode(['status' => 'success', 'data' => $row]);
    } else {
        echo json_encode(['status' => 'empty']);
    }
}

// Các hàm khác giữ nguyên...

switch ($action) {
    case 'search_products': handle_search_products($conn); break;
    case 'search_customers': handle_search_customers($conn); break;
    case 'save_quick_customer': handle_save_quick_customer($conn); break;
    case 'create_temp_order': handle_create_temp_order($conn, $user_id, $store_id); break; 
    case 'get_table_order': handle_get_table_order($conn); break;
    default: echo json_encode(['status' => 'error', 'message' => 'Action not found']); break;
}
?>