<?php
// Tablet Order System - Hold Order Handler
header('Content-Type: application/json');

// Prevent any output before JSON
ob_start();

// Error handling
error_reporting(E_ALL);
ini_set('display_errors', 0);

try {
    include '../db.php';
    
    // Test database connection
    if ($conn->connect_error) {
        throw new Exception('Database connection failed: ' . $conn->connect_error);
    }

    // Clear any previous output
    ob_clean();

    // Get JSON input
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON input: ' . json_last_error_msg());
    }

    // Validate required fields
    if (empty($data['customer_name'])) {
        throw new Exception('Customer name is required');
    }

    if (empty($data['cart']) || !is_array($data['cart'])) {
        throw new Exception('Cart data is required and must be an array');
    }

    if (empty($data['order_mode'])) {
        throw new Exception('Order mode is required');
    }

    if (empty($data['order_taker_id'])) {
        throw new Exception('Order taker is required');
    }

    // Extract data
    $customer_name = $data['customer_name'];
    $customer_id = $data['customer_id'] ?? null;
    
    // If customer_id is not provided, look up customer by name (similar to save_sale.php)
    if (!$customer_id && $customer_name !== 'Walk-in Customer') {
        $customer_stmt = $conn->prepare("SELECT id FROM customers WHERE name = ? LIMIT 1");
        $customer_stmt->bind_param("s", $customer_name);
        $customer_stmt->execute();
        $customer_result = $customer_stmt->get_result();
        
        if ($customer_row = $customer_result->fetch_assoc()) {
            $customer_id = $customer_row['id'];
        }
        $customer_stmt->close();
    }
    $cart = $data['cart'];
    $order_mode = $data['order_mode'];
    $table_id = $data['table_id'] ?? null;
    $order_taker_id = $data['order_taker_id'];
    $total_amount = $data['total_amount'] ?? 0;
    $hold_id = $data['hold_id'] ?? null; // Check if we're updating an existing order
    $is_running_order = $data['is_running_order'] ?? false; // Running order flag

    // Calculate total if not provided
    if ($total_amount == 0) {
        foreach ($cart as $item) {
            $total_amount += $item['price'] * $item['quantity'];
        }
    }

    // Begin transaction
    $conn->begin_transaction();

    try {
        // If we're updating an existing order
        if ($hold_id) {
            // Verify the hold order exists
            $check_stmt = $conn->prepare("SELECT id, table_id FROM hold_orders WHERE id = ?");
            $check_stmt->bind_param("i", $hold_id);
            $check_stmt->execute();
            $check_result = $check_stmt->get_result();
            
            if ($check_result->num_rows === 0) {
                throw new Exception('Hold order not found');
            }
            
            $existing_order = $check_result->fetch_assoc();
            $check_stmt->close();
            
            // Update the existing hold order
            $update_stmt = $conn->prepare("
                UPDATE hold_orders 
                SET customer_name = ?, customer_id = ?, total_amount = ?, order_taker_id = ?
                WHERE id = ?
            ");
            $update_stmt->bind_param("sidi", $customer_name, $customer_id, $total_amount, $order_taker_id, $hold_id);
            $update_stmt->execute();
            $update_stmt->close();
            
            // Instead of deleting existing items, append new items
            foreach ($cart as $item) {
                // Check if item already exists in this hold order
                $check_item_stmt = $conn->prepare("SELECT id, quantity FROM hold_items WHERE hold_id = ? AND item_id = ?");
                $check_item_stmt->bind_param("ii", $hold_id, $item['id']);
                $check_item_stmt->execute();
                $check_item_result = $check_item_stmt->get_result();
                
                if ($check_item_result->num_rows > 0) {
                    // Item exists, update quantity
                    $existing_item = $check_item_result->fetch_assoc();
                    $new_quantity = $existing_item['quantity'] + $item['quantity'];
                    
                    $update_item_stmt = $conn->prepare("
                        UPDATE hold_items 
                        SET quantity = ?, unit_price = ?, tax_rate = ?
                        WHERE id = ?
                    ");
                    $tax_rate = $item['tax_rate'] ?? 0.00;
                    $update_item_stmt->bind_param("iddi", $new_quantity, $item['price'], $tax_rate, $existing_item['id']);
                    $update_item_stmt->execute();
                    $update_item_stmt->close();
                } else {
                    // Item doesn't exist, insert new item
                    $modifiers = isset($item['modifiers']) && is_array($item['modifiers']) ? json_encode($item['modifiers']) : null;
                    $remarks = isset($item['remarks']) ? $item['remarks'] : null;
                    
                    $item_stmt = $conn->prepare("
                        INSERT INTO hold_items (hold_id, item_id, item_name, quantity, unit_price, tax_rate, modifiers, remarks)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    
                    $tax_rate = $item['tax_rate'] ?? 0.00;
                    $item_stmt->bind_param("iisiddss", 
                        $hold_id, 
                        $item['id'], 
                        $item['name'], 
                        $item['quantity'], 
                        $item['price'], 
                        $tax_rate,
                        $modifiers,
                        $remarks
                    );
                    $item_stmt->execute();
                    $item_stmt->close();
                }
                $check_item_stmt->close();
            }
            
            // Update KDS order if it exists
            $kds_enabled = $conn->query("SELECT setting_value FROM kds_settings WHERE setting_key = 'enable_kds'")->fetch_assoc()['setting_value'] ?? '1';
            
            if ($kds_enabled === '1') {
                // Include KDS helper
                include_once '../kds_helper.php';
                
                // Update existing KDS order or create new one
                $kds_result = createKDSOrderIfEnabled($conn, $hold_id, 'hold');
                
                if (!$kds_result['success']) {
                    error_log("KDS Order Update Error: " . $kds_result['message']);
                }
            }
            
        } else {
            // Check if there's already a hold order for this table (for dine-in)
            if ($order_mode === 'dine_in' && $table_id) {
                $check_stmt = $conn->prepare("SELECT id FROM hold_orders WHERE table_id = ? LIMIT 1");
                $check_stmt->bind_param("i", $table_id);
                $check_stmt->execute();
                $check_result = $check_stmt->get_result();
                
                if ($check_result->num_rows > 0) {
                    $row = $check_result->fetch_assoc();
                    $hold_id = $row['id'];

                    // Update existing hold order (removed updated_at column)
                    $update_stmt = $conn->prepare("
                        UPDATE hold_orders 
                        SET customer_name = ?, customer_id = ?, order_mode = ?, total_amount = total_amount + ?, order_taker_id = ?
                        WHERE id = ?
                    ");
                    $update_stmt->bind_param("sisdi", $customer_name, $customer_id, $order_mode, $total_amount, $order_taker_id, $hold_id);
                    $update_stmt->execute();
                    $update_stmt->close();
                }
                $check_stmt->close();
            }

            // Create new hold order if none exists
            if (!$hold_id) {
                $insert_stmt = $conn->prepare("
                    INSERT INTO hold_orders (customer_name, customer_id, table_id, order_mode, total_amount, order_taker_id, created_at) 
                    VALUES (?, ?, ?, ?, ?, ?, NOW())
                ");
                $insert_stmt->bind_param("sisiid", $customer_name, $customer_id, $table_id, $order_mode, $total_amount, $order_taker_id);
                $insert_stmt->execute();
                $hold_id = $insert_stmt->insert_id;
                $insert_stmt->close();
            }

            // Add hold items
            foreach ($cart as $item) {
                $modifiers = isset($item['modifiers']) && is_array($item['modifiers']) ? json_encode($item['modifiers']) : null;
                $remarks = isset($item['remarks']) ? $item['remarks'] : null;
                
                $item_stmt = $conn->prepare("
                    INSERT INTO hold_items (hold_id, item_id, item_name, quantity, unit_price, tax_rate, modifiers, remarks)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                
                $tax_rate = $item['tax_rate'] ?? 0.00;
                $item_stmt->bind_param("iisiddss", 
                    $hold_id, 
                    $item['id'], 
                    $item['name'], 
                    $item['quantity'], 
                    $item['price'], 
                    $tax_rate,
                    $modifiers,
                    $remarks
                );
                $item_stmt->execute();
                $item_stmt->close();
            }

            // Create KDS order if KDS is enabled
            $kds_enabled = $conn->query("SELECT setting_value FROM kds_settings WHERE setting_key = 'enable_kds'")->fetch_assoc()['setting_value'] ?? '1';
            
            if ($kds_enabled === '1') {
                // Include KDS helper
                include_once '../kds_helper.php';
                
                // Create KDS order from hold order
                $kds_result = createKDSOrderIfEnabled($conn, $hold_id, 'hold');
                
                if (!$kds_result['success']) {
                    error_log("KDS Order Creation Error: " . $kds_result['message']);
                }
                
                // If this is a running order, update the KDS order note
                if ($is_running_order && $kds_result['success']) {
                    $kds_order_id = $kds_result['kds_order_id'] ?? null;
                    if ($kds_order_id) {
                        $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
                                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();
                    }
                }
            }
        }

        // Update table status if it's a dine-in order
        if ($order_mode === 'dine_in' && $table_id) {
            $table_stmt = $conn->prepare("UPDATE dinein_tables SET status = 'occupied' WHERE id = ?");
            $table_stmt->bind_param("i", $table_id);
            $table_stmt->execute();
            $table_stmt->close();
        }

        // Commit transaction
        $conn->commit();

        // Return success response
        echo json_encode([
            'success' => true,
            'message' => 'Order held successfully',
            'hold_id' => $hold_id,
            'total_amount' => $total_amount,
            'kds_created' => $kds_enabled === '1',
            'table_id' => $table_id,
            'order_mode' => $order_mode
        ]);

    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        throw $e;
    }

} catch (Exception $e) {
    // Log error
    error_log('Tablet hold order error: ' . $e->getMessage());
    
    // Return error response
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

// Close database connection
if (isset($conn)) {
    $conn->close();
}
?>
