<?php
/**
 * Send Order to Kitchen API
 * Allows servers to send a placed order to the kitchen for preparation
 * Changes order status from 'pending' to 'confirmed' (sent to kitchen)
 */

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

// Check server authentication
if (!isset($_SESSION['server_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

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

if (!$input || !isset($input['order_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request. Missing order_id.']);
    exit;
}

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

try {
    // Verify order ownership
    $verify_sql = "SELECT id, server_id, status, table_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;
    }
    
    $order_data = $result->fetch_assoc();
    
    // Check if order is in pending, confirmed, or ready status (new order or adding items to existing order)
    // 'ready' status is allowed because server might add items to an order that was previously ready
    if ($order_data['status'] !== 'pending' && $order_data['status'] !== 'confirmed' && $order_data['status'] !== 'ready') {
        echo json_encode(['success' => false, 'message' => 'Order is in an invalid status for kitchen. Current status: ' . $order_data['status']]);
        exit;
    }
    
    // Update order status to 'confirmed' (ready for kitchen to start preparing)
    // If already confirmed, this will keep it confirmed (idempotent)
    // If status was 'ready', it goes back to 'confirmed' because new items were added
    $update_sql = "UPDATE dine_in_orders SET status = 'confirmed' WHERE id = $order_id";
    
    if (!$conn->query($update_sql)) {
        throw new Exception('Failed to update order status: ' . $conn->error);
    }
    
    // Generate KOT (Kitchen Order Ticket) if not already exists
    $kot_check = $conn->query("SELECT id FROM kot_tickets WHERE order_id = $order_id");
    $kot_data = null;
    
    if ($kot_check->num_rows === 0) {
        // Generate new KOT
        $ticket_number = 'KOT-' . date('YmdHis') . '-' . mt_rand(100, 999);
        $priority = 'normal';
        
        // Check for urgent requests
        $order_check = $conn->query("SELECT special_requests FROM dine_in_orders WHERE id = $order_id");
        $order_row = $order_check->fetch_assoc();
        if ($order_row['special_requests'] && stripos($order_row['special_requests'], 'urgent') !== false) {
            $priority = 'urgent';
        }
        
        $INSERT_kot = "INSERT INTO kot_tickets (order_id, ticket_number, status, priority) VALUES ($order_id, '$ticket_number', 'pending', '$priority')";
        if ($conn->query($INSERT_kot)) {
            $kot_id = $conn->insert_id;
            $kot_data = [
                'kot_id' => $kot_id,
                'ticket_number' => $ticket_number,
                'priority' => $priority
            ];
        }
    } else {
        $kot_id_row = $kot_check->fetch_assoc();
        $kot_data = ['kot_id' => $kot_id_row['id']];
    }
    
    // Get updated order details
    $order_details_sql = "SELECT id, order_number, table_id, total_amount, status FROM dine_in_orders WHERE id = $order_id";
    $order_result = $conn->query($order_details_sql);
    $order_details = $order_result->fetch_assoc();
    
    $response = [
        'success' => true,
        'message' => 'Order sent to kitchen successfully',
        'order_id' => $order_id,
        'order_number' => $order_details['order_number'],
        'table_id' => $order_details['table_id'],
        'status' => $order_details['status'],
        'total_amount' => (float)$order_details['total_amount']
    ];
    
    // Add KOT data if generated
    if ($kot_data) {
        $response['kot'] = $kot_data;
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
