<?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']) && !isset($input['row_id']))
) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$order_id = (int)$input['order_id'];
$item_id = isset($input['item_id']) ? (int)$input['item_id'] : 0;
$row_id = isset($input['row_id']) ? (int)$input['row_id'] : 0;

try {
    error_log('=== Removing item from order ' . $order_id . ' (item_id=' . $item_id . ', row_id=' . $row_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
    if ($row_id > 0) {
        $check_sql = "SELECT id, item_id, quantity, status FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND id = $row_id";
    } else {
        $check_sql = "SELECT id, item_id, quantity, status 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;
    }
    
    $item_row = $check_result->fetch_assoc();

    if (($item_row['status'] ?? '') === 'served') {
        echo json_encode(['success' => false, 'message' => 'Served items cannot be removed']);
        exit;
    }

    error_log('Item exists in order');
    
    // Delete the specific row when available so served/reordered rows are handled correctly.
    if ($row_id > 0) {
        $delete_sql = "DELETE FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND id = $row_id";
    } else {
        $delete_sql = "DELETE FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND item_id = $item_id";
    }
    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()
    ]);
}
?>
