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

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 (Giữ nguyên)
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 
            FROM cms_products 
            WHERE (prd_name LIKE ? OR prd_code LIKE ?) 
            AND deleted = 0 AND prd_status = 1 LIMIT 30";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $term, $term);
    $stmt->execute();
    $stmt->bind_result($id, $name, $code, $price, $price2, $inventory, $origin);
    $products = [];
    while ($stmt->fetch()) {
        $products[] = ['id' => $id, 'name' => $name, 'code' => $code, 'price_retail' => $price, 'price_wholesale' => $price2, 'inventory' => $inventory, 'origin_price' => $origin, 'unit' => 'Cái'];
    }
    $stmt->close();
    echo json_encode(['status' => 'success', 'results' => $products]);
}

// 2. TÌM KHÁCH HÀNG (Giữ nguyên)
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);
    $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 (Giữ nguyên)
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)");
    $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 (ĐÃ NÂNG CẤP)
function handle_create_temp_order($conn, $user_id, $store_id) {
    $order_id = intval($_POST['order_id'] ?? 0); // [MỚI] Lấy ID đơn hàng để biết là Sửa hay Thêm
    $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) {
        $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' => $item['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'] ?? ''
        ];
    }

    $order_discount_amt = ($discount_type == 'percent') ? ($total_price * ($discount_val / 100)) : $discount_val;
    $final_money = max(0, $total_price - $order_discount_amt);
    
    // Đơn khởi tạo: Chưa trả, Không tính nợ (Lack=0), Status = 0
    $customer_pay = 0;
    $lack = 0; 
    $status = 0;
    $detail_json = json_encode($detail_order, JSON_UNESCAPED_UNICODE);

    if ($order_id > 0) {
        // --- CẬP NHẬT (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);
        
        // [CHÚ Ý] Chuỗi định dạng: isiddddddddssi (14 ký tự) -> Khớp với 14 biến
        $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 {
        // --- TẠO MỚI (INSERT) ---
        $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);
        // Chuỗi định dạng: siisiddddddddss (15 ký tự)
        $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 SQL: ' . $stmt->error]);
    }
}

// 5. LẤY CHI TIẾT ĐƠN ĐỂ SỬA (MỚI)
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 (MỚI)
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; // Mới
    case 'delete_order': handle_delete_order($conn, $user_id); break; // Mới
    default: echo json_encode(['status' => 'error', 'message' => 'Action not found']); break;
}
?>