<?php

namespace KupShop\OrderDiscountBundle\Triggers\Frontend;

use KupShop\OrderDiscountBundle\Triggers\IsicTrigger;
use KupShop\OrderingBundle\Util\ISIC\AliveCard;

class IsicHandler extends BaseTriggerHandler
{
    /** @required */
    public AliveCard $aliveCard;

    protected $template = 'order_discount/triggers/isic.tpl';
    public $templateType = 'isic';

    public function processData($userData, array $persistenData): array
    {
        if ($userData['delete'] ?? false) {
            return ['success' => false];
        }

        if (($userData['name'] ?? false) && ($userData['id'] ?? false)) {
            if (($persistenData['name'] ?? false)
                && ($persistenData['id'] ?? false)
                && $userData['name'] == $persistenData['name'] && $userData['id'] == $persistenData['id']) {
                return $persistenData;
            }

            if ($result = $this->aliveCard->validate($this->userData['id'], $this->userData['name'])) {
                return [
                    'success' => true,
                    'id' => $result['cardNumber'],
                    'name' => $result['cardholderName'],
                    'verificationId' => $result['id'],
                ];
            } else {
                return [
                    'success' => false,
                    'id' => $userData['id'],
                    'name' => $userData['name'],
                    'error' => $this->aliveCard->getErrorMessage($this->aliveCard->error),
                ];
            }
        }

        if ($userData['success'] ?? false) {
            return $userData;
        }

        return $persistenData;
    }

    /** Dostávám v argumentu data od uživatele, které jsou zpracovány a následně se ukládají jako nový persistentData */
    public function handleData($data): array
    {
        $this->userData = $data[IsicTrigger::getType()] ?? [];

        return $this->persistentData = $this->processData($this->userData, $this->getPersistentData());
    }
}
