<?php

namespace Modules\Admin\Controllers;

use App\Controllers\Auth\AuthController;


class AdminUsers extends AuthController
{
    public function initController($request, $response, $logger)
    {
        parent::initController($request, $response, $logger);
    }

    public function index()
    {
        $this->data['title'] = "User List";
        $this->data['bcrumb'] = 'All Users';

        $this->data['groups'] = $this->usergroupsModel->getUserGroups();
        $this->data['users'] = $this->usersModel->getAllUsers();

        return view('Modules\Admin\Views\users\users', $this->data);
    }

    public function addUser()
    {
        $this->data['title'] = 'Add User';
        $this->data['bcrumb'] = 'Add User';
        
        $this->data['countries']    = $this->countryModel->getAll();
        $this->data['groups']       = $this->usergroupsModel->getAll();

        if($this->request->getMethod() == 'POST')
        {
            $hash = bin2hex(random_bytes(24));
            $validation = \Config\Services::validation();

            //Rules Set
            $rules = [
                'first_name'    => ["label"=>"First Name", "rules"=>"required"],
                'last_name'     => ["label"=>"Other Name", "rules"=>"required"],
                'email'         => ['label' => 'Email', 'rules' => 'required|min_length[5]|max_length[100]|valid_email|is_unique[users.email]'],
                'password'		 	 	 => ['label' => 'Password', 'rules' => 'required|min_length[8]|max_length[20]|alpha_numeric_punct'],
		        'cpass'				 	 => ['label' => 'Confirm Password', 'rules' => 'required|matches[password]'],
            ];
                
            if ($this->validate($rules))
            {
                $regData = [
                    'first_name' 			=> $this->request->getVar('first_name'),
                    'last_name' 			=> $this->request->getVar('last_name'),
                    'email' 				=> $this->request->getVar('email'),
                    'status'                => 'active',
                    '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'),
                    'description'		    => $this->request->getVar('description'),
                ];
                $results = $this->usersModel->save($regData);
                if($results)
                {
                    $users = $this->usersModel->getAdminUsers();
                    $firstName = $this->request->getVar('first_name');
                    $lastName = $this->request->getVar('last_name');
                    $productName = $this->request->getVar('name');
                    $id = $this->usersModel->getInsertID();

                    //Save user in Auth Group
                    $groupData = [
                        'user_id' => $id,
                        'group_id'=> '5',
                    ];
                    $this->userauthgroupModel->save($groupData);


                    //Notification
                    $adminmessage = 'New User: '.$firstName.' '.$lastName.' account has been <strong>CREATED</strong>';
                    $notificationType = 'security';
                    $this->sendAdminNotifications($adminmessage, $notificationType, $id);

                    if($this->request->isAJAX()){
                        $response = [
                            'success' => true,
                            'msg'     => 'User created successfully',
                        ];
                        return $this->response->setJSON($response);

                    }else{
                        session()->setFlashdata('success', 'User successfully', 3);
                        return redirect()->to('administrator/users');
                    }
                }else
                {
                    if($this->request->isAJAX()){
                        $response = [
                            'error'     => true,
                            'msg'     => 'Sorry! Account not created',
                        ];
                        return $this->response->setJSON($response);

                    }else{
                    session()->setTempdata('error', 'Sorry! Account not created', 3);
                    return redirect()->to('administrator/users/add');
                    }
                }
            }else{
                $this->data['validation'] = $this->validator;
            }
        }
        return View('Modules\Admin\Views\users\add_user', $this->data);
    }

    public function editUser($id)
    {
        $user = $this->usersModel->where('id', $id)->first($id);
        $this->data['title'] = 'Edit '.$user['first_name'].' '.$user['last_name'];
        $this->data['bcrumb'] = $user['first_name'].' '.$user['last_name'] .' Details';

        $this->data['singleUser'] = $this->usersModel->singleUser($id);

        return View('Modules\Admin\Views\users\edit_user', $this->data);
    }

    public function updateUser()
    {
        $this->data['title'] = 'Update User';
        $this->data['bcrumb'] = 'Update User';
        
        $this->data['countries'] = $this->countryModel->getAll();
        $this->data['groups'] = $this->usergroupsModel->getAll();
        $id = $this->request->getVar('id');
        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();

            //Rules set
            $rules = [
                'first_name'    => ["label"=>"First Name", "rules"=>"required"],
                'last_name'     => ["label"=>"Other Name", "rules"=>"required"],
            ];
                
            if ($this->validate($rules))
            {
                $regData = [
                    'first_name' 			=> $this->request->getVar('first_name'),
                    'last_name' 			=> $this->request->getVar('last_name'),
                    'email' 				=> $this->request->getVar('email'),
                    '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'),
                    'description'		    => $this->request->getVar('description'),
                ];
                $results = $this->usersModel->update($id, $regData);
                if($results)
                {
                    $users = $this->usersModel->getAdminUsers();
                    $firstName = $this->request->getVar('first_name');
                    $lastName = $this->request->getVar('last_name');
                    $userName = $firstName.' '.$lastName;
                    $adminmessage = 'User '.$userName.' account details updated successfully';
                    $notificationType = 'security';
                    $this->sendAdminNotifications($adminmessage, $notificationType, $id);

                    session()->setFlashdata('success', 'User updated successfully', 3);
                    return redirect()->to('administrator/users');
                    
                }else
                {
                    if($this->request->isAJAX()){
                        $response = [
                            'error'     => true,
                            'msg'     => 'Sorry! Account not created',
                        ];
                        return $this->response->setJSON($response);

                    }else{
                    session()->setTempdata('error', 'Sorry! Account not created', 3);
                    return redirect()->to('administrator/users/edit/'.$id);
                    }
                }
            }else{
                $this->data['validation'] = $this->validator;
            }
        }
        return View('Modules\Admin\Views\edit_user', $this->data);
    }

    public function deleteUser($id)
    {
        $admins = $this->usersModel->getAdminUsers();
        $user = $this->usersModel->singleUser($id);
         
        $this->usersModel->where('id', $id)->delete($id);
        if($this->request->isAJAX())
        {
            $response = [
            'error' => true,
            'msg' =>'User deleted successfully',	   
            ];
            return $this->response->setJSON($response);
        }else{
            //Save & Send Notification
            $adminmessage = $user->first_name .' '.$user->last_name.'\'s account has been <strong>DELETED</strong>';
            $notificationType = 'security';
            $this->sendAdminNotifications($adminmessage, $notificationType, $id);

            session()->setFlashdata('error', 'User deleted successfully', 3);
            return redirect()->to('administrator/users');
        }
    }

     //Update user password
    public function changePwd()
    {
        if($this->request->getMethod() == 'POST')
        {
            $rules = [
                'password'	=> ['label' => 'Password', 'rules' => 'required|min_length[8]|max_length[20]|alpha_numeric_punct'],
		        'cpass'	    => ['label' => 'Confirm Password', 'rules' => 'required|matches[password]'],
            ];

            if(!$this->validate($rules)){
                $validation = \Config\Services::validation();
                $errors = $validation->getErrors();
                
                $errorMessage = implode('<br>', $errors);
                session()->setFlashdata('error', $errorMessage, 5);
                return redirect()->to('administrator/users');
            }
                

            $id = $this->request->getVar('id');
            $u = $this->usersModel->where('id', $id)->first($id);
            $password = password_hash($this->request->getVar('password'), PASSWORD_DEFAULT);
            $newPwd = [
                'password' => $password,
            ];
            if($this->usersModel->update($id, $newPwd))
            {
                $adminmessage = 'User '.$u['first_name'].' '.$u['last_name'].' password updated by Admin';
                $notificationType = 'security';
                $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

                session()->setFlashdata('success', 'User password updated successfully', 3);
                return redirect()->to('administrator/users');
            }

        }
    }

    //Change User Group
    public function changeGroup()
    {
        $userId = $this->request->getVar('id');
        $u = $this->usersModel->singleUser($userId);
        //var_dump($u);
        if($this->request->getMethod() == 'POST')
        {
            $grpData = [
                'group_id' => $this->request->getVar('group_id'),
            ];
            $results = $this->userauthgroupModel->update($userId, $grpData);

            if($results)
            {
                //Notification save
                $adminmessage = 'User - '.$u->first_name.' '.$u->last_name.' GROUP updated';
                $notificationType = 'security';
                $this->sendAdminNotifications($adminmessage, $notificationType, $this->userdata->user_id);

                session()->setFlashdata('success', 'User Group updated successfully', 3);
                return redirect()->to('administrator/users');
            }
        }
    }



}