<?php

use Mtc\Plugins\NewsletterSignup\Classes\Newsletter;
use Mtc\Plugins\NewsletterSignup\Classes\NewSubscriberEvent;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;

$path = __DIR__ . '/../../../';
require_once $path . 'core/includes/header.inc.php';

$newsletter_success = false;

$errors  = [];
$success = [];

// if popup clicked render popup form
if (!empty($_REQUEST['newsletter_popup'])) {
    echo $twig->render('/includes/pages/newsletter/newsletter_form.twig', [
        'p'          => $newsletter_page,
        'in_overlay' => true,
    ]);

    // else validate form
} else {
    if (!empty($_REQUEST['newsletter_action'])
        && $_REQUEST['newsletter_action'] === 'newsletter_subscribe'
        && !$newsletter_success) {
        $validation = [
            'newsletter_first_name' => 'Please enter your first name.',
            'newsletter_surname'    => 'Please enter your surname.',
            'newsletter_email'      => '',
        ];

        $newsletter_email = filter_input(INPUT_POST, 'newsletter_email');
        foreach ($validation as $key => $message) {
            switch ($key) {
                case 'newsletter_email':
                    if (empty($newsletter_email)) {
                        $errors['newsletter_email'] = 'You did not enter an email address.';
                    } elseif (!filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)) {
                        $errors['newsletter_email'] = 'This email address is not valid.';
                    } elseif (Newsletter::checkIfExists($newsletter_email)) {
                        $errors['newsletter_email'] = 'You are already subscribed to the newsletter.';
                    }
                    break;
                default:
                    if (isset($_REQUEST[$key]) && empty($_REQUEST[$key])) {
                        $errors[$key] = $message;
                    }
                    break;
            }
        }

        if (empty($errors)) {
            $sign_up_params = [
                'email'      => $newsletter_email,
                'first_name' => filter_input(INPUT_POST, 'newsletter_first_name'),
                'last_name'  => filter_input(INPUT_POST, 'newsletter_surname'),
            ];
            $failure_text   = Newsletter::signUp($newsletter_email, $sign_up_params);
            if ($failure_text && $failure_text !== true) {
                $errors['newsletter_email'] = $failure_text;
            } else {
                $newsletter_success   = true;
                $success['message']   = 'Thank you for subscribing to our mailing list. <a href="/members/">Click here to register.</a>';
                $success['title']     = '';
                $success['hide_form'] = true;
            }

            Event::dispatch(new NewSubscriberEvent($_REQUEST));
        }

        $newsletter_details = [
            'errors'  => $errors,
            'success' => $success,
            'request' => $_REQUEST,
        ];

        if (!empty($_REQUEST['ajax'])) {
            $json = [
                'errors'  => $errors,
                'success' => $success,
            ];

            echo json_encode($json);
            exit();
        }

        $twig->addGlobal("newsletter_details", $newsletter_details);
    } elseif (!empty($_REQUEST['newsletter_success'])) {
        $newsletter_success            = true;
        $newsletter_details['success'] = $newsletter_success;
        $twig->addGlobal("newsletter_details", $newsletter_details);
    }
}
