<?php

namespace apexl\Io\modules\payment\callbacks;

use apexl\Io\modules\payment\entities\paymentEntity;
use apexl\Io\modules\payment\entities\paymentTokenEntity;
use apexl\Io\services\Output;
use apexl\Io\services\pathUtility;

class userLoginCallback {

    /**
     * Complete the activation of the latest valid token.
     * @param $match
     * @param $user
     * @param $request
     * @return void
     * @throws \Exception
     */
    public static function completeActivation($match, $user, $request)
    {
        if (isset($user->id) && $user->id) {
            $paymentToken = new paymentTokenEntity();
            $latestToken = $paymentToken->getLastForUser($user->id);
            if (isset($latestToken['id'])) {
                $paymentToken->load($latestToken['id']);
                if (!$paymentToken->setup_complete && $paymentToken->validated) {
                    $paymentToken->validateToken($request, ['user' => $user]);
                }
            }
        }
    }

    public static function displayPaymentNotifications($match, $user, $request)
    {
        if (isset($user->id) && $user->id) {
            $paymentEntity = new paymentEntity();
            $notifications = $paymentEntity->getPaymentNotifications($user->id);
            if (count($notifications) > 0) {
                $output = Output::getInstance();
                $path = pathUtility::getInstance();
                foreach ($notifications as $notification) {
                    if ($notification->status == 'successful') {
                        $output::addMessage($path->getRouteName($request), 'success',"Payment of {$notification->amount} successfully processed.");
                    } else {
                        $output::addMessage($path->getRouteName($request), 'error',"Payment of {$notification->amount} failed.");
                    }
                    $paymentEntity->load($notification->id);
                    $paymentEntity->user_notified = true;
                    $paymentEntity->store();
                }
            }
        }
    }
}