<?php

namespace App\Controllers\Admin;
use App\Models\UserModel;
use App\Models\LicenseModel;
use App\Controllers\BaseController;
class EditUserController extends BaseController
{
    protected $session;
    public function __construct(){
        helper(['form']);
        $this->session = service('session');
    }
    public function index($seg1 = false)
    {
    	
        if(!$this->user_exist($seg1)){
            return redirect()->to('/admin/users');
        }
        $userModel = new UserModel();
        $licenseModel = new LicenseModel();
    	$user = $userModel->where('Id', $seg1)->findAll();

        $data['title'] = 'Edit User';
    	$data['user']= (object)$user[0];
        $data['msg'] = $this->session->getFlashdata('msg');
        $data['error'] = $this->session->getFlashdata('error');
        $this->smartyView('admin/edituser', $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 user_exist($value)
    {
        $userModel = new UserModel();
        $user = $userModel->where('Id', $value)->findAll();
        if(!empty($user[0])){
            return TRUE;
        }else {
            return FALSE;
        }
    }
    public function DeleteUser($seg1 = false)
	{
        if(!$this->user_exist($seg1)){
            return redirect()->to('/admin/users');
        }
		
		$userModel = new UserModel();
		$user = $userModel->where('Id', $seg1)->findAll();
		$userModel->where('Id', $seg1)->delete();
		if($userModel){
			 return redirect()->to('/admin/users')->with('msg', "Usuário Removido");
		}

	}
    public function update($seg1 = false)
    {
         $userModel = new UserModel();
         $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]',
            'nivel' => 'required|min_length[1]',
            'status' => 'required|min_length[1]'
        ];
        $user = $userModel->where('Id', $seg1)->findAll();

        if($this->validate($rules)){
            
            $data = [
                'Name'     => $this->request->getVar('user'),
                'Mail'    => $this->request->getVar('email'),                
                'Password' => $this->request->getVar('password'),
                'Nivel' => $this->request->getVar('nivel'),
                'Status' => $this->request->getVar('status') 
            ];
            $userModel->update($seg1, $data);
            return redirect()->to('/admin/user/edit/'.$seg1)->with('msg', "Usuário Atualizado");
        }else{
            return redirect()->to('/admin/user/edit/'.$seg1)->with('error', $this->validator); 
        }
        
          
    }
  
}
