<?php
namespace Mnv\Modules;

use Mnv\Core\Locale\I18N;
use Mnv\Core\Validations\ValidateEmail;
use Mnv\Models\Users\UserTypes;

require_once GLOBAL_ROOT . '/includes/admin-functions.inc.php';

/**
 * Class Newsletter
 * @package Mnv\Modules
 */
class Newsletter
{
    protected string $table = 'subscribe';

    private static $email;
    private static $datetime = null;
    private static $valid = true;

    public $response = [];

    public function register($email)
    {

        self::$email    = $email;
        self::$datetime = date('Y-m-d H:i:s');

        if (empty(self::$email)) {

            $this->response = array('status' => 403, 'type' => 'error', 'message' => I18N::locale(
                "Поле email адреса не должно быть пустым.",
                "Elektron pochta manzili maydoni bo'sh bo'lmasligi kerak.",
                "The email address field should not be empty."
            ));

            self::$valid = false;
        }
        // валидация email
        else if (!filter_var(self::$email, FILTER_VALIDATE_EMAIL)) {

            $this->response = array('status' => 403, 'type' => 'error', 'message' => I18N::locale(
                "Вы должны заполнить поле действительным адресом электронной почты",
                "Siz maydonni haqiqiy elektron pochta manzili bilan to'ldirishingiz kerak",
                "You must fill in the field with a valid email address"
            ));

            self::$valid = false;
        }


        if (self::$valid) {
            $existingSignup = connect($this->table)->count('*')->where('email', $email)->getValue();
            $data_exists = $existingSignup > 0;

            if (!$data_exists) {
                $insert = connect($this->table)->insert([
                    'email'     => self::$email,
//                    'userType'  => UserTypes::SUBSCRIBER,
                    'registered'   => self::$datetime]
                );

                if ($insert) {
                    $this->response = array('status' => 200, 'type' => 'success', 'message' => I18N::locale(
                        "Вы успешно подписаны",
                        "Siz muvaffaqiyatli obuna bo'ldingiz",
                        "You have been successfully subscribed"
                    ));
                } else {
                    $this->response = array('status' => 403, 'type' => 'error', 'message' => I18N::locale(
                        "Произошла ошибка. Пожалуйста, попробуйте еще раз",
                        "Xato yuz berdi. Iltimos, yana urinib ko'ring",
                        "An error has occurred. Please try again"
                    ));
                }
            } else {
                $this->response = array('status' => 403, 'type' => 'error', 'message' => I18N::locale(
                    "Это email уже подписан",
                    "Bu elektron pochta allaqachon imzolangan",
                    "This email is already signed"
                ));
            }
        }
    }

}