<?php

namespace App\Controllers\Admin;
use App\Models\UserModel;
use App\Models\LicenseModel;
use App\Controllers\BaseController;
class CreateUserController extends BaseController
{
    protected $session;
    public function __construct(){
        helper(['form']);
        $this->session = service('session');
    }
    public function index()
    {

        $userModel = new UserModel();
        $licenseModel = new LicenseModel();

        $data['title'] = 'Edit User';
        $data['msg'] = $this->session->getFlashdata('msg');
        $data['error'] = $this->session->getFlashdata('error');
        $this->smartyView('admin/createuser', $data);
    }

   
   public function is_unique($table,$value)
    {
        $userModel = new UserModel();
        $user = $userModel->where($table, $value)->findAll();
        if(!empty($user[0])){
            return TRUE;
        }else {
            return FALSE;
        }
    }
    public function store()
    {
        helper(['form']);
         $rules = [
            'user'          => 'required|min_length[2]|max_length[50]',
            'email'         => 'required|min_length[4]|max_length[100]|valid_email',
            'password'      => 'required|min_length[4]|max_length[50]',
            'ustatus'      => 'required',
            'ulevel'      => 'required',
            'confirmpassword'  => 'matches[password]'

        ];
        if($this->is_unique('Mail', $this->request->getVar('email'))){
            return redirect()->to('/admin/createuser')->with('msg', 'Email já existe.'); 
        
        }elseif($this->is_unique('Name', $this->request->getVar('user'))){

            return redirect()->to('/admin/createuser')->with('msg', 'Usuário já existe.'); 

        }elseif(!$this->is_unique('Name', $this->request->getVar('user')) && !$this->is_unique('Mail', $this->request->getVar('email'))){
            if($this->validate($rules)){
            $userModel = new UserModel();
            $licenseModel = new LicenseModel();
            $data = [
                'Name'     => $this->request->getVar('user'),
                'Mail'    => $this->request->getVar('email'),
                'Status' => $this->request->getVar('ustatus'),
                'Nivel' => $this->request->getVar('ulevel'),
                'ClientName' => $this->request->getVar('user'),
                'Password' => $this->request->getVar('password')
            ];
            $userModel->save($data);
            unset($data);
            return redirect()->to('/admin/createuser')->with('msg', 'Usuário Registrado! .'); 
        
        }else{
            return redirect()->to('/admin/createuser')->with('error', $this->validator); 
        
        }
        }
          
    }
  
}
