<?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 (consistent with other KDS endpoints)

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

// Get the request data
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

if ($action === 'restore_to_kds') {
    $order_id = intval($input['order_id'] ?? 0);
    $restore_status = $input['restore_status'] ?? 'ready'; // 'ready' or 'preparing'
    
    if ($order_id <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid order ID']);
        exit;
    }
    
    // Validate restore status
    if (!in_array($restore_status, ['pending', 'preparing', 'ready'])) {
        $restore_status = 'pending';
    }
    
    try {
        // Start transaction
        $conn->begin_transaction();
        
        // Check if order exists and is currently served/completed
        $check_query = "SELECT id, order_status FROM kds_orders WHERE id = ?";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param("i", $order_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows === 0) {
            $conn->rollback();
            echo json_encode(['success' => false, 'message' => 'Order not found']);
            exit;
        }
        
        $order = $check_result->fetch_assoc();
        
        // Only allow restoring if order is currently served or completed
        if (!in_array($order['order_status'], ['served', 'completed'])) {
            $conn->rollback();
            echo json_encode(['success' => false, 'message' => 'Order is not in a completed state']);
            exit;
        }
        
        // Update the order status
        $update_order_query = "UPDATE kds_orders SET order_status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $update_order_stmt = $conn->prepare($update_order_query);
        $update_order_stmt->bind_param("si", $restore_status, $order_id);
        $update_order_stmt->execute();
        
        // Update all order items to the appropriate status
        $item_status = 'pending'; // Always restore items to pending status
        $update_items_query = "UPDATE kds_order_items SET item_status = ? WHERE kds_order_id = ?";
        $update_items_stmt = $conn->prepare($update_items_query);
        $update_items_stmt->bind_param("si", $item_status, $order_id);
        $update_items_stmt->execute();
        
        // Log the restoration activity (temporarily commented out to avoid table structure issues)
        // Since this is a KDS endpoint without authentication, we'll skip detailed logging
        // In production, you might want to implement a simple KDS activity log
        
        // $log_details = "Order restored to KDS with status: " . $restore_status;
        // $log_query = "INSERT INTO kds_activity_log (kds_order_id, action, details, created_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)";
        // $log_stmt = $conn->prepare($log_query);
        // $log_stmt->bind_param("iss", $order_id, $action, $log_details);
        // $log_stmt->execute();
        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Order successfully restored to KDS',
            'order_status' => $restore_status
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
    
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
}
?>
