<?php

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

/**
 * Handles the selection of a payment card during checkout.
 * Stores the selected card ID in the session and proceeds to address step.
 */
function handleCardSelection(array $params, int $chat_id, ?int $message_id, int $user_id, string $platform, array $session_data, array $user): void {
    $selected_card_id = (int)($params['card_id'] ?? 0);
    $callback_query_id = $GLOBALS['update']['callback_query']['id'] ?? null;
    $can_edit = ($message_id !== null);

    if ($selected_card_id <= 0) {
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا در اطلاعات کارت.', 'show_alert' => true], $platform);
        // Go back to card selection
        startCheckout([], $chat_id, $message_id, $user_id, $platform, $user);
        return;
    }

    // Verify the selected card belongs to the user
    $card_exists = false;
    $user_cards = getUserCards($user_id); // Assumes CardQueries loaded
    foreach($user_cards as $card) {
        if (($card['id'] ?? 0) == $selected_card_id) {
            $card_exists = true;
             break;
        }
    }

    if ($card_exists) {
        // Store selected card ID in session
        $session_data['selected_card_id'] = $selected_card_id;
        // Reset address fields and state for address step
        unset($session_data['checkout']['province'], $session_data['checkout']['city']);
        unset($session_data['checkout']['address_text'], $session_data['checkout']['postal_code']);
        unset($session_data['checkout']['note']);
        $session_data['state'] = 'awaiting_checkout_province';
         updateUserField($user_id, 'session', json_encode($session_data));

        // Show province selection keyboard
        $province_keyboard_markup = buildProvinceKeyboard(0); // Assumes KeyboardBuilders loaded
        $prov_text = "کارت انتخاب شد. لطفا استان محل سکونت خود را انتخاب کنید:";
        if ($can_edit) {
            editMessage($chat_id, $message_id, $prov_text, $province_keyboard_markup);
        } else {
            sendMessage($chat_id, $prov_text, $province_keyboard_markup, $platform);
        }
    } else {
        // Card doesn't belong to user or is invalid
        if ($callback_query_id) apiRequest('answerCallbackQuery', ['callback_query_id' => $callback_query_id, 'text' => 'خطا: کارت انتخاب شده نامعتبر است.', 'show_alert' => true], $platform);
        // Go back to card selection
        startCheckout([], $chat_id, $message_id, $user_id, $platform, $user);
    }
}

?>