<?php
// Bật hiển thị lỗi để debug (sau này ổn định có thể tắt đi)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Cách 1: Dùng DOCUMENT_ROOT (Khuyến nghị)
$root = $_SERVER['DOCUMENT_ROOT'];
if (file_exists($root . '/quanlybanhang/core/init.php')) {
    require_once $root . '/quanlybanhang/core/init.php';
} elseif (file_exists($root . '/core/init.php')) {
    require_once $root . '/core/init.php';
} else {
    // Fallback: Thử đường dẫn tương đối cũ nhưng sửa lại cho đúng cấp thư mục
    // File này ở: /quanlybanhang/ajax/pos_mobile_ajax.php
    // init.php ở: /quanlybanhang/core/init.php
    // => Cần lùi lại 1 cấp (..) để ra khỏi 'ajax', rồi vào 'core'
    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'] ?? '';

// 1. TÌM SẢN PHẨM (Đã thêm bắt lỗi SQL)
function handle_search_products($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    
    // Lưu ý: Đảm bảo trong Database bảng cms_products đã có các cột prd_image_url, prd_size, prd_color
    $sql = "SELECT ID, prd_name, prd_code, prd_sell_price, prd_sell_price2, prd_sls, prd_origin_price, prd_image_url, prd_size, prd_color 
            FROM cms_products 
            WHERE (prd_name LIKE ? OR prd_code LIKE ?) 
            AND deleted = 0 AND prd_status = 1 LIMIT 30";
            
    $stmt = $conn->prepare($sql);
    
    // [FIX LỖI 500] Kiểm tra nếu SQL sai (do thiếu cột hoặc sai tên bảng)
    if (!$stmt) {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi SQL Tìm SP: ' . $conn->error]);
        exit();
    }

    $stmt->bind_param("ss", $term, $term);
    $stmt->execute();
    $stmt->bind_result($id, $name, $code, $price, $price2, $inventory, $origin, $image, $size, $color);
    
    $products = [];
    while ($stmt->fetch()) {
        $products[] = [
            'id' => $id, 
            'name' => $name, 
            'code' => $code, 
            'price_retail' => $price, 
            'price_wholesale' => $price2, 
            'inventory' => $inventory, 
            'origin_price' => $origin, 
            'image' => $image,
            'size' => $size,
            'color' => $color,
            'unit' => 'Cái'
        ];
    }
    $stmt->close();
    echo json_encode(['status' => 'success', 'results' => $products]);
}

// 2. TÌM KHÁCH HÀNG (Đã thêm bắt lỗi SQL)
function handle_search_customers($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    $sql = "SELECT c.ID, c.customer_name, c.customer_phone, c.customer_group,
                    (SELECT SUM(total_money) FROM cms_orders WHERE customer_id = c.ID AND deleted=0 AND order_status=1) as total_spent,
                    (SELECT SUM(lack) FROM cms_orders WHERE customer_id = c.ID AND deleted=0 AND order_status=1) as total_debt
            FROM cms_customers c
            WHERE (customer_name LIKE ? OR customer_phone LIKE ?) LIMIT 20";
            
    $stmt = $conn->prepare($sql);
    
    // [FIX LỖI 500]
    if (!$stmt) {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi SQL Tìm Khách: ' . $conn->error]);
        exit();
    }

    $stmt->bind_param("ss", $term, $term);
    $stmt->execute();
    $stmt->bind_result($id, $name, $phone, $group, $spent, $debt);
    
    $customers = [];
    while ($stmt->fetch()) {
        $customers[] = ['id' => $id, 'name' => $name, 'code' => $phone, 'phone' => $phone, 'customer_group' => $group, 'total_spent' => $spent ?? 0, 'total_debt' => $debt ?? 0];
    }
    $stmt->close();
    echo json_encode(['status' => 'success', 'results' => $customers]);
}

// 3. LƯU KHÁCH NHANH
function handle_save_quick_customer($conn) {
    $name = $_POST['customer_name'] ?? '';
    $phone = $_POST['customer_phone'] ?? '';
    $addr = $_POST['customer_addr'] ?? '';
    
    if(empty($name)){ echo json_encode(['status' => 'error', 'message' => 'Tên bắt buộc']); return; }
    
    $res = $conn->query("SELECT ID FROM cms_customers ORDER BY ID DESC LIMIT 1");
    $last_id = ($res && $res->num_rows > 0) ? ($res->fetch_row()[0] ?? 0) : 0;
    
    $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, customer_group, created, user_init) VALUES (?, ?, ?, ?, 1, NOW(), 1)");
    
    if (!$stmt) {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi SQL Thêm Khách: ' . $conn->error]);
        return;
    }

    $stmt->bind_param("ssss", $code, $name, $phone, $addr);
    
    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]); 
    }
}

// 4. TẠO HOẶC CẬP NHẬT ĐƠN HÀNG
function handle_create_temp_order($conn, $user_id, $store_id) {
    $order_id = intval($_POST['order_id'] ?? 0);
    $customer_id = intval($_POST['customer_id'] ?? 1);
    $notes = $_POST['notes'] ?? '';
    $items = json_decode($_POST['items'] ?? '[]', true);
    $discount_val = floatval($_POST['order_discount_val'] ?? 0);
    $discount_type = $_POST['order_discount_type'] ?? 'money';
    
    $raw_date = $_POST['sale_date'] ?? '';
    if (!empty($raw_date)) { $sell_date = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $raw_date))); } else { $sell_date = date('Y-m-d H:i:s'); }

    if (empty($items)) { echo json_encode(['status' => 'error', 'message' => 'Giỏ hàng trống']); return; }

    // Lấy thông tin chi tiết sản phẩm từ DB
    $product_ids = array_column($items, 'id');
    $products_info = [];
    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_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[$row['ID']] = $row;
            }
            $stmt_p->close();
        }
    }

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

    foreach ($items as $item) {
        $p_id = intval($item['id']);
        $qty = floatval($item['quantity']);
        $price = floatval($item['price']);
        $origin = floatval($item['cost'] ?? 0);
        $item_discount_percent = floatval($item['discount_percent'] ?? 0);
        $item_discount_amt = $price * ($item_discount_percent / 100);
        
        $total_price += (($price - $item_discount_amt) * $qty);
        $total_origin += ($origin * $qty);
        $total_qty += $qty;

        $p_db = $products_info[$p_id] ?? [];

        $detail_order[] = [
            'id' => $p_id, 'code' => $item['code'], 'name' => $item['name'],
            'quantity' => $qty, 'price' => $price, 'origin_price' => $origin,
            'percent' => $item_discount_percent, 'discount' => $item_discount_amt,
            'note' => $item['note'] ?? '',
            'image' => $p_db['prd_image_url'] ?? '', 
            'size' => $p_db['prd_size'] ?? '',       
            'color' => $p_db['prd_color'] ?? ''      
        ];
    }

    $order_discount_amt = ($discount_type == 'percent') ? ($total_price * ($discount_val / 100)) : $discount_val;
    $final_money = max(0, $total_price - $order_discount_amt);
    
    $customer_pay = 0;
    $lack = 0; 
    $detail_json = json_encode($detail_order, JSON_UNESCAPED_UNICODE);

    if ($order_id > 0) {
        // UPDATE
        $sql = "UPDATE cms_orders SET 
                customer_id=?, sell_date=?, user_upd=?, 
                total_price=?, total_origin_price=?, total_quantity=?, total_money=?, 
                customer_pay=?, lack=?, discount_item=?, discount_percent=?, notes=?, 
                detail_order=?, updated=NOW()
                WHERE ID=?";
        $stmt = $conn->prepare($sql);
        
        if (!$stmt) { echo json_encode(['status' => 'error', 'message' => 'Lỗi SQL Update: ' . $conn->error]); return; }

        $stmt->bind_param("isiddddddddssi", 
            $customer_id, $sell_date, $user_id,
            $total_price, $total_origin, $total_qty, $final_money,
            $customer_pay, $lack, $order_discount_amt, $discount_val, $notes,
            $detail_json, $order_id
        );
        $msg = "Đã cập nhật đơn hàng!";
        $code = ''; 
    } else {
        // INSERT
        $res = $conn->query("SELECT MAX(ID) FROM cms_orders");
        $last_id_row = $res ? $res->fetch_row() : [0];
        $last_id = ($last_id_row[0] ?? 0) + 1;
        $output_code = 'DH' . str_pad($last_id, 7, '0', STR_PAD_LEFT);
        
        $sql = "INSERT INTO cms_orders (
            output_code, store_id, customer_id, created, sell_date, user_init, 
            total_price, total_origin_price, total_quantity, total_money, 
            customer_pay, lack, discount_item, discount_percent, notes, 
            detail_order, order_status, deleted
        ) VALUES (?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0)";
        
        $stmt = $conn->prepare($sql);
        
        if (!$stmt) { echo json_encode(['status' => 'error', 'message' => 'Lỗi SQL Insert: ' . $conn->error]); return; }

        $stmt->bind_param("siisiddddddddss", 
            $output_code, $store_id, $customer_id, $sell_date, $user_id, 
            $total_price, $total_origin, $total_qty, $final_money, 
            $customer_pay, $lack, 
            $order_discount_amt, $discount_val, $notes, $detail_json
        );
        $msg = "Tạo đơn thành công!";
        $code = $output_code;
    }

    if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => $msg, 'code' => $code, 'order_id' => $order_id > 0 ? $order_id : $stmt->insert_id]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi Thực thi: ' . $stmt->error]);
    }
}

// 5. LẤY CHI TIẾT ĐƠN
function handle_get_order_details($conn) {
    $order_id = intval($_REQUEST['order_id'] ?? 0);
    $sql = "SELECT o.*, c.customer_name, c.customer_phone, c.customer_group FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID WHERE o.ID = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $order = $stmt->get_result()->fetch_assoc();
    if ($order) { echo json_encode(['status' => 'success', 'order' => $order]); } 
    else { echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy đơn']); }
}

// 6. XÓA ĐƠN
function handle_delete_order($conn, $user_id) {
    $order_id = intval($_POST['order_id'] ?? 0);
    $stmt = $conn->prepare("UPDATE cms_orders SET deleted = 1, user_upd = ? WHERE ID = ?");
    $stmt->bind_param("ii", $user_id, $order_id);
    if ($stmt->execute()) { echo json_encode(['status' => 'success', 'message' => 'Đã xóa đơn hàng']); } 
    else { echo json_encode(['status' => 'error', 'message' => 'Lỗi xóa đơ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_order_details': handle_get_order_details($conn); break; 
    case 'delete_order': handle_delete_order($conn, $user_id); break; 
    default: echo json_encode(['status' => 'error', 'message' => 'Action not found']); break;
}
?>