<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Inventory API
 * Developer: JOACHIM'S INNOTECH
 */

// Verify authentication
$user_id = verify_api_request();
if (!$user_id) {
    json_response(['error' => 'Authentication required'], 401);
}

// Get current user
$current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$user_id]);

// Handle different methods based on subresource
$subresource = $subresource ?? '';

switch ($method) {
    case 'GET':
        if ($id === 'products') {
            get_products();
        } elseif ($id === 'stock') {
            if ($subresource === 'low') {
                get_low_stock();
            } elseif ($subresource) {
                get_product_stock($subresource);
            } else {
                get_all_stock();
            }
        } elseif ($id === 'movements') {
            if ($subresource) {
                get_product_movements($subresource);
            } else {
                get_all_movements();
            }
        } elseif ($id === 'suppliers') {
            get_suppliers();
        } elseif ($id === 'purchases') {
            if ($subresource) {
                get_purchase_order($subresource);
            } else {
                get_purchase_orders();
            }
        } else {
            json_response(['error' => 'Invalid endpoint'], 400);
        }
        break;
        
    case 'POST':
        if ($id === 'products') {
            create_product();
        } elseif ($id === 'movements') {
            create_movement();
        } elseif ($id === 'adjustments') {
            create_adjustment();
        } elseif ($id === 'suppliers') {
            create_supplier();
        } elseif ($id === 'purchases') {
            create_purchase_order();
        } elseif ($id === 'receive') {
            receive_purchase_order();
        } else {
            json_response(['error' => 'Invalid endpoint'], 400);
        }
        break;
        
    case 'PUT':
        if ($id === 'products' && $subresource) {
            update_product($subresource);
        } elseif ($id === 'suppliers' && $subresource) {
            update_supplier($subresource);
        } elseif ($id === 'purchases' && $subresource) {
            update_purchase_order($subresource);
        } else {
            json_response(['error' => 'Invalid endpoint'], 400);
        }
        break;
        
    default:
        json_response(['error' => 'Method not allowed'], 405);
}

/**
 * Get products list
 */
function get_products() {
    $category_id = isset($_GET['category_id']) ? (int)$_GET['category_id'] : null;
    $stock_only = isset($_GET['stock_only']) ? (bool)$_GET['stock_only'] : false;
    $search = $_GET['search'] ?? '';
    
    $sql = "
        SELECT 
            p.*,
            c.category_name,
            (SELECT COUNT(*) FROM purchase_order_items WHERE product_id = p.product_id) as po_count
        FROM pos_products p
        LEFT JOIN pos_categories c ON p.category_id = c.category_id
        WHERE p.is_active = 1
    ";
    
    $params = [];
    
    if ($category_id) {
        $sql .= " AND p.category_id = ?";
        $params[] = $category_id;
    }
    
    if ($stock_only) {
        $sql .= " AND p.stock_item = 1";
    }
    
    if (!empty($search)) {
        $sql .= " AND (p.product_name LIKE ? OR p.product_code LIKE ?)";
        $search_term = "%$search%";
        $params = array_merge($params, [$search_term, $search_term]);
    }
    
    $sql .= " ORDER BY c.category_name, p.product_name";
    
    $products = db_fetch_all($sql, $params);
    
    json_response([
        'success' => true,
        'data' => $products
    ]);
}

/**
 * Create product
 */
function create_product() {
    global $current_user;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        json_response(['error' => 'Invalid request data'], 400);
    }
    
    // Validate required fields
    $required = ['product_code', 'product_name', 'category_id', 'unit_price'];
    foreach ($required as $field) {
        if (empty($input[$field])) {
            json_response(['error' => "Field '$field' is required"], 400);
        }
    }
    
    // Check if code exists
    $exists = db_fetch_value("SELECT COUNT(*) FROM pos_products WHERE product_code = ?", [$input['product_code']]);
    if ($exists) {
        json_response(['error' => 'Product code already exists'], 400);
    }
    
    try {
        begin_transaction();
        
        $product_id = db_insert('pos_products', [
            'product_code' => $input['product_code'],
            'barcode' => $input['barcode'] ?? null,
            'product_name' => $input['product_name'],
            'description' => $input['description'] ?? null,
            'category_id' => $input['category_id'],
            'outlet_id' => $input['outlet_id'] ?? null,
            'unit_price' => $input['unit_price'],
            'cost_price' => $input['cost_price'] ?? null,
            'tax_id' => $input['tax_id'] ?? null,
            'tax_inclusive' => isset($input['tax_inclusive']) ? 1 : 0,
            'stock_item' => isset($input['stock_item']) ? 1 : 0,
            'current_stock' => $input['current_stock'] ?? 0,
            'min_stock' => $input['min_stock'] ?? 0,
            'max_stock' => $input['max_stock'] ?? null,
            'unit_of_measure' => $input['unit_of_measure'] ?? null,
            'track_serial' => isset($input['track_serial']) ? 1 : 0,
            'is_active' => 1
        ]);
        
        // Create initial stock movement if stock > 0
        if (($input['current_stock'] ?? 0) > 0) {
            db_insert('stock_movements', [
                'product_id' => $product_id,
                'movement_type' => 'adjustment',
                'quantity' => $input['current_stock'],
                'reference_type' => 'initial',
                'notes' => 'Initial stock on creation',
                'created_by' => $current_user['user_id']
            ]);
        }
        
        commit_transaction();
        
        $product = db_fetch_one("SELECT * FROM pos_products WHERE product_id = ?", [$product_id]);
        
        json_response([
            'success' => true,
            'message' => 'Product created successfully',
            'data' => $product
        ], 201);
        
    } catch (Exception $e) {
        rollback_transaction();
        json_response(['error' => 'Failed to create product: ' . $e->getMessage()], 500);
    }
}

/**
 * Update product
 */
function update_product($product_id) {
    global $current_user;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        json_response(['error' => 'Invalid request data'], 400);
    }
    
    // Check if product exists
    $product = db_fetch_one("SELECT * FROM pos_products WHERE product_id = ?", [$product_id]);
    if (!$product) {
        json_response(['error' => 'Product not found'], 404);
    }
    
    try {
        begin_transaction();
        
        $update_data = [];
        $allowed_fields = [
            'product_name', 'description', 'category_id', 'outlet_id',
            'unit_price', 'cost_price', 'tax_id', 'tax_inclusive',
            'min_stock', 'max_stock', 'unit_of_measure', 'track_serial', 'is_active'
        ];
        
        foreach ($allowed_fields as $field) {
            if (isset($input[$field])) {
                $update_data[$field] = $input[$field];
            }
        }
        
        // Handle stock update separately
        if (isset($input['current_stock']) && $input['current_stock'] != $product['current_stock']) {
            $quantity_diff = $input['current_stock'] - $product['current_stock'];
            
            if ($quantity_diff != 0) {
                db_insert('stock_movements', [
                    'product_id' => $product_id,
                    'movement_type' => 'adjustment',
                    'quantity' => $quantity_diff,
                    'reference_type' => 'manual',
                    'notes' => 'Stock adjusted via API',
                    'created_by' => $current_user['user_id']
                ]);
            }
            
            $update_data['current_stock'] = $input['current_stock'];
        }
        
        if (!empty($update_data)) {
            db_update('pos_products', $update_data, 'product_id = ?', [$product_id]);
        }
        
        commit_transaction();
        
        $updated = db_fetch_one("SELECT * FROM pos_products WHERE product_id = ?", [$product_id]);
        
        json_response([
            'success' => true,
            'message' => 'Product updated successfully',
            'data' => $updated
        ]);
        
    } catch (Exception $e) {
        rollback_transaction();
        json_response(['error' => 'Failed to update product: ' . $e->getMessage()], 500);
    }
}

/**
 * Get all stock levels
 */
function get_all_stock() {
    $stock = db_fetch_all("
        SELECT 
            product_id, product_code, product_name,
            current_stock, min_stock, max_stock, unit_of_measure,
            CASE 
                WHEN current_stock <= min_stock THEN 'low'
                WHEN current_stock <= 0 THEN 'out'
                ELSE 'normal'
            END as status
        FROM pos_products
        WHERE stock_item = 1 AND is_active = 1
        ORDER BY product_name
    ");
    
    json_response([
        'success' => true,
        'data' => $stock
    ]);
}

/**
 * Get product stock
 */
function get_product_stock($product_id) {
    $product = db_fetch_one("
        SELECT 
            product_id, product_code, product_name,
            current_stock, min_stock, max_stock, unit_of_measure
        FROM pos_products
        WHERE product_id = ? AND stock_item = 1
    ", [$product_id]);
    
    if (!$product) {
        json_response(['error' => 'Product not found or not a stock item'], 404);
    }
    
    json_response([
        'success' => true,
        'data' => $product
    ]);
}

/**
 * Get low stock items
 */
function get_low_stock() {
    $threshold = $_GET['threshold'] ?? 0;
    
    $sql = "
        SELECT 
            product_id, product_code, product_name,
            current_stock, min_stock, unit_of_measure,
            (min_stock - current_stock) as needed
        FROM pos_products
        WHERE stock_item = 1 AND is_active = 1
        AND current_stock <= min_stock
    ";
    
    if ($threshold > 0) {
        $sql .= " AND current_stock <= ?";
        $params = [$threshold];
    } else {
        $params = [];
    }
    
    $sql .= " ORDER BY (current_stock / min_stock)";
    
    $items = db_fetch_all($sql, $params);
    
    json_response([
        'success' => true,
        'data' => $items
    ]);
}

/**
 * Get stock movements
 */
function get_all_movements() {
    $limit = min(100, (int)($_GET['limit'] ?? 50));
    
    $movements = db_fetch_all("
        SELECT 
            sm.*,
            p.product_name, p.product_code,
            u.first_name, u.last_name
        FROM stock_movements sm
        JOIN pos_products p ON sm.product_id = p.product_id
        LEFT JOIN users u ON sm.created_by = u.user_id
        ORDER BY sm.created_at DESC
        LIMIT ?
    ", [$limit]);
    
    json_response([
        'success' => true,
        'data' => $movements
    ]);
}

/**
 * Get product movements
 */
function get_product_movements($product_id) {
    $limit = min(100, (int)($_GET['limit'] ?? 50));
    
    $movements = db_fetch_all("
        SELECT 
            sm.*,
            u.first_name, u.last_name
        FROM stock_movements sm
        LEFT JOIN users u ON sm.created_by = u.user_id
        WHERE sm.product_id = ?
        ORDER BY sm.created_at DESC
        LIMIT ?
    ", [$product_id, $limit]);
    
    json_response([
        'success' => true,
        'data' => $movements
    ]);
}

/**
 * Create stock movement
 */
function create_movement() {
    global $current_user;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        json_response(['error' => 'Invalid request data'], 400);
    }
    
    // Validate required fields
    $required = ['product_id', 'movement_type', 'quantity'];
    foreach ($required as $field) {
        if (!isset($input[$field])) {
            json_response(['error' => "Field '$field' is required"], 400);
        }
    }
    
    if ($input['quantity'] == 0) {
        json_response(['error' => 'Quantity cannot be zero'], 400);
    }
    
    // Get product
    $product = db_fetch_one("SELECT * FROM pos_products WHERE product_id = ?", [$input['product_id']]);
    if (!$product) {
        json_response(['error' => 'Product not found'], 404);
    }
    
    if (!$product['stock_item']) {
        json_response(['error' => 'Product does not track inventory'], 400);
    }
    
    try {
        begin_transaction();
        
        // Create movement
        $movement_id = db_insert('stock_movements', [
            'product_id' => $input['product_id'],
            'movement_type' => $input['movement_type'],
            'quantity' => $input['quantity'],
            'reference_type' => $input['reference_type'] ?? null,
            'reference_id' => $input['reference_id'] ?? null,
            'notes' => $input['notes'] ?? null,
            'created_by' => $current_user['user_id']
        ]);
        
        // Update product stock
        db_query("
            UPDATE pos_products 
            SET current_stock = current_stock + ? 
            WHERE product_id = ?
        ", [$input['quantity'], $input['product_id']]);
        
        commit_transaction();
        
        $movement = db_fetch_one("
            SELECT sm.*, p.product_name
            FROM stock_movements sm
            JOIN pos_products p ON sm.product_id = p.product_id
            WHERE sm.movement_id = ?
        ", [$movement_id]);
        
        json_response([
            'success' => true,
            'message' => 'Movement recorded successfully',
            'data' => $movement
        ], 201);
        
    } catch (Exception $e) {
        rollback_transaction();
        json_response(['error' => 'Failed to record movement: ' . $e->getMessage()], 500);
    }
}

/**
 * Create stock adjustment
 */
function create_adjustment() {
    global $current_user;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        json_response(['error' => 'Invalid request data'], 400);
    }
    
    // Validate required fields
    if (empty($input['reason'])) {
        json_response(['error' => 'Reason is required'], 400);
    }
    
    if (empty($input['items'])) {
        json_response(['error' => 'No items to adjust'], 400);
    }
    
    try {
        begin_transaction();
        
        // Create adjustment record
        $adjustment_number = 'ADJ-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
        
        $adjustment_id = db_insert('stock_adjustments', [
            'adjustment_number' => $adjustment_number,
            'adjustment_type' => $input['adjustment_type'] ?? 'adjustment',
            'reason' => $input['reason'],
            'notes' => $input['notes'] ?? null,
            'created_by' => $current_user['user_id']
        ]);
        
        foreach ($input['items'] as $item) {
            if (empty($item['product_id']) || empty($item['quantity'])) {
                continue;
            }
            
            // Insert adjustment item
            db_insert('stock_adjustment_items', [
                'adjustment_id' => $adjustment_id,
                'product_id' => $item['product_id'],
                'quantity' => $item['quantity'],
                'notes' => $item['notes'] ?? null
            ]);
            
            // Update product stock
            db_query("
                UPDATE pos_products 
                SET current_stock = current_stock + ? 
                WHERE product_id = ?
            ", [$item['quantity'], $item['product_id']]);
            
            // Record movement
            db_insert('stock_movements', [
                'product_id' => $item['product_id'],
                'movement_type' => 'adjustment',
                'quantity' => $item['quantity'],
                'reference_type' => 'adjustment',
                'reference_id' => $adjustment_id,
                'notes' => "Stock adjustment: {$input['reason']}",
                'created_by' => $current_user['user_id']
            ]);
        }
        
        commit_transaction();
        
        json_response([
            'success' => true,
            'message' => 'Adjustment completed successfully',
            'adjustment_id' => $adjustment_id
        ], 201);
        
    } catch (Exception $e) {
        rollback_transaction();
        json_response(['error' => 'Failed to create adjustment: ' . $e->getMessage()], 500);
    }
}

/**
 * Get suppliers
 */
function get_suppliers() {
    $suppliers = db_fetch_all("
        SELECT * FROM suppliers 
        WHERE is_active = 1 
        ORDER BY supplier_name
    ");
    
    json_response([
        'success' => true,
        'data' => $suppliers
    ]);
}

/**
 * Create supplier
 */
function create_supplier() {
    global $current_user;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        json_response(['error' => 'Invalid request data'], 400);
    }
    
    // Validate required fields
    if (empty($input['supplier_code'])) {
        json_response(['error' => 'Supplier code is required'], 400);
    }
    
    if (empty($input['supplier_name'])) {
        json_response(['error' => 'Supplier name is required'], 400);
    }
    
    // Check if code exists
    $exists = db_fetch_value("SELECT COUNT(*) FROM suppliers WHERE supplier_code = ?", [$input['supplier_code']]);
    if ($exists) {
        json_response(['error' => 'Supplier code already exists'], 400);
    }
    
    $supplier_id = db_insert('suppliers', [
        'supplier_code' => $input['supplier_code'],
        'supplier_name' => $input['supplier_name'],
        'contact_person' => $input['contact_person'] ?? null,
        'email' => $input['email'] ?? null,
        'phone' => $input['phone'] ?? null,
        'address' => $input['address'] ?? null,
        'city' => $input['city'] ?? null,
        'country' => $input['country'] ?? null,
        'tax_id' => $input['tax_id'] ?? null,
        'payment_terms' => $input['payment_terms'] ?? null,
        'is_active' => 1
    ]);
    
    $supplier = db_fetch_one("SELECT * FROM suppliers WHERE supplier_id = ?", [$supplier_id]);
    
    json_response([
        'success' => true,
        'message' => 'Supplier created successfully',
        'data' => $supplier
    ], 201);
}

/**
 * Update supplier
 */
function update_supplier($supplier_id) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        json_response(['error' => 'Invalid request data'], 400);
    }
    
    // Check if supplier exists
    $supplier = db_fetch_one("SELECT * FROM suppliers WHERE supplier_id = ?", [$supplier_id]);
    if (!$supplier) {
        json_response(['error' => 'Supplier not found'], 404);
    }
    
    $update_data = [];
    $allowed_fields = [
        'supplier_name', 'contact_person', 'email', 'phone',
        'address', 'city', 'country', 'tax_id', 'payment_terms', 'is_active'
    ];
    
    foreach ($allowed_fields as $field) {
        if (isset($input[$field])) {
            $update_data[$field] = $input[$field];
        }
    }
    
    if (!empty($update_data)) {
        db_update('suppliers', $update_data, 'supplier_id = ?', [$supplier_id]);
    }
    
    $updated = db_fetch_one("SELECT * FROM suppliers WHERE supplier_id = ?", [$supplier_id]);
    
    json_response([
        'success' => true,
        'message' => 'Supplier updated successfully',
        'data' => $updated
    ]);
}

/**
 * Get purchase orders
 */
function get_purchase_orders() {
    $status = $_GET['status'] ?? '';
    $supplier_id = isset($_GET['supplier_id']) ? (int)$_GET['supplier_id'] : null;
    
    $sql = "
        SELECT 
            po.*,
            s.supplier_name,
            COUNT(poi.item_id) as item_count
        FROM purchase_orders po
        JOIN suppliers s ON po.supplier_id = s.supplier_id
        LEFT JOIN purchase_order_items poi ON po.po_id = poi.po_id
        WHERE 1=1
    ";
    
    $params = [];
    
    if (!empty($status)) {
        $sql .= " AND po.status = ?";
        $params[] = $status;
    }
    
    if ($supplier_id) {
        $sql .= " AND po.supplier_id = ?";
        $params[] = $supplier_id;
    }
    
    $sql .= " GROUP BY po.po_id ORDER BY po.order_date DESC";
    
    $orders = db_fetch_all($sql, $params);
    
    json_response([
        'success' => true,
        'data' => $orders
    ]);
}

/**
 * Get purchase order
 */
function get_purchase_order($po_id) {
    $order = db_fetch_one("
        SELECT 
            po.*,
            s.supplier_name,
            u.first_name, u.last_name
        FROM purchase_orders po
        JOIN suppliers s ON po.supplier_id = s.supplier_id
        LEFT JOIN users u ON po.created_by = u.user_id
        WHERE po.po_id = ?
    ", [$po_id]);
    
    if (!$order) {
        json_response(['error' => 'Purchase order not found'], 404);
    }
    
    // Get items
    $items = db_fetch_all("
        SELECT 
            poi.*,
            p.product_name, p.product_code
        FROM purchase_order_items poi
        JOIN pos_products p ON poi.product_id = p.product_id
        WHERE poi.po_id = ?
    ", [$po_id]);
    
    $order['items'] = $items;
    
    json_response([
        'success' => true,
        'data' => $order
    ]);
}

/**
 * Create purchase order
 */
function create_purchase_order() {
    global $current_user;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        json_response(['error' => 'Invalid request data'], 400);
    }
    
    // Validate required fields
    if (empty($input['supplier_id'])) {
        json_response(['error' => 'Supplier ID is required'], 400);
    }
    
    if (empty($input['items'])) {
        json_response(['error' => 'No items in order'], 400);
    }
    
    try {
        begin_transaction();
        
        // Calculate totals
        $subtotal = 0;
        foreach ($input['items'] as $item) {
            $subtotal += $item['quantity'] * $item['unit_price'];
        }
        
        // Generate PO number
        $po_number = 'PO-' . date('Ymd') . '-' . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
        
        // Create PO
        $po_id = db_insert('purchase_orders', [
            'po_number' => $po_number,
            'supplier_id' => $input['supplier_id'],
            'order_date' => $input['order_date'] ?? date('Y-m-d'),
            'expected_date' => $input['expected_date'] ?? null,
            'status' => 'ordered',
            'subtotal' => $subtotal,
            'total_amount' => $subtotal,
            'notes' => $input['notes'] ?? null,
            'created_by' => $current_user['user_id']
        ]);
        
        // Add items
        foreach ($input['items'] as $item) {
            db_insert('purchase_order_items', [
                'po_id' => $po_id,
                'product_id' => $item['product_id'],
                'quantity_ordered' => $item['quantity'],
                'unit_price' => $item['unit_price'],
                'total_price' => $item['quantity'] * $item['unit_price']
            ]);
        }
        
        commit_transaction();
        
        $order = db_fetch_one("SELECT * FROM purchase_orders WHERE po_id = ?", [$po_id]);
        
        json_response([
            'success' => true,
            'message' => 'Purchase order created successfully',
            'data' => $order
        ], 201);
        
    } catch (Exception $e) {
        rollback_transaction();
        json_response(['error' => 'Failed to create purchase order: ' . $e->getMessage()], 500);
    }
}

/**
 * Receive purchase order
 */
function receive_purchase_order() {
    global $current_user;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        json_response(['error' => 'Invalid request data'], 400);
    }
    
    $po_id = (int)($input['po_id'] ?? 0);
    $items = $input['items'] ?? [];
    
    if (!$po_id) {
        json_response(['error' => 'PO ID is required'], 400);
    }
    
    if (empty($items)) {
        json_response(['error' => 'No items to receive'], 400);
    }
    
    // Get PO
    $po = db_fetch_one("SELECT * FROM purchase_orders WHERE po_id = ?", [$po_id]);
    if (!$po) {
        json_response(['error' => 'Purchase order not found'], 404);
    }
    
    try {
        begin_transaction();
        
        $all_received = true;
        
        foreach ($items as $item) {
            $item_id = $item['item_id'];
            $received_qty = (float)($item['received_quantity'] ?? 0);
            
            if ($received_qty > 0) {
                // Get PO item
                $po_item = db_fetch_one("SELECT * FROM purchase_order_items WHERE item_id = ?", [$item_id]);
                
                if ($po_item) {
                    $new_received = $po_item['quantity_received'] + $received_qty;
                    
                    if ($new_received > $po_item['quantity_ordered']) {
                        throw new Exception("Cannot receive more than ordered quantity");
                    }
                    
                    // Update PO item
                    db_update('purchase_order_items', [
                        'quantity_received' => $new_received
                    ], 'item_id = ?', [$item_id]);
                    
                    // Update product stock
                    db_query("
                        UPDATE pos_products 
                        SET current_stock = current_stock + ? 
                        WHERE product_id = ?
                    ", [$received_qty, $po_item['product_id']]);
                    
                    // Record movement
                    db_insert('stock_movements', [
                        'product_id' => $po_item['product_id'],
                        'movement_type' => 'purchase',
                        'quantity' => $received_qty,
                        'reference_type' => 'purchase_order',
                        'reference_id' => $po_id,
                        'notes' => "Received from PO #{$po['po_number']}",
                        'created_by' => $current_user['user_id']
                    ]);
                    
                    if ($new_received < $po_item['quantity_ordered']) {
                        $all_received = false;
                    }
                }
            }
        }
        
        // Update PO status
        $new_status = $all_received ? 'received' : 'partial';
        db_update('purchase_orders', [
            'status' => $new_status,
            'received_by' => $current_user['user_id'],
            'received_at' => date(DATETIME_FORMAT)
        ], 'po_id = ?', [$po_id]);
        
        commit_transaction();
        
        json_response([
            'success' => true,
            'message' => 'Purchase order received successfully',
            'status' => $new_status
        ]);
        
    } catch (Exception $e) {
        rollback_transaction();
        json_response(['error' => 'Failed to receive PO: ' . $e->getMessage()], 500);
    }
}