<?php
// Bật hiển thị lỗi để debug (nhưng ẩn khỏi output để không hỏng JSON)
ini_set('display_errors', 0);
error_reporting(E_ALL);

// --- CẤU HÌNH ĐƯỜNG DẪN ---
$root = dirname(__DIR__); 
if (file_exists($root . '/core/init.php')) {
    require_once $root . '/core/init.php';
} else {
    die(json_encode(['status' => 'error', 'message' => 'Không tìm thấy file kết nối Database (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'] ?? '';

// --- [MỚI] 0. QUÉT MÃ VẠCH (Tìm chính xác để thêm nhanh) ---
function handle_get_product_by_barcode($conn) {
    $barcode = trim($_GET['barcode'] ?? '');
    
    if (empty($barcode)) {
        echo json_encode(['status' => 'error', 'message' => 'Mã vạch rỗng']);
        return;
    }

    // Tìm chính xác mã (prd_code = ?) thay vì tìm gần đúng (LIKE)
    $sql = "SELECT ID, prd_name, prd_code, prd_sell_price, prd_sell_price2, prd_sls, prd_origin_price
            FROM cms_products 
            WHERE prd_code = ? 
            AND deleted = 0 AND prd_status = 1 LIMIT 1";
            
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi SQL: ' . $conn->error]);
        exit;
    }

    $stmt->bind_param("s", $barcode);
    $stmt->execute();
    
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        $product = [
            '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' => '',  
            'size' => '',     
            'color' => '',   
            'unit' => 'Cái'
        ];
        // Trả về single product để JS tự add vào giỏ
        echo json_encode(['status' => 'success', 'product' => $product]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy sản phẩm: ' . $barcode]);
    }
    $stmt->close();
}

// 1. TÌM SẢN PHẨM (Đã bỏ ảnh, size, màu)
function handle_search_products($conn) {
    $term = "%" . ($_GET['term'] ?? '') . "%";
    
    // Chỉ lấy các trường cơ bản
    $sql = "SELECT ID, prd_name, prd_code, prd_sell_price, prd_sell_price2, prd_sls, prd_origin_price
            FROM cms_products 
            WHERE (prd_name LIKE ? OR prd_code LIKE ?) 
            AND deleted = 0 AND prd_status = 1 LIMIT 30";
            
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi SQL: ' . $conn->error]);
        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'], 
            'price_retail' => $row['prd_sell_price'], 
            'price_wholesale' => $row['prd_sell_price2'], 
            'inventory' => $row['prd_sls'], 
            'origin_price' => $row['prd_origin_price'], 
            // Để trống các trường này
            'image' => '',  
            'size' => '',     
            'color' => '',   
            'unit' => 'Cái'
        ];
    }
    $stmt->close();
    echo json_encode(['status' => 'success', 'results' => $products]);
}

// 2. TÌM KHÁCH HÀNG
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);
    
    if (!$stmt) {
        echo json_encode(['status' => 'error', 'message' => 'Lỗi SQL Khách hàng: ' . $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->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, 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]); exit; }
    
    $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; }

    $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;

        $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' => '', 
            'size' => '',       
            '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) {
        $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);
        $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 {
        $res = $conn->query("SELECT MAX(ID) FROM cms_orders");
        $last_id = ($res->fetch_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 Tạo đơn: ' . $conn->error]); exit; }

        $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 ĐỂ SỬA
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 'get_product_by_barcode': handle_get_product_by_barcode($conn); break; // CASE MỚI
    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;
}
?>