<?php

/**
 *
 * @category MultiSafepay
 * @package  MultiSafepay_Msp
 */
class MultiSafepay_Msp_Block_Tokenization extends Mage_Payment_Block_Form
{
    /**
     * Construct
     */
    protected function _construct()
    {
        $tokenization = Mage::getStoreConfigFlag('msp/settings/enable_tokenization');
        if ($tokenization) {
            parent::_construct();
            $this->setTemplate('msp/tokenization.phtml');
        }
    }

    public function getRecurrings($paymentMethod, $customerId = null)
    {
        if ($customerId === null || !is_int($customerId)) {
            if (Mage::getSingleton('customer/session')->isLoggedIn()) {
                $customerId = Mage::getSingleton('customer/session')->getCustomer()->getId();
            } else {
                return array();
            }
        }
        $tokenization = Mage::getModel("msp/tokenization")->getCollection()->addFieldToFilter('customer_id', $customerId);

        $array = array();

        $_paymentMethod = explode("_", $paymentMethod);

        $_paymentMethod = $_paymentMethod[1];

        foreach ($tokenization as $token) {
            if (!is_null($token['cc_type']) && !is_null($token['cc_last4'])) {
                if (strtolower($token['cc_type']) === strtolower($_paymentMethod)) {
                    array_push(
                        $array,
                        [
                            "label" => (!is_null($token['cc_name']) || !empty($token['cc_name'])) ? $token['cc_name'] : "{$token['cc_type']} - {$token['cc_last4']}",
                            "value" => $token['recurring_hash']
                        ]
                    );
                }
            }
        }
        return $array;
    }
}
