<?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, 
                    created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, ?, 'pending', 'normal', NOW(), NOW())
            ");
            
            $order_type = $sale['order_mode'] ?? 'dine_in';
            $customer_name = $sale['customer_name'] ?? 'Walk-in Customer';
            
            $stmt->bind_param("isssss", 
                $order_id, $sale['invoice_number'], $order_number, $table_number,
                $customer_name, $order_type
            );
            $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, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NOW())
                ");
                
                $total_price = $item['quantity'] * $item['unit_price'];
                
                $stmt->bind_param("iiisidds", 
                    $kds_order_id, $item['id'], $item['item_id'], $item['item_name'], $item['quantity'],
                    $item['unit_price'], $total_price, $special_instructions
                );
                $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, 
                    notes, created_at, updated_at
                ) VALUES (?, ?, ?, ?, ?, 'pending', 'normal', ?, NOW(), NOW())
            ");
            
            $order_type = $hold['order_mode'] ?? 'dine_in';
            $customer_name = $hold['customer_name'] ?? 'Walk-in Customer';
            
            $stmt->bind_param("isssss", 
                $order_id, $order_number, $table_number,
                $customer_name, $order_type, $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 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;
                }
                
                $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, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NOW())
                ");
                
                $total_price = $item['quantity'] * $item['unit_price'];
                
                $stmt->bind_param("iiisidds", 
                    $kds_order_id, $item['id'], $item['item_id'], $item['item_name'], $item['quantity'],
                    $item['unit_price'], $total_price, $special_instructions
                );
                $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) {
    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 FROM kds_orders WHERE sale_id = $order_id")->fetch_assoc();
        } elseif ($order_type === 'hold') {
            $existing_kds = $conn->query("SELECT id 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 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']];
                }
            }
            
            return createKDSOrder($conn, $order_type, $order_id);
        } else {
            // KDS order exists, update it with new items for hold orders
            if ($order_type === 'hold') {
                return updateKDSOrder($conn, $order_id, $existing_kds['id'], $newly_added_items);
            }
        }
    }
    
    return ['success' => true, 'message' => 'KDS order already exists or KDS disabled'];
}

function updateKDSOrder($conn, $hold_id, $kds_order_id, $newly_added_items = null) {
    try {
        // 🍳 NEW ITEMS ONLY: Only add new items to KDS, don't touch existing ones
        // This ensures KOT only prints new items while keeping existing KDS items
        
        $has_new_items = false;
        
        // If no new items specified, don't add anything to KDS
        if (empty($newly_added_items)) {
            return ['success' => true, 'message' => 'No new items to add to KDS'];
        }
        
        // Get only the new items from hold_items
        $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([$hold_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 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, 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, $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 'NEW ITEMS ADDED'
                    WHEN notes LIKE '%NEW ITEMS ADDED%' THEN notes
                    ELSE CONCAT(notes, ' | NEW ITEMS ADDED')
                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()];
    }
}
?>
