<?php

namespace YOOtheme\Builder\Newsletter;

use YOOtheme\Application;
use YOOtheme\Config;
use YOOtheme\Encrypter;
use YOOtheme\Http\Request;
use YOOtheme\Http\Response;
use YOOtheme\Translator;

class NewsletterController
{
    /**
     * @var Application
     */
    protected $app;

    /**
     * @var Config
     */
    protected $config;

    public function __construct(Application $app, Config $config)
    {
        $this->app = $app;
        $this->config = $config;
    }

    public function lists(Request $request, Response $response)
    {
        $settings = $request('settings');

        try {

            $provider = $this->getProvider($settings);

            if (!$provider) {
                $request->abort(400, 'Invalid provider');
            }

            return $response->withJson($provider->lists($settings));

        } catch (\Exception $e) {
            $request->abort(400, $e->getMessage());
        }
    }

    public function subscribe(Request $request, Response $response, Encrypter $encrypter, Translator $translator)
    {
        $settings = $encrypter->decrypt($request('settings'));

        try {

            $provider = $this->getProvider($settings);

            if (!$provider) {
                $request->abort(400, 'Invalid provider');
            }

            $provider->subscribe($request('email'), ['first_name' => $request('first_name', ''), 'last_name' => $request('last_name', '')], $settings);

        } catch (\Exception $e) {
            $request->abort(400, $e->getMessage());
        }

        $return = [
            'successful' => true,
        ];

        if ($settings['after_submit'] === 'redirect') {
            $return['redirect'] = $settings['redirect'];
        } else {
            $return['message'] = $translator->trans($settings['message']);
        }

        return $response->withJson($return);
    }

    /**
     * @param array $settings
     *
     * @throws \ReflectionException
     *
     * @return AbstractProvider|false
     */
    protected function getProvider($settings)
    {
        $name = isset($settings['name']) ? $settings['name'] : '';
        $service = $this->config->get("theme.newsletterProvider.{$name}", '');
        return $name && $service ? $this->app->get($service) : false;
    }
}
