<?php
// Prevent direct script access
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
    die('No direct script access allowed'); //
}

/**
 * Handles removing an item from the cart via the delete button.
 * Logic from a.txt customer_handler.php, case 'removeCartItem' callback [cite: 4949-4961]
 */
function handleRemoveItem(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform): void {
    $item_id = (int)($params['item_id'] ?? 0); //
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null; //

    if ($item_id <= 0) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطای پارامتر.', 'show_alert' => true], $platform); //
        return; //
    }

    // Check if item belongs to user before deleting (optional but safer)
    $stmt_check = pdo()->prepare("SELECT COUNT(*) FROM carts WHERE id = ? AND user_id = ?");
    $stmt_check->execute([$item_id, $user_id]);
    if ($stmt_check->fetchColumn() > 0) {
        if (deleteCartItem($item_id)) { //
            if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'آیتم از سبد حذف شد.'], $platform); //
        } else {
            if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا در حذف آیتم.', 'show_alert' => true], $platform); //
        }
    } else {
         if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: آیتم یافت نشد.', 'show_alert' => true], $platform);
    }


    // Refresh the cart view regardless
    showCart($chat_id, $user_id, $message_id, $platform); //
}
?>