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

/**
 * Handles +/- buttons to update item quantity in the cart.
 */
function handleUpdateQuantity(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $user): void {
    $item_id = (int)($params['item_id'] ?? 0); 
    $change = $params['change'] ?? '0'; 
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null; 

    if ($item_id <= 0 || !in_array($change, ['+1', '-1'])) { 
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطای پارامترها.', 'show_alert' => true], $platform); 
        return; 
    }

    try {
        
        $pdo = pdo(); 
        $pdo->beginTransaction(); 

        $stmt_item = $pdo->prepare("SELECT c.quantity, p.stock FROM carts c JOIN products p ON c.product_id = p.id WHERE c.id = ? AND c.user_id = ? FOR UPDATE"); 
        $stmt_item->execute([$item_id, $user_id]); 
        $item_data = $stmt_item->fetch(); 

        if (!$item_data) {
            $pdo->rollBack(); 
            if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: آیتم یافت نشد.', 'show_alert' => true], $platform); 
            
            showCart($chat_id, $user_id, $message_id, $platform, $user); 
            return; 
        }

        $current_quantity = $item_data['quantity']; 
        $stock = $item_data['stock']; 
        $new_quantity = bcadd((string)$current_quantity, $change, 1); 

        
        if (bccomp($new_quantity, '0', 1) <= 0) { 
            deleteCartItem($item_id); 
            $pdo->commit(); 
            if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'آیتم از سبد حذف شد.'], $platform); 
        } else {
            
            if ($change === '+1' && $stock !== null && bccomp((string)$stock, $new_quantity, 1) < 0) { 
                $pdo->rollBack(); 
                if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'موجودی کافی نیست!', 'show_alert' => true], $platform); 
                return; 
            }
            
            updateCartItemQuantity($item_id, $new_quantity); 
            $pdo->commit(); 
            if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'تعداد به‌روز شد.'], $platform); 
        }

        
        showCart($chat_id, $user_id, $message_id, $platform, $user); 

    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) {
            $pdo->rollBack(); 
        }
        if (defined('ERROR_LOG_PATH')) { file_put_contents(ERROR_LOG_PATH, date('Y-m-d H:i:s') . " - Error updating cart quantity for item {$item_id}: " . $e->getMessage() . "\n", FILE_APPEND); } 
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا در به‌روزرسانی سبد.', 'show_alert' => true], $platform); 
         
         showCart($chat_id, $user_id, $message_id, $platform, $user);
    }
}
?>