<?php
/**
 * Credorax Payments For Magento 2
 * https://www.credorax.com/
 *
 * @category Credorax
 * @package  WC_Credorax
 * @author   Girit-Interactive (https://www.girit-tech.com/)
 */

 if (! defined('ABSPATH')) {
     exit; // Exit if accessed directly.
 }

/**
 * Credorax payment card tokenization model.
 */
class WC_Credorax_Model_CardTokenization
{
    /**
     * @method processCardPaymentToken
     * @param  WC_Order                $order
     * @param  string                  $token
     * @return WC_Credorax_Model_Token
     */
    public static function saveCcToken(WC_Order $order, $token)
    {
        $alreadyExists = (array) WC_Payment_Tokens::get_tokens([
            'token_id'   => $order->get_meta(WC_Credorax_Gateway::KEY_CC_TOKEN_ID) ?: '',
            'user_id'    => get_current_user_id(),
            'gateway_id' => WC_Credorax_Gateway::GATEWAY_ID,
            'type'       => WC_Credorax_Gateway::GATEWAY_ID,
            'token'      => (string)$token,
        ]);
        if (count($alreadyExists)) {
            $tkn = array_pop($alreadyExists);
        } else {
            $tkn = new WC_Credorax_Model_Token($order->get_meta(WC_Credorax_Gateway::KEY_CC_TOKEN_ID));
        }

        $tkn->set_token((string)$token);
        $tkn->set_gateway_id(WC_Credorax_Gateway::GATEWAY_ID);
        $tkn->set_card_type($order->get_meta(WC_Credorax_Gateway::KEY_CC_TYPE));
        $tkn->set_last4(substr($order->get_meta(WC_Credorax_Gateway::KEY_CC_LAST_4), -4));
        $tkn->set_card_number($order->get_meta(WC_Credorax_Gateway::KEY_CC_NUMBER));
        $tkn->set_expiry_month($order->get_meta(WC_Credorax_Gateway::KEY_CC_EXP_MONTH));
        $tkn->set_expiry_year($order->get_meta(WC_Credorax_Gateway::KEY_CC_EXP_YEAR));
        $tkn->set_card_owner($order->get_meta(WC_Credorax_Gateway::KEY_CC_OWNER));
        $tkn->set_user_id(get_current_user_id());
        $tkn->save();

        $order->add_meta_data(WC_Credorax_Gateway::KEY_CC_TOKEN, $tkn->get_token(), true);
        $order->add_meta_data(WC_Credorax_Gateway::KEY_CC_TOKEN_ID, $tkn->get_id(), true);

        return $tkn;
    }
}
