<?php
/**
 * Generate KOT (Kitchen Order Ticket) API
 * Called when an order is sent to the kitchen
 * Phase 2: KOT Generation System
 */

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    sendResponse(false, 'Only POST method allowed', null);
}

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

if (!isset($input['order_id'])) {
    sendResponse(false, 'Missing order_id', null);
}

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

try {
    // 1. Verify order exists
    $order_sql = "
        SELECT 
            o.id,
            o.order_number,
            o.table_id,
            o.server_id,
            o.total_amount,
            o.status,
            o.special_requests,
            rt.table_number,
            rt.section,
            rt.floor_level,
            s.name as server_name
        FROM dine_in_orders o
        LEFT JOIN restaurant_tables rt ON o.table_id = rt.id
        LEFT JOIN servers s ON o.server_id = s.id
        WHERE o.id = ?
    ";
    
    $stmt = $conn->prepare($order_sql);
    $stmt->bind_param('i', $order_id);
    $stmt->execute();
    $order_result = $stmt->get_result();
    
    if ($order_result->num_rows === 0) {
        sendResponse(false, 'Order not found', null);
    }
    
    $order = $order_result->fetch_assoc();
    $stmt->close();

    // 2. Check if KOT already exists for this order
    $existing_kot = $conn->query("SELECT id FROM kot_tickets WHERE order_id = $order_id");
    if ($existing_kot->num_rows > 0) {
        $existing = $existing_kot->fetch_assoc();
        sendResponse(false, 'KOT already exists for this order', ['kot_id' => $existing['id']]);
    }

    // 3. Generate unique ticket number
    $ticket_number = 'KOT-' . date('YmdHis') . '-' . mt_rand(100, 999);

    // 4. Determine priority based on special requests or urgency
    $priority = 'normal';
    if ($order['special_requests'] && (
        stripos($order['special_requests'], 'urgent') !== false ||
        stripos($order['special_requests'], 'rush') !== false
    )) {
        $priority = 'urgent';
    }

    // 5. Insert KOT ticket
    $insert_kot = "
        INSERT INTO kot_tickets (
            order_id, 
            ticket_number, 
            status, 
            priority,
            table_number,
            server_name,
            special_instructions
        ) VALUES (?, ?, 'pending', ?, ?, ?, ?)
    ";
    
    $stmt = $conn->prepare($insert_kot);
    $stmt->bind_param(
        'isssss',
        $order_id,
        $ticket_number,
        $priority,
        $order['table_number'],
        $order['server_name'],
        $order['special_requests']
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to create KOT: ' . $stmt->error);
    }
    
    $kot_id = $stmt->insert_id;
    $stmt->close();

    // 6. Get order items for KOT details
    $items_sql = "
        SELECT 
            doi.id,
            doi.item_id,
            doi.item_name,
            doi.quantity,
            doi.unit_price,
            doi.special_instructions,
            mi.item_code
        FROM dine_in_order_items doi
        LEFT JOIN menu_items mi ON doi.item_id = mi.id
        WHERE doi.dine_in_order_id = ?
        ORDER BY doi.created_at ASC
    ";
    
    $stmt = $conn->prepare($items_sql);
    $stmt->bind_param('i', $order_id);
    $stmt->execute();
    $items_result = $stmt->get_result();
    
    $items = [];
    while ($item = $items_result->fetch_assoc()) {
        $items[] = $item;
    }
    $stmt->close();

    sendResponse(true, 'KOT generated successfully', [
        'kot_id' => $kot_id,
        'ticket_number' => $ticket_number,
        'order_id' => $order_id,
        'order_number' => $order['order_number'],
        'table_number' => $order['table_number'],
        'section' => $order['section'],
        'floor' => $order['floor_level'],
        'server_name' => $order['server_name'],
        'priority' => $priority,
        'item_count' => count($items),
        'generated_at' => date('Y-m-d H:i:s')
    ]);

} catch (Exception $e) {
    http_response_code(500);
    sendResponse(false, $e->getMessage(), null);
}

$conn->close();
?>
