<?php

namespace Mtc\Plugins\NewsletterSignup\Classes;

use Illuminate\Support\Facades\App;
use Twig\Environment;

/**
 * NewsletterSignup Plugin Class
 *
 * Implements newsletter sign-up functionality
 * Renders newsletter_popup_trigger to footer if needed
 *
 * @author  Paul McAvoy <paul.mcavoy@mtcmedia.co.uk>
 * @author Uldis Zvirbulis <uldis.zvirbulis@mtcmedia.co.uk>
 * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @version 0.4
 */
class Newsletter
{

    public const DRIVER_MAILCHIMP = 'mailchimp';
    public const DRIVER_DEFAULT = 'default';
    /**
     * Echo trigger on page.
     * @access public
     * @throws \Exception
     */
    public static function addPopupTrigger(Environment $twig)
    {
        // echo trigger on page;
        echo $twig->render('includes/newsletter_popup_trigger.twig');
    }

    /**
     * Run a validation if email already is not in a newsletter list
     *
     * @param string $email email to validate
     * @return bool
     */
    public static function checkIfExists($email)
    {
        /** @var SignUpInterface $driver */
        $driver = App::make(SignUpInterface::class);
        try {
            return $driver->checkIfExists($email);
        } catch (\Exception $exception) {
            return false;
        }
    }

    /**
     * Attempt sign-up process
     *
     * @param string $email email address
     * @param array $additional_params additional info captured by sign-up form
     * @return bool|string success or failure text for sign-up
     */
    public static function signUp($email, $additional_params = [])
    {
        /** @var SignUpInterface $driver */
        $driver = App::make(SignUpInterface::class);
        try {
            return $driver->signUp($email, $additional_params);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * Attempt unsubscribe process
     *
     * @param string $email email address
     *
     * @return string success or failure text for unsubscribe
     */
    public static function unsubscribe($email)
    {
        /** @var SignUpInterface $driver */
        $driver = App::make(SignUpInterface::class);
        try {
            return $driver->unsubscribe($email);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
    }

    /**
     * Whether we're using default driver or not.
     *
     * If the driver is not set, or set to default, then we're using the default driver.
     *
     * @return bool
     */
    public static function isDefaultDriver(): bool
    {
        return empty(NEWSLETTER_DRIVER) ||
            NEWSLETTER_DRIVER === Newsletter::DRIVER_DEFAULT;
    }
}

