<?php
include '../db.php';

// KDS endpoints don't require full authentication but should be protected
// Check for a simple KDS access token or allow direct access for now
// In production, you might want to implement a proper KDS authentication system

// For now, allow direct access to KDS endpoints

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

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

$order_type = $input['order_type']; // 'hold' or 'sale'
$order_id = intval($input['order_id']);

try {
    // Begin transaction
    $conn->begin_transaction();
    
    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
        $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_number = 'SALE-' . str_pad($order_id, 6, '0', STR_PAD_LEFT);
        $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 item details
            $item_details = $conn->query("SELECT * FROM items WHERE id = {$item['item_id']}")->fetch_assoc();
            
            $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, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
            ");
            
            $total_price = $item['quantity'] * $item['unit_price'];
            
            $stmt->bind_param("iiisidd", 
                $kds_order_id, $item['id'], $item['item_id'], $item['item_name'], $item['quantity'],
                $item['unit_price'], $total_price
            );
            $stmt->execute();
            $stmt->close();
        }
        
    } else {
        throw new Exception('Invalid order type. Only "sale" is supported.');
    }
    
    // Log activity
    $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();
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'success' => true, 
        'message' => 'KDS order created successfully',
        'kds_order_id' => $kds_order_id,
        'order_number' => $order_number ?? ''
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
