<?php
/**
 * Server Remove Order API - Cancel dine-in orders
 * Allows servers to remove/cancel their placed orders
 */

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

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

// 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']);
    exit;
}

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

try {
    error_log('=== Cancelling order ' . $order_id . ' ===');
    
    // Verify order ownership
    $verify_sql = "SELECT id, server_id, status 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 already served or completed
    if ($order_data['status'] === 'served' || $order_data['status'] === 'completed') {
        echo json_encode(['success' => false, 'message' => 'Cannot remove order that has been served']);
        exit;
    }

    $served_items_sql = "SELECT COUNT(*) AS served_count FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND status = 'served'";
    $served_items_result = $conn->query($served_items_sql);
    $served_items_data = $served_items_result ? $served_items_result->fetch_assoc() : ['served_count' => 0];

    if ((int)($served_items_data['served_count'] ?? 0) > 0) {
        echo json_encode(['success' => false, 'message' => 'Cannot remove this order because some items are already served']);
        exit;
    }
    
    error_log('Order verified for server ' . $server_id);
    
    // Delete order items first (due to foreign key constraint)
    $delete_items_sql = "DELETE FROM dine_in_order_items WHERE dine_in_order_id = $order_id";
    if (!$conn->query($delete_items_sql)) {
        throw new Exception('Failed to delete order items: ' . $conn->error);
    }
    
    error_log('Order items deleted');
    
    // Delete the order itself
    $delete_order_sql = "DELETE FROM dine_in_orders WHERE id = $order_id";
    if (!$conn->query($delete_order_sql)) {
        throw new Exception('Failed to delete order: ' . $conn->error);
    }
    
    error_log('Order deleted');
    
    // Return success
    echo json_encode([
        'success' => true,
        'message' => 'Order cancelled successfully',
        'order_id' => $order_id
    ]);
    
    error_log('=== Order cancellation complete ===');
    
} catch (Exception $e) {
    error_log('ERROR: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
