<?php
/**
 * Server Remove Order Item API - Remove individual items from dine-in orders
 * Allows servers to remove specific items from 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']) || !isset($input['item_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

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

try {
    error_log('=== Removing item ' . $item_id . ' from 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 items from served orders']);
        exit;
    }
    
    error_log('Order verified for server ' . $server_id);
    
    // Check if item exists in the order
    $check_sql = "SELECT id, quantity FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND item_id = $item_id";
    $check_result = $conn->query($check_sql);
    
    if (!$check_result || $check_result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Item not found in this order']);
        exit;
    }
    
    error_log('Item exists in order');
    
    // Delete ONLY non-served items with this item_id (reorders/pending items)
    // This prevents accidentally deleting served items when removing reorders
    $delete_sql = "DELETE FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND item_id = $item_id AND status != 'served'";
    if (!$conn->query($delete_sql)) {
        throw new Exception('Failed to delete item: ' . $conn->error);
    }
    
    error_log('Item deleted');
    
    // Recalculate order total
    $total_sql = "UPDATE dine_in_orders SET total_amount = (SELECT COALESCE(SUM(total_price), 0) FROM dine_in_order_items WHERE dine_in_order_id = $order_id) WHERE id = $order_id";
    
    if (!$conn->query($total_sql)) {
        throw new Exception('Total update failed: ' . $conn->error);
    }
    
    error_log('Order total updated');
    
    // Get updated order details
    $order_sql = "SELECT total_amount FROM dine_in_orders WHERE id = $order_id";
    $order_result = $conn->query($order_sql);
    $order_info = $order_result->fetch_assoc();
    
    echo json_encode([
        'success' => true,
        'message' => 'Item removed successfully',
        'order_id' => $order_id,
        'new_total' => (float)$order_info['total_amount']
    ]);
    
    error_log('=== Item removal complete ===');
    
} catch (Exception $e) {
    error_log('ERROR: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
