<?php
/**
 * @author Colinet Julien
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Provider\Payment;

use CpCreation\VitiCore\Behavior\HasPayment;
use CpCreation\VitiCore\Bridge\Symfony\Bundle\Utils\Mailer;
use CpCreation\VitiCore\Cart\Model\Cart;
use CpCreation\VitiCore\Contact\Model\Contact;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;

class CheckProvider implements PaymentProviderInterface
{
    const TYPE = 'check';

    private $router;

    private $path;

    private $session;

    private $mailer;

    public function __construct(RouterInterface $router, SessionInterface $session, Mailer $mailer, $paths)
    {
        $this->router  = $router;
        $this->session = $session;
        $this->mailer  = $mailer;
        foreach ($paths as $path) {
            if ($path['name'] === $this->getMethod()) {
                $this->path = $path['path'];
            }
        }
    }

    /**
     * @param Contact    $contact
     * @param HasPayment $payment
     * @return RedirectResponse
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function checkout(Contact $contact, HasPayment $payment)
    {
        $this->session->set('cart', null);
        if ($payment instanceof Cart) {
            $this->mailer->sendOrder($contact, $payment);
        }

        return new RedirectResponse($this->router->generate($this->path, ['id' => $payment->getId()->toString()]));
    }

    /**
     * @return string
     */
    public function getMethod(): string
    {
        return static::TYPE;
    }
}
