<?php
/**
 * KDS Helper Functions
 * These functions can be called directly instead of making HTTP requests
 */

function createKDSOrder($conn, $order_type, $order_id) {
    try {
        if ($order_type === 'sale') {
            // Create KDS order from completed sale
            $sale = $conn->query("SELECT * FROM sales WHERE id = $order_id")->fetch_assoc();
            if (!$sale) {
                throw new Exception('Sale not found');
            }
            
            $sale_items = $conn->query("SELECT * FROM sale_items WHERE sale_id = $order_id");
            
            // Get table information if it's a dine-in order
            $table_number = null;
            if (!empty($sale['table_id'])) {
                $table_result = $conn->query("SELECT table_name FROM dinein_tables WHERE id = {$sale['table_id']}")->fetch_assoc();
                $table_number = $table_result ? $table_result['table_name'] : null;
            }
            
            // Create KDS order
            // Generate unique order number
            $order_number = 'SALE-' . str_pad($order_id, 6, '0', STR_PAD_LEFT);
            
            // Check if order number already exists and generate a unique one
            $counter = 1;
            $original_order_number = $order_number;
            while (true) {
                $check_stmt = $conn->prepare("SELECT id FROM kds_orders WHERE order_number = ?");
                $check_stmt->bind_param("s", $order_number);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                $check_stmt->close();
                
                if ($check_result->num_rows == 0) {
                    break; // Order number is unique
                }
                
                // Order number exists, try with suffix
                $order_number = $original_order_number . '-' . $counter;
                $counter++;
                
                if ($counter > 100) {
                    // Fallback: use timestamp
                    $order_number = 'SALE-' . $order_id . '-' . time();
                    break;
                }
            }
            
            $stmt = $conn->prepare("
                INSERT INTO kds_orders (
                    sale_id, invoice_number, order_number, table_number, 
                    customer_name, order_type, order_status, priority, 
                    order_sequence, parent_order_id, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, 'pending', 'normal', ?, NULL, NOW(), NOW())
            ");
            
            $order_type = $sale['order_mode'] ?? 'dine_in';
            $customer_name = $sale['customer_name'] ?? 'Walk-in Customer';
            
            $stmt->bind_param("isssssi", 
                $order_id, $sale['invoice_number'], $order_number, $table_number,
                $customer_name, $order_type, $order_id
            );
            $stmt->execute();
            $kds_order_id = $stmt->insert_id;
            $stmt->close();
            
            // Add KDS order items
            while ($item = $sale_items->fetch_assoc()) {
                // Get modifiers for this sale item
                $modifiers_query = $conn->prepare("SELECT modifier_name, price_adjustment FROM sale_item_modifiers WHERE sale_item_id = ?");
                $modifiers_query->bind_param("i", $item['id']);
                $modifiers_query->execute();
                $modifiers_result = $modifiers_query->get_result();
                
                $modifier_text = '';
                if ($modifiers_result->num_rows > 0) {
                    $modifiers = [];
                    while ($modifier = $modifiers_result->fetch_assoc()) {
                        $modifiers[] = $modifier['modifier_name'];
                    }
                    $modifier_text = implode(', ', $modifiers);
                }
                $modifiers_query->close();
                
                // Get remarks from sale item
                $remarks_text = $item['remarks'] ?? '';
                
                // Combine modifiers and remarks for special_instructions
                $special_instructions = '';
                if ($modifier_text && $remarks_text) {
                    $special_instructions = $modifier_text . ' | REMARKS: ' . $remarks_text;
                } elseif ($modifier_text) {
                    $special_instructions = $modifier_text;
                } elseif ($remarks_text) {
                    $special_instructions = 'REMARKS: ' . $remarks_text;
                }
                
                $stmt = $conn->prepare("
                    INSERT INTO kds_order_items (
                        kds_order_id, sale_item_id, item_id, item_name, quantity, 
                        unit_price, total_price, item_status, special_instructions, 
                        total_quantity, served_quantity, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, 0, NOW())
                ");
                
                $total_price = $item['quantity'] * $item['unit_price'];
                
                // Ensure parameters are correct types
                $special_instructions = (string) $special_instructions;
                $item_name = (string) $item['item_name'];
                $quantity = (int) $item['quantity'];
                $unit_price = (float) $item['unit_price'];
                $total_price = (float) $total_price;
                $item_id = (int) $item['id'];
                $item_item_id = (int) $item['item_id'];
                $kds_order_id = (int) $kds_order_id;
                
                $stmt->bind_param("iiisiddsi", 
                    $kds_order_id, $item_id, $item_item_id, $item_name, $quantity,
                    $unit_price, $total_price, $special_instructions, $quantity
                );
                $stmt->execute();
                $stmt->close();
            }
            
        } elseif ($order_type === 'hold') {
            // Create KDS order from hold order
            $hold = $conn->query("SELECT * FROM hold_orders WHERE id = $order_id")->fetch_assoc();
            if (!$hold) {
                throw new Exception('Hold order not found');
            }
            
            $hold_items = $conn->query("SELECT * FROM hold_items WHERE hold_id = $order_id");
            
            // Get table information if it's a dine-in order
            $table_number = null;
            if (!empty($hold['table_id'])) {
                $table_result = $conn->query("SELECT table_name FROM dinein_tables WHERE id = {$hold['table_id']}")->fetch_assoc();
                $table_number = $table_result ? $table_result['table_name'] : null;
            }
            
            // Check if this is the first order for this table or an additional order
            $is_running_order = false;
            if ($table_number) {
                // Check if there's already a KDS order for this table
                $existing_kds_check = $conn->query("
                    SELECT COUNT(*) as count 
                    FROM kds_orders 
                    WHERE table_number = '$table_number' 
                    AND order_status != 'served' 
                    AND id != (SELECT MAX(id) FROM kds_orders WHERE hold_id = $order_id)
                ")->fetch_assoc();
                
                $is_running_order = $existing_kds_check['count'] > 0;
            }
            
            // Create KDS order - only add RUNNING ORDER note if it's an additional order
            $notes = $is_running_order ? 'RUNNING ORDER - ADDITIONAL ITEMS' : null;
            
            // Generate unique order number
            $order_number = 'HOLD-' . str_pad($order_id, 6, '0', STR_PAD_LEFT);
            
            // Check if order number already exists and generate a unique one
            $counter = 1;
            $original_order_number = $order_number;
            while (true) {
                $check_stmt = $conn->prepare("SELECT id FROM kds_orders WHERE order_number = ?");
                $check_stmt->bind_param("s", $order_number);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                $check_stmt->close();
                
                if ($check_result->num_rows == 0) {
                    break; // Order number is unique
                }
                
                // Order number exists, try with suffix
                $order_number = $original_order_number . '-' . $counter;
                $counter++;
                
                if ($counter > 100) {
                    // Fallback: use timestamp
                    $order_number = 'HOLD-' . $order_id . '-' . time();
                    break;
                }
            }
            
            $stmt = $conn->prepare("
                INSERT INTO kds_orders (
                    hold_id, order_number, table_number, 
                    customer_name, order_type, order_status, priority, 
                    order_sequence, parent_order_id, notes, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, 'pending', 'normal', ?, NULL, ?, NOW(), NOW())
            ");
            
            $order_type = $hold['order_mode'] ?? 'dine_in';
            $customer_name = $hold['customer_name'] ?? 'Walk-in Customer';
            
            $stmt->bind_param("isssssi", 
                $order_id, $order_number, $table_number,
                $customer_name, $order_type, $order_id, $notes
            );
            $stmt->execute();
            $kds_order_id = $stmt->insert_id;
            $stmt->close();
            
            // Add KDS order items
            while ($item = $hold_items->fetch_assoc()) {
                // Get modifiers for this hold item
                $modifier_text = '';
                if (!empty($item['modifiers'])) {
                    $modifiers = json_decode($item['modifiers'], true);
                    if (is_array($modifiers)) {
                        $modifier_names = [];
                        foreach ($modifiers as $modifier) {
                            $modifier_names[] = $modifier['name'] ?? '';
                        }
                        $modifier_text = implode(', ', array_filter($modifier_names));
                    }
                }
                
                // Get template information if template_id exists
                $template_text = '';
                if (!empty($item['template_id'])) {
                    $template_stmt = $conn->prepare("SELECT name FROM modifier_templates WHERE id = ?");
                    $template_stmt->bind_param("i", $item['template_id']);
                    $template_stmt->execute();
                    $template_result = $template_stmt->get_result();
                    if ($template_row = $template_result->fetch_assoc()) {
                        $template_text = 'TEMPLATE: ' . $template_row['name'];
                    }
                    $template_stmt->close();
                }
                
                // Get remarks from hold item
                $remarks_text = $item['remarks'] ?? '';
                
                // Combine template, modifiers and remarks for special_instructions
                $special_instructions_parts = [];
                if ($template_text) $special_instructions_parts[] = $template_text;
                if ($modifier_text) $special_instructions_parts[] = $modifier_text;
                if ($remarks_text) $special_instructions_parts[] = 'REMARKS: ' . $remarks_text;
                
                $special_instructions = implode(' | ', $special_instructions_parts);
                
                $stmt = $conn->prepare("
                    INSERT INTO kds_order_items (
                        kds_order_id, hold_item_id, item_id, item_name, quantity, 
                        unit_price, total_price, item_status, special_instructions, 
                        total_quantity, served_quantity, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, 0, NOW())
                ");
                
                $total_price = $item['quantity'] * $item['unit_price'];
                
                // Ensure parameters are correct types
                $special_instructions = (string) $special_instructions;
                $item_name = (string) $item['item_name'];
                $quantity = (int) $item['quantity'];
                $unit_price = (float) $item['unit_price'];
                $total_price = (float) $total_price;
                $item_id = (int) $item['id'];
                $item_item_id = (int) $item['item_id'];
                $kds_order_id = (int) $kds_order_id;
                
                $stmt->bind_param("iiisiddsi", 
                    $kds_order_id, $item_id, $item_item_id, $item_name, $quantity,
                    $unit_price, $total_price, $special_instructions, $quantity
                );
                $stmt->execute();
                $stmt->close();
            }
        } else {
            throw new Exception('Invalid order type. Only "sale" and "hold" are supported.');
        }
        
        // Log activity (commented out for now to avoid table structure issues)
        // $activity_stmt = $conn->prepare("
        //     INSERT INTO kds_activity_log (
        //         kds_order_id, action, details, created_at
        //     ) VALUES (?, 'order_created', ?, NOW())
        // ");
        // $details = "Created KDS order from {$order_type} #{$order_id}";
        // $activity_stmt->bind_param("is", $kds_order_id, $details);
        // $activity_stmt->execute();
        // $activity_stmt->close();
        
        return [
            'success' => true, 
            'message' => 'KDS order created successfully',
            'kds_order_id' => $kds_order_id,
            'order_number' => $order_number ?? ''
        ];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Database error: ' . $e->getMessage()];
    }
}

function isKDSEnabled($conn) {
    // Check if kds_settings table exists first
    $table_exists = $conn->query("SHOW TABLES LIKE 'kds_settings'");
    if ($table_exists && $table_exists->num_rows > 0) {
        // Check if enable_kds setting exists, if not use default value
        $kds_enabled_result = $conn->query("SELECT setting_value FROM kds_settings WHERE setting_key = 'enable_kds'");
        if ($kds_enabled_result && $kds_enabled_result->num_rows > 0) {
            $kds_enabled = $kds_enabled_result->fetch_assoc()['setting_value'];
        } else {
            $kds_enabled = '1'; // Default to enabled
        }
        
        return $kds_enabled === '1';
    }
    
    return false;
}

function createKDSOrderIfEnabled($conn, $order_id, $order_type = 'sale', $unhold_id = null, $newly_added_items = null, $smart_new_items = null) {
    if (isKDSEnabled($conn)) {
        // Check if KDS order already exists for this order
        $existing_kds = null;
        if ($order_type === 'sale') {
            $existing_kds = $conn->query("SELECT id, order_status, order_sequence FROM kds_orders WHERE sale_id = $order_id")->fetch_assoc();
        } elseif ($order_type === 'hold') {
            $existing_kds = $conn->query("SELECT id, order_status, order_sequence FROM kds_orders WHERE hold_id = $order_id")->fetch_assoc();
        }
        
        if (!$existing_kds) {
            // Special case: If this is a sale from an unheld order, check if KDS order exists for the hold
            if ($order_type === 'sale' && $unhold_id) {
                $existing_kds = $conn->query("SELECT id, order_status, order_sequence FROM kds_orders WHERE hold_id = $unhold_id")->fetch_assoc();
                if ($existing_kds) {
                    // Update the existing KDS order to link to the sale instead of hold
                    $stmt = $conn->prepare("UPDATE kds_orders SET hold_id = NULL, sale_id = ?, order_type = 'sale' WHERE id = ?");
                    $stmt->bind_param("ii", $order_id, $existing_kds['id']);
                    $stmt->execute();
                    $stmt->close();
                    
                    return ['success' => true, 'message' => 'KDS order updated from hold to sale', 'kds_order_id' => $existing_kds['id']];
                }
            }
            
            // 🔧 UNIVERSAL RE-ORDER: Check if there are ANY served orders for this hold_id
            if ($order_type === 'hold') {
                // Look for ANY served KDS orders for this hold_id
                $served_kds = $conn->query("
                    SELECT id, order_sequence, order_status 
                    FROM kds_orders 
                    WHERE hold_id = $order_id 
                    AND order_status = 'served' 
                    ORDER BY id DESC 
                    LIMIT 1
                ")->fetch_assoc();
                
                if ($served_kds) {
                    // This is a re-order (1st, 2nd, 3rd, etc.), use the sequence system
                    return addItemsToOrderSequence($conn, $served_kds['order_sequence'], $order_id, $order_type, $newly_added_items, $smart_new_items);
                }
            }
            
            return createKDSOrder($conn, $order_type, $order_id);
        } else {
            // KDS order exists - check if it's served (universal re-order scenario)
            if ($existing_kds['order_status'] === 'served') {
                // Use universal re-order system: Add items to the same order sequence
                return addItemsToOrderSequence($conn, $existing_kds['order_sequence'], $order_id, $order_type, $newly_added_items, $smart_new_items);
            }
            
            // KDS order exists and not served, update it with new items for hold orders
            if ($order_type === 'hold') {
                return updateKDSOrder($conn, $order_id, $existing_kds['id'], $newly_added_items);
            }
        }
    }
    
    // Return the existing KDS order ID so quantity updates can work
    if (isset($existing_kds)) {
        return [
            'success' => true, 
            'message' => 'KDS order already exists',
            'kds_order_id' => $existing_kds['id']
        ];
    }
    
    return ['success' => true, 'message' => 'KDS disabled'];
}

function addItemsToOrderSequence($conn, $order_sequence, $order_id, $order_type, $newly_added_items = null, $smart_new_items = null) {
    try {
        // Check if there's already a RE-ORDER for this sequence
        $existing_reorder = $conn->query("SELECT * FROM kds_orders WHERE order_sequence = $order_sequence AND parent_order_id IS NOT NULL ORDER BY id DESC LIMIT 1")->fetch_assoc();
        
        if ($existing_reorder) {
            // Use existing RE-ORDER - PRESERVE the original hold_id
            $new_kds_order_id = $existing_reorder['id'];
            
            // 🔧 UNIVERSAL RE-ORDER: Update the existing RE-ORDER to use the current hold_id
            // This ensures the KDS order is linked to the current hold order
            $stmt = $conn->prepare("UPDATE kds_orders SET hold_id = ? WHERE id = ?");
            $stmt->bind_param("ii", $order_id, $new_kds_order_id);
            $stmt->execute();
            $stmt->close();
        } else {
            // Create new RE-ORDER
            $main_order = $conn->query("SELECT * FROM kds_orders WHERE order_sequence = $order_sequence ORDER BY id LIMIT 1")->fetch_assoc();
            if (!$main_order) {
                throw new Exception('Main order not found');
            }
            
            // Get the next sequence number
            $max_sequence = $conn->query("SELECT MAX(id) as max_id FROM kds_orders WHERE order_sequence = $order_sequence")->fetch_assoc()['max_id'] ?? 0;
            $next_sequence = $max_sequence + 1;
            
            // Create new sequence entry (same order sequence, different KDS order ID)
            $stmt = $conn->prepare("
                INSERT INTO kds_orders (
                    order_sequence, parent_order_id, hold_id, 
                    order_number, table_number, customer_name, order_type, 
                    order_status, priority, notes, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 'normal', 'RE-ORDER', NOW(), NOW())
            ");
            
            $new_order_number = $main_order['order_number'] . '-ADD' . $next_sequence;
            
            // 🔧 UNIVERSAL RE-ORDER: Use the current hold_id for the re-order
            $stmt->bind_param("iiissss", 
                $order_sequence, $main_order['id'], $order_id,
                $new_order_number, $main_order['table_number'], $main_order['customer_name'], $main_order['order_type']
            );
            
            $stmt->execute();
            $new_kds_order_id = $stmt->insert_id;
            $stmt->close();
        }
        
        // Add new items to this sequence
        if (!empty($newly_added_items) || !empty($smart_new_items)) {
            // 🔧 SMART QUANTITY: Handle smart new items with calculated quantities
            if (!empty($smart_new_items)) {
                // For universal re-orders with calculated quantities
                foreach ($smart_new_items as $smart_item) {
                    $item_id = $smart_item['item_id'];
                    $quantity = $smart_item['quantity'];
                    $name = $smart_item['name'];
                    $modifiers = $smart_item['modifiers'] ?? '';
                    
                    // Get modifiers text
                    $modifier_text = '';
                    if (!empty($modifiers)) {
                        $modifiers_array = json_decode($modifiers, true);
                        if (is_array($modifiers_array)) {
                            $modifier_names = [];
                            foreach ($modifiers_array as $modifier) {
                                $modifier_names[] = $modifier['name'] ?? '';
                            }
                            $modifier_text = implode(', ', array_filter($modifier_names));
                        }
                    }
                    
                    // Insert smart item with calculated quantity
                    $insert_stmt = $conn->prepare("
                        INSERT INTO kds_order_items (
                            kds_order_id, hold_item_id, item_id, item_name, quantity, 
                            unit_price, total_price, item_status, special_instructions, 
                            total_quantity, served_quantity, item_status_type, created_at
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, 'new', NOW())
                    ");
                    
                    // Get unit price and hold_item_id from hold_items
                    $price_result = $conn->query("SELECT id, unit_price FROM hold_items WHERE hold_id = $order_id AND item_id = $item_id LIMIT 1")->fetch_assoc();
                    $unit_price = $price_result ? $price_result['unit_price'] : 0;
                    $actual_hold_item_id = $price_result ? $price_result['id'] : $item_id; // Fallback to item_id if not found
                    $total_price = $quantity * $unit_price;
                    $zero_value = 0;
                    
                    $insert_stmt->bind_param("iiisiddsii", 
                        $new_kds_order_id, $actual_hold_item_id, $item_id, $name, $quantity,
                        $unit_price, $total_price, $modifier_text, $quantity, $zero_value
                    );
                    
                    $insert_stmt->execute();
                    $insert_stmt->close();
                }
            } elseif ($order_type === 'sale') {
                $placeholders = str_repeat('?,', count($newly_added_items) - 1) . '?';
                $new_items_query = "SELECT * FROM sale_items WHERE sale_id = ? AND item_id IN ($placeholders)";
                
                $stmt = $conn->prepare($new_items_query);
                $params = array_merge([$order_id], $newly_added_items);
                $stmt->bind_param(str_repeat('i', count($params)), ...$params);
                $stmt->execute();
                $result = $stmt->get_result();
                
                while ($item = $result->fetch_assoc()) {
                    // 🔧 FIX: Get modifiers for sale items
                    $modifiers_query = $conn->prepare("SELECT modifier_name FROM sale_item_modifiers WHERE sale_item_id = ?");
                    $modifiers_query->bind_param("i", $item['id']);
                    $modifiers_query->execute();
                    $modifiers_result = $modifiers_query->get_result();
                    
                    $modifier_text = '';
                    if ($modifiers_result->num_rows > 0) {
                        $modifiers = [];
                        while ($modifier = $modifiers_result->fetch_assoc()) {
                            $modifiers[] = $modifier['modifier_name'];
                        }
                        $modifier_text = implode(', ', $modifiers);
                    }
                    $modifiers_query->close();
                    
                    // Get remarks from sale item
                    $remarks_text = $item['remarks'] ?? '';
                    
                    // Combine modifiers and remarks for special_instructions
                    $special_instructions = '';
                    if ($modifier_text && $remarks_text) {
                        $special_instructions = $modifier_text . ' | REMARKS: ' . $remarks_text;
                    } elseif ($modifier_text) {
                        $special_instructions = $modifier_text;
                    } elseif ($remarks_text) {
                        $special_instructions = 'REMARKS: ' . $remarks_text;
                    }
                    
                    $insert_stmt = $conn->prepare("
                        INSERT INTO kds_order_items (
                            kds_order_id, sale_item_id, item_id, item_name, quantity, 
                            unit_price, total_price, item_status, special_instructions, 
                            total_quantity, served_quantity, item_status_type, created_at
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, 'new', NOW())
                    ");
                    
                    $total_price = $item['quantity'] * $item['unit_price'];
                    $zero_value = 0;
                    $insert_stmt->bind_param("iiisiddsii", 
                        $new_kds_order_id, $item['id'], $item['item_id'], $item['item_name'], $item['quantity'],
                        $item['unit_price'], $total_price, $special_instructions, $item['quantity'], $zero_value
                    );
                    $insert_stmt->execute();
                    $insert_stmt->close();
                }
                $stmt->close();
            } else {
                $placeholders = str_repeat('?,', count($newly_added_items) - 1) . '?';
                $new_items_query = "SELECT * FROM hold_items WHERE hold_id = ? AND item_id IN ($placeholders)";
                
                $stmt = $conn->prepare($new_items_query);
                $params = array_merge([$order_id], $newly_added_items);
                $stmt->bind_param(str_repeat('i', count($params)), ...$params);
                $stmt->execute();
                $result = $stmt->get_result();
                
                while ($item = $result->fetch_assoc()) {
                    // 🔧 FIX: Get modifiers for hold items
                    $modifier_text = '';
                    if (!empty($item['modifiers'])) {
                        $modifiers = json_decode($item['modifiers'], true);
                        if (is_array($modifiers)) {
                            $modifier_names = [];
                            foreach ($modifiers as $modifier) {
                                $modifier_names[] = $modifier['name'] ?? '';
                            }
                            $modifier_text = implode(', ', array_filter($modifier_names));
                        }
                    }
                    
                    // Get remarks from hold item
                    $remarks_text = $item['remarks'] ?? '';
                    
                    // Combine modifiers and remarks for special_instructions
                    $special_instructions = '';
                    if ($modifier_text && $remarks_text) {
                        $special_instructions = $modifier_text . ' | REMARKS: ' . $remarks_text;
                    } elseif ($modifier_text) {
                        $special_instructions = $modifier_text;
                    } elseif ($remarks_text) {
                        $special_instructions = 'REMARKS: ' . $remarks_text;
                    }
                    
                    $insert_stmt = $conn->prepare("
                        INSERT INTO kds_order_items (
                            kds_order_id, hold_item_id, item_id, item_name, quantity, 
                            unit_price, total_price, item_status, special_instructions, 
                            total_quantity, served_quantity, item_status_type, created_at
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, 'new', NOW())
                    ");
                    
                    $total_price = $item['quantity'] * $item['unit_price'];
                    $zero_value = 0;
                    
                    $insert_stmt->bind_param("iiisiddsii", 
                        $new_kds_order_id, $item['id'], $item['item_id'], $item['item_name'], $item['quantity'],
                        $item['unit_price'], $total_price, $special_instructions, $item['quantity'], $zero_value
                    );
                    
                    $insert_stmt->execute();
                    $insert_stmt->close();
                }
                $stmt->close();
            }
        }
        
        return [
            'success' => true, 
            'message' => 'Items added to order sequence successfully',
            'kds_order_id' => $new_kds_order_id,
            'order_sequence' => $order_sequence
        ];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error adding items to sequence: ' . $e->getMessage()];
    }
}

function updateKDSOrderQuantities($conn, $hold_id, $kds_order_id, $quantity_changed_items = null) {
    try {
        // 🔄 QUANTITY UPDATES: Update quantities for existing KDS items
        // This handles cases where customer increases/decreases quantities of existing items
        
        error_log("updateKDSOrderQuantities called with kds_order_id: $kds_order_id, quantity_changed_items: " . json_encode($quantity_changed_items));
        
        if (empty($quantity_changed_items)) {
            return ['success' => true, 'message' => 'No quantity changes to update'];
        }
        
        // Get current KDS items for this order
        $kds_items_result = $conn->query("SELECT * FROM kds_order_items WHERE kds_order_id = $kds_order_id");
        if (!$kds_items_result) {
            throw new Exception("Failed to fetch KDS items: " . $conn->error);
        }
        
        $kds_items = [];
        while ($row = $kds_items_result->fetch_assoc()) {
            $kds_items[] = $row;
        }
        
        error_log("Found " . count($kds_items) . " KDS items for order $kds_order_id");
        
        $updated_count = 0;
        foreach ($kds_items as $kds_item) {
            $item_id = intval($kds_item['item_id']);
            $kds_modifiers = $kds_item['special_instructions'] ?? '';
            
            error_log("Checking KDS item: item_id=$item_id, kds_modifiers='$kds_modifiers'");
            
            // Find matching quantity change
            foreach ($quantity_changed_items as $change) {
                $change_modifiers = $change['modifiers'] ?? '';
                
                // Convert JSON modifiers to text format for comparison
                $change_modifiers_text = '';
                if (!empty($change_modifiers)) {
                    $modifiers_array = json_decode($change_modifiers, true);
                    if (is_array($modifiers_array)) {
                        $modifier_names = [];
                        foreach ($modifiers_array as $modifier) {
                            $modifier_names[] = $modifier['name'] ?? '';
                        }
                        $change_modifiers_text = implode(', ', array_filter($modifier_names));
                    }
                }
                
                error_log("Comparing with change: item_id={$change['item_id']}, change_modifiers='$change_modifiers_text'");
                
                // 🔧 FIX: Improved matching logic - match by item_id and handle modifiers properly
                $modifiers_match = ($change_modifiers_text === $kds_modifiers) || 
                                 (empty($change_modifiers_text) && empty($kds_modifiers));
                
                if ($change['item_id'] == $item_id && $modifiers_match) {
                    // Update quantity and set status type to 'quantity_changed' in KDS
                    $update_stmt = $conn->prepare("UPDATE kds_order_items SET quantity = ?, total_quantity = ?, item_status_type = 'quantity_changed' WHERE id = ?");
                    $update_stmt->bind_param("iii", $change['new_quantity'], $change['new_quantity'], $kds_item['id']);
                    $update_stmt->execute();
                    $update_stmt->close();
                    
                    $updated_count++;
                    error_log("✅ Updated KDS item quantity: Item {$item_id} from {$change['old_quantity']} to {$change['new_quantity']} - Status set to 'quantity_changed'");
                    break;
                }
            }
        }
        
        error_log("Total updated items: $updated_count");
        
        return [
            'success' => true, 
            'message' => "Updated quantities for $updated_count items",
            'updated_count' => $updated_count
        ];
        
    } catch (Exception $e) {
        error_log("KDS Quantity Update Error: " . $e->getMessage());
        return ['success' => false, 'message' => $e->getMessage()];
    }
}

function updateKDSOrder($conn, $hold_id, $kds_order_id, $newly_added_items = null) {
    try {
        // 🔧 FIX: Handle both hold_id and sale_id scenarios
        // This function is now called for both hold orders and POST-SERVICE orders
        
        $has_new_items = false;
        
        // If no new items specified, don't add anything to KDS but return KDS order ID for quantity updates
        if (empty($newly_added_items)) {
            return ['success' => true, 'message' => 'No new items to add to KDS', 'kds_order_id' => $kds_order_id];
        }
        
        // Check if this is a POST-SERVICE ORDER (linked to sale) or regular hold order
        $kds_order_check = $conn->query("SELECT sale_id, hold_id, notes FROM kds_orders WHERE id = $kds_order_id")->fetch_assoc();
        $is_post_service = $kds_order_check && strpos($kds_order_check['notes'], 'POST-SERVICE ORDER') !== false;
        
        if ($is_post_service && $kds_order_check['sale_id']) {
            // This is a POST-SERVICE ORDER linked to a sale
            // Get items from sale_items instead of hold_items
            $placeholders = str_repeat('?,', count($newly_added_items) - 1) . '?';
            $new_items_query = "SELECT * FROM sale_items WHERE sale_id = ? AND item_id IN ($placeholders)";
            
            $stmt = $conn->prepare($new_items_query);
            $params = array_merge([$kds_order_check['sale_id']], $newly_added_items);
            $stmt->bind_param(str_repeat('i', count($params)), ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $has_new_items = $result->num_rows > 0;
            
            // Add only new items to KDS
            while ($item = $result->fetch_assoc()) {
                // Get modifiers for this sale item
                $modifiers_query = $conn->prepare("SELECT modifier_name FROM sale_item_modifiers WHERE sale_item_id = ?");
                $modifiers_query->bind_param("i", $item['id']);
                $modifiers_query->execute();
                $modifiers_result = $modifiers_query->get_result();
                
                $modifier_text = '';
                if ($modifiers_result->num_rows > 0) {
                    $modifiers = [];
                    while ($modifier = $modifiers_result->fetch_assoc()) {
                        $modifiers[] = $modifier['modifier_name'];
                    }
                    $modifier_text = implode(', ', $modifiers);
                }
                $modifiers_query->close();
                
                // Get remarks from sale item
                $remarks_text = $item['remarks'] ?? '';
                
                // Combine modifiers and remarks for special_instructions
                $special_instructions = '';
                if ($modifier_text && $remarks_text) {
                    $special_instructions = $modifier_text . ' | REMARKS: ' . $remarks_text;
                } elseif ($modifier_text) {
                    $special_instructions = $modifier_text;
                } elseif ($remarks_text) {
                    $special_instructions = 'REMARKS: ' . $remarks_text;
                }
                
                $insert_stmt = $conn->prepare("
                    INSERT INTO kds_order_items (
                        kds_order_id, sale_item_id, item_id, item_name, quantity, 
                        unit_price, total_price, item_status, special_instructions, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NOW())
                ");
                
                $total_price = $item['quantity'] * $item['unit_price'];
                
                $insert_stmt->bind_param("iiisidds", 
                    $kds_order_id, $item['id'], $item['item_id'], $item['item_name'], $item['quantity'],
                    $item['unit_price'], $total_price, $special_instructions
                );
                $insert_stmt->execute();
                $insert_stmt->close();
            }
            $stmt->close();
            
        } else {
            // This is a regular hold order
            // 🔧 FIX: Handle item_key format (item_id|modifiers) instead of just item_id
            $new_items_query = "SELECT * FROM hold_items WHERE hold_id = ?";
            $params = [$hold_id];
            $types = 'i';
            
            // Build WHERE clause to match specific item+modifier combinations
            $where_conditions = [];
            foreach ($newly_added_items as $item_key) {
                // Parse item_key format: "item_id|modifiers"
                $parts = explode('|', $item_key, 2);
                $item_id = $parts[0];
                $modifiers = isset($parts[1]) ? $parts[1] : '';
                
                if ($modifiers === '') {
                    // No modifiers - match items with NULL or empty modifiers
                    $where_conditions[] = "(item_id = ? AND (modifiers IS NULL OR modifiers = ''))";
                    $params[] = $item_id;
                    $types .= 'i';
                } else {
                    // Has modifiers - match exact modifier combination
                    $where_conditions[] = "(item_id = ? AND modifiers = ?)";
                    $params[] = $item_id;
                    $params[] = $modifiers;
                    $types .= 'is';
                }
            }
            
            if (!empty($where_conditions)) {
                $new_items_query .= " AND (" . implode(' OR ', $where_conditions) . ")";
            }
            
            $stmt = $conn->prepare($new_items_query);
            $stmt->bind_param($types, ...$params);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $has_new_items = $result->num_rows > 0;
            
            // Add only new items to KDS
            while ($item = $result->fetch_assoc()) {
                // Get modifiers for this hold item
                $modifier_text = '';
                if (!empty($item['modifiers'])) {
                    $modifiers = json_decode($item['modifiers'], true);
                    if (is_array($modifiers)) {
                        $modifier_names = [];
                        foreach ($modifiers as $modifier) {
                            $modifier_names[] = $modifier['name'] ?? '';
                        }
                        $modifier_text = implode(', ', array_filter($modifier_names));
                    }
                }
                
                $insert_stmt = $conn->prepare("
                    INSERT INTO kds_order_items (
                        kds_order_id, hold_item_id, item_id, item_name, quantity, 
                        unit_price, total_price, item_status, special_instructions, item_status_type, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, 'new', NOW())
                ");
                
                $total_price = $item['quantity'] * $item['unit_price'];
                
                $insert_stmt->bind_param("iiisidds", 
                    $kds_order_id, $item['id'], $item['item_id'], $item['item_name'], $item['quantity'],
                    $item['unit_price'], $total_price, $modifier_text
                );
                $insert_stmt->execute();
                $insert_stmt->close();
            }
            $stmt->close();
        }
        
        // Update KDS order note to indicate new items were added
        if ($has_new_items) {
            $update_note_stmt = $conn->prepare("
                UPDATE kds_orders 
                SET notes = CASE 
                    WHEN notes IS NULL OR notes = '' THEN 'RUNNING ORDER - ADDITIONAL ITEMS'
                    WHEN notes LIKE '%RUNNING ORDER%' THEN notes
                    WHEN notes LIKE '%POST-SERVICE ORDER%' THEN CONCAT(notes, ' | ADDITIONAL ITEMS')
                    ELSE CONCAT(notes, ' | RUNNING ORDER - ADDITIONAL ITEMS')
                END,
                updated_at = NOW()
                WHERE id = ?
            ");
            $update_note_stmt->bind_param("i", $kds_order_id);
            $update_note_stmt->execute();
            $update_note_stmt->close();
        }
        
        return ['success' => true, 'message' => 'KDS order updated successfully', 'kds_order_id' => $kds_order_id];
        
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error updating KDS order: ' . $e->getMessage()];
    }
}

// Removed createPostServiceKDSOrder function - now using addItemsToOrderSequence
?>
