<?php

namespace Amwdeveloper\controller;

use Amwdeveloper\core\confirmEmail;
use Amwdeveloper\core\session;
use Amwdeveloper\model\layer;
use Amwdeveloper\model\message;
use Amwdeveloper\plugins\whatsapp\send;

class register extends layer
{
    public $message;
    public $session;
    public function account($request)
    {
        $this->message = new message();
        $this->session = new session();
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $user = filter_var($request['user'], FILTER_SANITIZE_SPECIAL_CHARS);
        $passwd = filter_var($request['passwd'], FILTER_SANITIZE_SPECIAL_CHARS);
        $repasswd = filter_var($request['repasswd'], FILTER_SANITIZE_SPECIAL_CHARS);
        $email = filter_var($request['email'], FILTER_VALIDATE_EMAIL);
        $reemail = filter_var($request['reemail'], FILTER_VALIDATE_EMAIL);
        $pid = $request['pid'];
        $terms = isset($request['terms'])
            ? true
            : false;
        $idRef = isset($request['id_ref'])
            ? filter_var($request['id_ref'], FILTER_SANITIZE_FULL_SPECIAL_CHARS)
            : null;

        if (requests_form("fail_register", 5, 10)) {
            $this->message->class("error")->text("IP: {$_SERVER['REMOTE_ADDR']}, bloqueado por <em><strong>10 minutos</strong></em>")->flash(true);
            return null;
        }

        if (empty($name) or empty($user) or empty($passwd) or empty($email)) {
            $this->message->class("error")->text("Campos <em><strong>obrigatórios</strong></em> vázio")->flash();
            return null;
        }

        /** Name */
        if (strlen($name) < 4 or strlen($name) > 10 or !preg_match("/^[a-zA-Z]+$/i", $name)) {
            $this->message->class("error")->text("Seu nome deve <em><strong>conter 4 à 10 caracteres</strong></em>, <br> <em><strong>não use (acentuações ou números)</strong></em>")->flash();
            return null;
        }

        /** User */
        if (strlen($user) < 4 or strlen($user) > 10) {
            $this->message->class("error")->text("Seu usúario deve <em><strong>conter 4 à 10 caracteres</strong></em>")->flash();
            return null;
        }
        if (!preg_match("/^[a-zA-Z0-9]+$/i", $user)) {
            $this->message->class("error")->text("Não use <em><strong>simbolos</strong></em> em seu usúario")->flash();
            return null;
        }

        /** Password */
        if ((strlen($passwd) < 4 or strlen($repasswd) < 4) or (strlen($passwd) > 10 or strlen($repasswd) > 10)) {
            $this->message->class("error")->text("Suas senhas não pode conter <em><strong>entre 4 à 10 caracteres</strong></em>")->flash();
            return null;
        }
        if (!preg_match("/^[a-zA-Z0-9]+$/i", $passwd) or !preg_match("/^[a-zA-Z0-9]+$/i", $repasswd)) {
            $this->message->class("error")->text("Não use <em><strong>simbolos</strong></em> em sua senha")->flash();
            return null;
        }
        if ($passwd != $repasswd) {
            $this->message->class("error")->text("Suas <em><strong>senhas</strong></em> não conferem")->flash();
            return null;
        }

        /** E-mail */
        if (empty($email) or empty($reemail)) {
            $this->message->class("error")->text("Digite um <em><strong>e-mail válido</strong></em>, será usado para você recuperar seus dados quando necessário")->flash();
            return null;
        }
        if ($email != $reemail) {
            $this->message->class("error")->text("Seus <em><strong>e-mails</strong></em> não conferem")->flash();
            return null;
        }

        /** Personal ID */
        if (!is_numeric($pid) or strlen($pid) != 7) {
            $this->message->class("error")->text("Seu <em><strong>Personal ID </strong></em>deve conter 7 números")->flash();
            return null;
        }

        /** Terms */
        if (!$terms) {
            $this->message->class("error")->text("Aceite os nossos <em><strong>termos</strong></em> para continuar")->flash();
            return null;
        }

        /** Verification existent account */
        $verificationaccount = $this->table("MEMB_INFO")->columns("memb___id")->where("memb___id = :mi", "mi={$user}")->get();
        if (!empty($verificationaccount)) {
            $this->message->class("error")->text("Este <em><strong>usúario</strong></em> não está disponível")->flash();
            return null;
        };

        /** Verification existent email */
        $verificationemail = $this->table("MEMB_INFO")->columns("mail_addr")->where("mail_addr = :email", "email={$email}")->get();
        if (!empty($verificationemail)) {
            $this->message->class("error")->text("Este <em><strong>e-mail</strong></em> não está disponível")->flash();
            return null;
        };

        if (requests_form("account_register", 2, 15)) {
            $this->message->class("error")->text("Você criou uma conta recentemente, aguarde <em><strong>15 minutos</strong></em>")->flash();
            return null;
        }

        /** Insert account register */

        $codding = uniqid();

        $dataaccount = array(
            'memb___id' => trim($user),
            'memb__pwd' => trim($passwd),
            'memb_name' => trim(ucfirst($name)),
            'sno__numb' => '111111' . $pid,
            'bloc_code' => 0,
            'ctl1_code' => 1,
            'mail_addr' => $email,
            'appl_days' => '2003-01-01 00:00:00',
            'mail_chek' => config['confirm_email'] ? 0 : 1,
            'id_ref' => uniqid(),
            'email_codding' =>  config['confirm_email'] ? $codding : null
        );

        if (register['curr_info']) {
            $currinfo = array(
                'ends_days' => '2005',
                'chek_code' => 1,
                'memb___id' => trim($user),
                'memb_name' => trim(ucfirst($name)),
                'memb_guid' => '1',
                'sno__numb' => '7',
                'used_time' => '1234',
                'Bill_Section' => '6',
                'Bill_Value' => '3',
                'Bill_Hour' => '6',
                'Surplus_Point' => '6',
                'Surplus_Minute' => '1905-06-26 00:00:00.000',
                'Increase_Days' => '0',
            );
            $this->table("VI_CURR_INFO")->created($currinfo);
        }

        $this->table("MEMB_INFO")->created($dataaccount);

        $messageUpdateVip = "";
        if (register['gift_vip']['active']) {
            $update = array(
                '' . config['column_vip'] . '' => register['gift_vip']['type_vip'],
                'AccountExpireDate' => __updatedate("now", register['gift_vip']['time_vip'])
            );
            $this->table("MEMB_INFO")->where("memb___id = :mi", "mi={$user}")->updated($update);
            $messageUpdateVip = "<br> <em><strong>Você foi premiado com " . register['gift_vip']['time_vip'] . " dias de vip</strong></em>";
        }

        $userRef = $this->table("MEMB_INFO")->columns("memb___id")->where("id_ref = :r", "r={$idRef}")->get();
        if ($userRef) {
            $ref = [
                'user_ref' => $userRef->memb___id,
                'account' => $user,
                'ip' => $_SERVER['REMOTE_ADDR'],
                'created_at' => date("Y-m-d H:i:s", strtotime("now"))
            ];
            $this->table("amw_indication")->created($ref);
        }

        if (config['confirm_email']) {
            $sendMailConfirm = new confirmEmail();
            $sendMailConfirm->sendmail($email);
        }

        $this->message->class("success")->text("Conta criada com sucesso {$messageUpdateVip}")->flash(true, true);
        $this->session->set('token_csrf', md5(uniqid()));
    }
}
