<?php
/**
 * Server Add Items to Existing Order API - SIMPLIFIED
 * Handles both: adding new items and updating quantities for existing items
 */

session_start();
header('Content-Type: application/json');
require_once 'config.php';

// Suppress any output that might interfere with JSON
ini_set('display_errors', 0);
error_reporting(E_ALL);

// Log the request for debugging
error_log('=== SERVER_ADD_ITEMS_TO_ORDER REQUEST ===');
error_log('REQUEST METHOD: ' . $_SERVER['REQUEST_METHOD']);
error_log('SESSION SERVER_ID: ' . (isset($_SESSION['server_id']) ? $_SESSION['server_id'] : 'NOT SET'));

// Check server authentication
if (!isset($_SESSION['server_id'])) {
    error_log('ERROR: No server_id in session');
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access - Please login as a server']);
    exit;
}

$server_id = $_SESSION['server_id'];
$input = json_decode(file_get_contents('php://input'), true);

error_log('INPUT: ' . json_encode($input));

if (!$input || !isset($input['order_id']) || !isset($input['items'])) {
    error_log('ERROR: Invalid request - Missing order_id or items');
    echo json_encode(['success' => false, 'message' => 'Invalid request - order_id and items are required']);
    exit;
}

$order_id = (int)$input['order_id'];
$items = $input['items'];

if (empty($items)) {
    error_log('ERROR: No items provided');
    echo json_encode(['success' => false, 'message' => 'No items provided']);
    exit;
}

try {
    error_log('=== Adding items to order ' . $order_id . ' ===');
    
    // Verify order ownership using direct query first
    $verify_sql = "SELECT id FROM dine_in_orders WHERE id = $order_id AND server_id = $server_id";
    $result = $conn->query($verify_sql);
    
    if (!$result || $result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Order not found or not assigned to you']);
        exit;
    }
    
    error_log('Order verified');
    
    // Ensure table exists (with correct schema matching server_create_order.php)
    $create_sql = "CREATE TABLE IF NOT EXISTS dine_in_order_items (
        id INT PRIMARY KEY AUTO_INCREMENT,
        dine_in_order_id INT NOT NULL,
        item_id INT NOT NULL,
        item_name VARCHAR(100) NOT NULL,
        quantity INT NOT NULL DEFAULT 1,
        unit_price DECIMAL(10, 2) NOT NULL,
        total_price DECIMAL(10, 2) NOT NULL,
        status VARCHAR(50) DEFAULT 'pending',
        is_reorder TINYINT(1) DEFAULT 0 COMMENT 'Indicates if this is a reordered item',
        special_instructions TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (dine_in_order_id) REFERENCES dine_in_orders(id) ON DELETE CASCADE,
        FOREIGN KEY (item_id) REFERENCES menu_items(id) ON DELETE RESTRICT
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
    
    $conn->query($create_sql);
    
    // Add is_reorder column if it doesn't exist
    $check_column_sql = "SHOW COLUMNS FROM dine_in_order_items LIKE 'is_reorder'";
    $column_result = $conn->query($check_column_sql);
    
    if (!$column_result || $column_result->num_rows === 0) {
        $alter_sql = "ALTER TABLE dine_in_order_items ADD COLUMN is_reorder TINYINT(1) DEFAULT 0 COMMENT 'Indicates if this is a reordered item'";
        $conn->query($alter_sql);
        error_log('Added is_reorder column to dine_in_order_items');
    }
    
    error_log('Table verified');
    
    // Process each item
    $inserted_count = 0;
    $updated_count = 0;
    
    foreach ($items as $item) {
        $item_id = (int)$item['id'];
        $quantity = (int)$item['quantity'];
        
        error_log("Processing item $item_id with quantity $quantity");
        
        // Get price and name from active menu.
        // If missing (item no longer in current menu), fall back to historical
        // order item data so reorder still works.
        $price_sql = "SELECT id, price, item_name FROM menu_items WHERE id = $item_id";
        $price_result = $conn->query($price_sql);
        
        $unit_price = 0.0;
        $menu_item_name = '';

        if ($price_result && $price_result->num_rows > 0) {
            $price_data = $price_result->fetch_assoc();
            $unit_price = (float)$price_data['price'];
            $menu_item_name = $price_data['item_name'];
        } else {
            // Historical fallback for discontinued/hidden menu items.
            $fallback_sql = "SELECT item_name, unit_price
                             FROM dine_in_order_items
                             WHERE dine_in_order_id = $order_id AND item_id = $item_id
                             ORDER BY id DESC
                             LIMIT 1";
            $fallback_result = $conn->query($fallback_sql);

            if (!$fallback_result || $fallback_result->num_rows === 0) {
                throw new Exception("Item $item_id not found in menu or order history");
            }

            $fallback_data = $fallback_result->fetch_assoc();
            $unit_price = (float)$fallback_data['unit_price'];
            $menu_item_name = $fallback_data['item_name'];
        }

        // Use provided item name if available, otherwise use resolved name.
        $item_name = isset($item['name']) && !empty($item['name']) ? $item['name'] : $menu_item_name;
        $total_price = $unit_price * $quantity;
        
        error_log("Item: $item_name, Unit Price: $unit_price, Quantity: $quantity, Total: $total_price");
        
        // Check if item already exists (and NOT served yet) - we only want to update pending/preparing items
        // For served items, we want to create a new reorder row
        $check_sql = "SELECT id, quantity, status FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND item_id = $item_id AND status != 'served'";
        $check_result = $conn->query($check_sql);
        
        if ($check_result && $check_result->num_rows > 0) {
            // Item exists and is NOT served, update with new quantity and prices
            $existing = $check_result->fetch_assoc();
            $new_qty = $existing['quantity'] + $quantity;  // ADD to existing quantity
            $new_total = $unit_price * $new_qty;
            
            $update_sql = "UPDATE dine_in_order_items SET quantity = $new_qty, total_price = $new_total WHERE dine_in_order_id = $order_id AND item_id = $item_id AND status != 'served'";
            
            if (!$conn->query($update_sql)) {
                throw new Exception('Update query failed: ' . $conn->error);
            }
            
            error_log("Item $item_id updated. Old qty: " . $existing['quantity'] . ", New qty: $new_qty");
            $updated_count++;
        } else {
            // Item doesn't exist in non-served status, insert as new
            // Check if this item was previously served (reorder scenario)
            $reorder_check_sql = "SELECT id FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND item_id = $item_id AND status = 'served' LIMIT 1";
            $reorder_check_result = $conn->query($reorder_check_sql);
            $is_reorder = ($reorder_check_result && $reorder_check_result->num_rows > 0) ? 1 : 0;
            
            $escaped_item_name = $conn->real_escape_string($item_name);
            $insert_sql = "INSERT INTO dine_in_order_items (dine_in_order_id, item_id, item_name, quantity, unit_price, total_price, status, is_reorder) VALUES ($order_id, $item_id, '$escaped_item_name', $quantity, $unit_price, $total_price, 'pending', $is_reorder)";
            
            if (!$conn->query($insert_sql)) {
                throw new Exception('Insert query failed: ' . $conn->error);
            }
            
            error_log("Item $item_id inserted. Is reorder: $is_reorder");
            $inserted_count++;
        }
    }
    
    // Recalculate order total
    $total_sql = "UPDATE dine_in_orders SET total_amount = (SELECT COALESCE(SUM(total_price), 0) FROM dine_in_order_items WHERE dine_in_order_id = $order_id) WHERE id = $order_id";
    
    if (!$conn->query($total_sql)) {
        throw new Exception('Total update failed: ' . $conn->error);
    }
    
    // Update order status back to 'confirmed' if new items have been added
    // This ensures the order appears in the kitchen dashboard for the new items
    $status_update_sql = "UPDATE dine_in_orders SET status = 'confirmed' WHERE id = $order_id AND ($inserted_count > 0 OR $updated_count > 0)";
    
    if (!$conn->query($status_update_sql)) {
        throw new Exception('Status update failed: ' . $conn->error);
    }
    
    error_log("Order total updated. Inserted: $inserted_count, Updated: $updated_count");
    
    echo json_encode([
        'success' => true,
        'message' => 'Items processed successfully',
        'order_id' => $order_id,
        'inserted' => $inserted_count,
        'updated' => $updated_count
    ]);
    
    error_log('=== Order update complete ===');
    
} catch (Exception $e) {
    error_log('ERROR: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
