<?php

namespace App\Controllers\Auth;

use CodeIgniter\Controller;
use Config\Services;
use App\Controllers\BaseController;
use App\Models\CountryModel;
use App\Models\StateModel;
use App\Models\CityModel;
use App\Models\RegisterModel;
use App\Models\UserAuthGroupModel;
use App\Models\AuthLoginModel;
use App\Models\UserAuthTokenModel;
use App\Models\UserGroupsModel;
use App\Models\UserActivateTokensModel;
use App\Models\UserActivationAttemptsModel;
use App\Models\UserResetsAttemptsModel;
//use App\Models\CountryStateCityModel;

class Register extends BaseController
{
    public $registerModel;
    public $userauthgroupModel;
    public $usergroupsModel;
    public $authloginModel;
    public $userauthtokenModel;
    public $useractivatetokensModel;
    public $useractivationattemptsModel;
    public $userresetsattemptsModel;
    public $subscriptionModel;
    public $subscriptionplansModel;

    public function __construct(){

		$this->countryModel 				= new CountryModel();
		$this->stateModel					= new StateModel();
		$this->cityModel					= new CityModel();
        $this->registerModel                = new RegisterModel();
        $this->userauthgroupModel           = new UserAuthGroupModel();
        $this->usergroupsModel              = new UserGroupsModel();
        $this->authloginModel               = new AuthLoginModel();
        $this->userauthtokenModel           = new UserAuthTokenModel();
        $this->useractivatetokensModel      = new UserActivateTokensModel();
        $this->useractivationattemptsModel  = new UserActivationAttemptsModel();
        $this->userresetsattemptsModel      = new UserResetsAttemptsModel();;
        
    }

    public function index()
    { 
		$this->data['Allcountries'] = $this->countryModel->getAll();
        return view('auth/register', $this->data);
    }

    public function createAccount()
    {
		$data['Allcountries'] = $this->countryModel->getAll();

        
        if($this->request->getMethod() == 'POST')
        {
            $expiryTime = date('Y-m-d H:i:s', strtotime('+240 minutes'));
            $hash = bin2hex(random_bytes(24));
            $validation = \Config\Services::validation();
            $email = \Config\Services::email();

            if (! $this->request->is('POST')) {
                return $this->response->setStatusCode(405)->setBody('Method Not Allowed');
            }
            
            //Rules set
            $rules = $validation->getRuleGroup('userRegister');
            
            if (! $this->validate($rules)){
                $data['validation'] = $validation;
            }else
            {
                $regData = [
                    'first_name' 			=> $this->request->getVar('first_name'),
					'last_name' 			=> $this->request->getVar('last_name'),
					'email' 				=> $this->request->getVar('email'),
					'password'				=> password_hash($this->request->getVar('password'), PASSWORD_DEFAULT),
					'mobile'				=> $this->request->getVar('mobile'),
					'address'				=> $this->request->getVar('address'),
					'country_id'			=> $this->request->getVar('country_id'),
					'state_id'				=> $this->request->getVar('state_id'),
					'city_id'				=> $this->request->getVar('city_id'),
                ];
                $results = $this->registerModel->save($regData);
                //var_dump($regData);
                if($results)
                {
                    //USer ID 
                    $uid = $this->registerModel->getInsertID();
					
					//Save Activate Token
                    $activateData = [
                            'hashed_token'  => $hash,
                            'user_id'       => $uid,
                            'ip_address'    => $_SERVER['REMOTE_ADDR'],
                            'expires'       => $expiryTime,
                    ];

                    if($this->useractivatetokensModel->save($activateData))
                    {
                                //Send email to New User for Activation.
                            $filepath = 'assets/images/logo-mobile.png';
                            $to = $this->request->getVar('email');
                            $subject = 'Account Activation Link - YIM';						
                            $message = '<body style="background: #EFFAF0; padding: 2em 1em;"><div style="width: 500px; background: #fff; border-radius:5px; padding: 15px; margin: 0 auto;">
                                <p><center><img src="'.base_url().'/'.$filepath.'" style="height: 80px"/></center></p>
                                <center><h3 style="font-weight: bold;"><strong> Activate Your Account Now.</h3></center>
                                <p></p>
                                <p>Dear '.$this->request->getVar('first_name').'</strong>, </p>
                                
                                <p>Welcome to Your ICT Magazine! We are thrilled to have you on board. To get started, we kindly request you to verify your email address  <strong>'.$this->request->getVar('email').'</strong> and activate your account by clicking on the link below:</p>

                                <p style="word-wrap: break-word; padding: 15px;">Activate Account:<br>  <a style="color:#3CB44A; text-align: center" href="'.base_url()."/register/activate/".$hash.'">'.base_url()."/register/activate/".$hash.'</a></p>
                                <p></p>
								

                                <p>If you have any questions or require assistance during the activation process, please do not hesitate to reach out to our dedicated support team. We are here to ensure a seamless onboarding experience for you.</p>

                                <p>Thank you for choosing AgriMarket</p>

                                <p>&nbsp;</p>
                                <p>Warm regards, <br> The YIM team <br>
                                 www.yourictmagazine.com <br> 
                                </p></div></body>';
                            $email->setFrom('no-reply@yourictmagazine.com', 'Your ICT Magazine');
                            $email->setTo($to);
                            $email->setSubject($subject);
                            $email->setMessage($message);
                            $email->setMailType('html');
                            
                            if($email->send())
                            {
                                session()->setTempdata('success', 'Account created, Check email to activate your account', 3);
                                return redirect()->to('thank-you');
                            }else
                            {
                                session()->setTempdata('error', 'Account created, Sorry unable to send you activation link. Contact Admin', 3);
                                return redirect()->to('register');
                            }
                    }

                }else
                {
                    session()->setTempdata('error', 'Sorry! Account not created', 3);
					return redirect()->to('register');
                }
            }
            
            
        }
        return view('auth/register', $data);
    }

    //A Thank you page for newly created user account before activation
    public function thankYou()
    {
        return view('auth/thank_you', $this->data);
    }

    //User Verification & Activation
    public function accountActivate($code = null)
    {
        //setting unique session id
        $this->data['sessionid'] = $this->GUID();

        $checkToken = $this->useractivatetokensModel->verifyToken($code);
        $userInfo = $this->registerModel->getUserId($checkToken->user_id);
        if($code != null)
        {
            if(!empty($checkToken))
            {
                //Check for token Expiry
                $expired = (time() > strtotime($checkToken->expires));
                if(!$expired)
                {
                    if($userInfo->status == 'inactive')
                    {
                        $status = $this->registerModel->updateStatus($checkToken->user_id);
                        if($status)
                        {
                            //Add user to USER Group
                            $groupData = [
                                'user_id' => $checkToken->user_id,
                                'group_id' => 6,
                            ];
                            if($this->userauthgroupModel->save($groupData))
                            {
                                //Record user Activation Attempts
                                $resetData = [
                                    'token'      => $checkToken->hashed_token,
                                    'ip'         => $_SERVER['REMOTE_ADDR'],
                                    'user_agent' => $_SERVER['HTTP_USER_AGENT'],
                                ];
                                if($this->useractivationattemptsModel->save($resetData))
                                {
                                    //Set a session for User login
                                    session()->set('logged_user', $checkToken->hashed_token);
                                    session()->set('loggedIn', true);
                                    $sesndata = [
                                        'ip'            => $_SERVER['REMOTE_ADDR'],
                                        'user_agent'    => $_SERVER['HTTP_USER_AGENT'],
                                        'id_type'       => $checkToken->hashed_token,
                                        'identifier'    => $userInfo->email,
                                        'user_id'       => $checkToken->user_id,
                                    ];
                                    if($this->authloginModel->save($sesndata))
                                    {
                                    session()->setTempdata('success', "Congratulations <strong>$userInfo->first_name</strong>!, Your account is activated successfully. Setup your <strong>Account</strong>", 3);
                                    return redirect()->to('shop'); 
                                    } 
                                }else
                                {
                                    session()->setTempdata('error', "Sorry!, Something is not right. Contact Support", 3);
                                    return redirect()->to('/');
                                }
                            }
                        }
                    }else
                    {
                            //Set a session for User login
                            session()->set('logged_user', $this->data['sessionid']);
                            session()->set('loggedIn', true);
                            $sesndata = [
                                'ip' => $_SERVER['REMOTE_ADDR'],
                                'user_agent' => $_SERVER['HTTP_USER_AGENT'],
                                'id_type'   => $this->data['sessionid'],
                                'identifier' => $userInfo->email,
                                'user_id' => $checkToken->user_id,
                            ];
                            if($this->authloginModel->save($sesndata))
                            {
                                session()->setTempdata('success', "Welcome back, $userInfo->first_name!", 3);
                                return redirect()->to('shop'); 
                            }
                    }
                }else
                {
                    session()->setTempdata('error', 'Sorry! Account activation Token Expired. Enter <strong>Email</strong> to receive a new one.', 3);
                    return view('auth/new_activationlink', $this->data);
                }
            }else
            {
                session()->setTempdata('error', "Sorry! Account activation Token does not exist", 3);
			    return redirect()->to('register');
            }
        }else
        {
            session()->setTempdata('error', 'Sorry! Unauthorized Access', 3);
            return redirect()->to('register');
        }
        return view('auth/login', $this->data);
    }

    //Resend Activation Token
    public function reActivationLink()
    {
        $hash = bin2hex(random_bytes(20));
        $validation =  \Config\Services::validation();
        $email = \Config\Services::email();
        $expiryTime = date('Y-m-d H:i:s', strtotime('+240 minutes'));

        if($this->request->getMethod() == 'POST')
        {
            $rules = ['email' => ['label'=>'Email', 'rules'=>'required|valid_email']];
            if(!$this->validate($rules))
            {
                return view('auth/forgot', ['validation' => $this->validator]);
            }else
            {
                $getEmail = $this->registerModel->verifyEmail($this->request->getVar('email'));
                //Check if Email is already registered
                if($getEmail)
                {
                        //Save Activate Token
                        $activateData = [
                            'hashed_token'  => $hash,
                            'user_id'       => $getEmail->id,
                            'ip_address'    => $_SERVER['REMOTE_ADDR'],
                            'expires'       => $expiryTime,
                        ];
                        if($this->useractivatetokensModel->save($activateData))
                        {
                            //send email to user
                            $filepath = '/assets/images/logo-mobile.png';
                            $to = $this->request->getVar('email');
                            $subject = 'Resend Activation Token - YIM';
                            $message = '<body style="background: #EFFAF0;  padding: 2em 1em;"><div style="width: 500px; background: #fff; border-radius:5px; padding: 15px; margin: 0 auto;">
                            <p>Hello '.$getEmail->first_name.'</p>
                            <p>Seems you missed your first attempt to <strong>activate</strong> your <strong>Yourictmagazine.com</i></strong> account associated with <strong> '.$getEmail->email.'</strong><p>
                        
                            <p>Click on the link  or  copy this URL below to receive a new activation token </p>
                            <p style="word-wrap: break-word; padding: 15px;"><a style="color:#BA2c2c; text-align: center" href="'.base_url()."/register/activate/".$hash.'">'.base_url()."/register/activate/".$hash.'</a></p>
                            <p></p>
                            <p style="font-weight: bold; font-style: italic;"> If you did not request a new token, and your account is active, please ignore this email.</p>

                            <p>&nbsp;</p>

                            
                            <p>Yours, <br> Your ICT Magazine team <br> <img src="'.base_url().$filepath.'" />
                            </p></div></body>';
                            
                            $email->setFrom('no-reply@yourictmagazine.com', 'Your ICT Magazine');
                            $email->setTo($to);
                            $email->setSubject($subject);
                            $email->setMessage($message);
                            $email->setMailType('html');
                            
                            if($email->send())
                            {
                                session()->setTempdata('success', 'Check <strong>Email</strong> for activation link', 3);
                                return redirect()->to('resend/token');
                            }else{
                                session()->setTempdata('error', 'Sorry! Activation token not sent. Try Again or Contact Support', 3);
                                return redirect()->to('resend/token');
                            }
                        }else{
                            session()->setTempdata('error', 'Sorry! seems reset token not set. Try again');
                        }
                }else
                {
                    session()->setTempdata('error', 'Sorry! The email doest not exist', 3);
                    return redirect()->to('resend/token');
                }
                
            }
        }
        return view('auth/new_activationlink', $this->data);
    }

}