<?php

namespace Hyperpay\Gateways\Helpers;

use WC_Payment_Token_CC;
use WC_Payment_tokens;

class TokenManager
{
    const TOKENIZATION_AMOUNT = "0.01";
    
    private static function is_exists($registration_id)
    {
        if (empty($registration_id) || !get_current_user_id()) {
            return false;
        }

        $token_manager = null;

        foreach (WC_Payment_tokens::get_customer_tokens(get_current_user_id()) ?? [] as $token) {
            if ($token->get_token() === $registration_id) {
                $token_manager = $token;
                break;
            }
        }

        return $token_manager;
    }

    public static function save($registration_id, $details,  $gateway_id)
    {
        
        if ($token_manager = self::is_exists($registration_id)) {
            return $token_manager;
        }
        $token_manager = new WC_Payment_Token_CC();
        $token_manager->set_token($registration_id);
        $token_manager->set_last4($details['last4Digits'] ?? '****');
        $token_manager->set_expiry_year($details['expiryYear'] ?? '****');
        $token_manager->set_expiry_month($details['expiryMonth'] ?? '****');
        $token_manager->set_card_type($details['paymentBrand'] ?? 'unknown');
        $token_manager->set_gateway_id($gateway_id);
        $token_manager->set_user_id(get_current_user_id());
        $token_manager->add_meta_data('agreement_id', $details['recurringPaymentAgreement'] ?? '', true);
        $token_manager->add_meta_data('initial_transaction_id', $details['initial_tx_id'] ?? '', true);
        $token_manager->save();

        return $token_manager;
    }

}
