<?php

namespace App\Controllers;
use App\Models\UserModel;


class CredentialController extends BaseController
{
  // Password hasing password_hash($password, PASSWORD_BCRYPT, 14);
    
   
    public function Login()
    {  
        $header['title']='Login';
        echo view('Login.php',$header);
 
    }

      public function Logout()
    {  
        $session = session();
        $session->destroy();
        return redirect()->to('/login');
 
    }

    public function auth()
    {
        $session = session();
        $model = new UserModel();
        $username = $this->request->getVar('username');
        $password = $this->request->getVar('password');
        $data = $model->where('USER_NAME', $username)->first();
        if($data){
            $pass = $data['USER_PWD'];
            $verify_pass = password_verify($password, $pass);
            if($verify_pass){
                $ses_data = [
                    'USER_ID '       => $data['USER_ID'],
                    'USER_NAME'     => $data['USER_NAME'],
                    'USER_LEVEL'     => $data['USER_LEVEL'],                 
                    'logged_in'     => TRUE
                ];
                $session->set($ses_data);
                return redirect()->to('/');
            }else{
                $session->setFlashdata('msg', 'Wrong Password');
                return redirect()->to('/login');
            }
        }else{
            $session->setFlashdata('msg', 'Username not found');
            return redirect()->to('/login');
        }
    }

    public function Masteruser()
    {
        $header['title']='Master user';
        echo view('Master/User.php',$header);
    
        
    }

    public function User_profile()
    {
        helper(['form']);
        $session = session();
        $header['USER_NAME'] = $session->USER_NAME;
        $header['title']='Profile user';
        echo view('Profile.php',$header);
    
        
    }


    public function Update_profile()
    {
        $session = session();
        helper(['form']);
        $datenow = date("Y-m-d H:i:s");
        $uploadfile = 0;
        $isreset = 0;
        $e_resetpass = $this->request->getVar('e_resetpass');

       if($e_resetpass  != null && !empty($_FILES['x_photo']['name']))
       { // jika  ganti foto dan reset pass

        $rules = [ 
            'newpass'      => 'required|min_length[6]|max_length[200]',
            'repass'  => 'matches[newpass]',
            'x_photo' => [
				'rules' => 'uploaded[x_photo]|mime_in[x_photo,image/jpg,image/jpeg,image/gif,image/png]|max_size[x_photo,1024]',
				'errors' => [					
					'mime_in' => 'File Extention Harus Berupa jpg,jpeg,gif,png',
					'max_size' => 'Ukuran File Maksimal 1 MB'
				]
 
			]
             ];
             $uploadfile = 1;
             $isreset = 1;

       } else if ($e_resetpass  == null && !empty($_FILES['x_photo']['name']))
       { // jika hanya ganti foto
           $rules = [ 
           
            'x_photo' => [
				'rules' => 'uploaded[x_photo]|mime_in[x_photo,image/jpg,image/jpeg,image/gif,image/png]|max_size[x_photo,1024]',
				'errors' => [					
					'mime_in' => 'File Extention Harus Berupa jpg,jpeg,gif,png',
					'max_size' => 'Ukuran File Maksimal 1 MB'
				]
 
			]
             ];
            $uploadfile = 1; 

       } else if ($e_resetpass  != null && empty($_FILES['x_photo']['name']))
       { // jika hanya ganti password
         $rules = [ 
            'newpass'      => 'required|min_length[6]|max_length[200]',
            'repass'  => 'matches[newpass]'
           
             ];
            $isreset = 1;
       }

       
        if($this->validate($rules)){
                $UserModel = new UserModel();
                $username = $session->USER_NAME;
                $data = $UserModel->where('USER_NAME', $username)->first();
                

                if($data){
                    $id = $data['USER_ID'];

                    if($uploadfile == 1 && $isreset == 0)
                    { // jika  hanya foto 

                            $dataBerkas = $this->request->getFile('x_photo');
                            $fileName = $dataBerkas->getRandomName();
                            $dataBerkas->move('public/files/', $fileName);
                            $verify_pass = true;
                            $data = [
                                
                                                     
                                'UPDBY' => $username,          
                                'UPDDTM' => $datenow,
                                'FILE_FOTO' => $fileName

                            ];

                    } else if ($uploadfile == 0 && $isreset == 1)
                    { 
                        // jika hanya reset password
                        $oldpassword = $this->request->getVar('oldpass');
                        $pass = $data['USER_PWD'];                    
                        $verify_pass = password_verify($oldpassword, $pass);
                        $newpass = $this->request->getVar('newpass');
                        $xpassword = password_hash($newpass, PASSWORD_DEFAULT);
                        $data = [
                                    
                                    'USER_PWD' => $xpassword,                        
                                    'UPDBY' => $username,          
                                    'UPDDTM' => $datenow

                                ];
                       
       

                    }else if($uploadfile == 1 && $isreset == 1)
                    {
                        // jika ganti password dan ganti foto
                            $oldpassword = $this->request->getVar('oldpass');
                            $pass = $data['USER_PWD'];                    
                            $verify_pass = password_verify($oldpassword, $pass);
                            $dataBerkas = $this->request->getFile('x_photo');
                            $fileName = $dataBerkas->getRandomName();
                            $dataBerkas->move('public/files/', $fileName);
                            $newpass = $this->request->getVar('newpass');
                            $xpassword = password_hash($newpass, PASSWORD_DEFAULT);
                            $data = [
                                
                                'USER_PWD' => $xpassword,                        
                                'UPDBY' => $username,          
                                'UPDDTM' => $datenow,
                                'FILE_FOTO' => $fileName

                            ];
                            


                    }
                  
               
                    if($verify_pass){
    
                       $UserModel->update($id,$data);
                       $session->setFlashdata('msg', 'Password has been changed, please login');
                        
                        return redirect()->to('login');
                    }else{
                        $session->setFlashdata('msg', 'Wrong old password');
                        return redirect()->to('user/profile');
                    }
                }else{
                    $session->setFlashdata('msg', 'Session timeout');
                    return redirect()->to('/Login');
                }
                $session->setFlashdata('msg', 'Password mismatch');
                    return redirect()->to('user/profile');
        }else{
            $header['USER_NAME'] = $session->USER_NAME;
            $header['title']='Profile user';
            $header['validation'] = $this->validator;
             echo view('Profile.php',$header);
        }
        
    }



    public function Simpan()
    {
        
        $datenow = date("Y-m-d H:i:s");
        $pass = $this->request->getPost('password');
        $xpassword = password_hash($pass, PASSWORD_DEFAULT);
        $UserParam = new UserModel;
        $data = [
            'USER_NAME' => $this->request->getPost('username'),
            'USER_PWD' => $xpassword,
            'USER_LEVEL' => $this->request->getPost('level'),
            'IS_ACTIVE' => $this->request->getPost('active'),
            'CRTBY' => "Admin",
            'UPDBY' => "Admin",
            'CRTDTM' => $datenow,
            'UPDDTM' => $datenow

        ];
        $UserParam->save($data);
        $data = ['status' => 'data berhasil disimpan'];
        return $this->response->setJson($data);    
        
    }

    public function delete()
    {
        $id = $this->request->getPost('user_id');
        $datenow = date("Y-m-d H:i:s");
        $UserParam = new UserModel;
        $data = [
            'IS_DELETE' => 1,
            'CRTBY' => "Admin",
            'UPDBY' => "Admin",
            'IS_ACTIVE' => 0,
            'CRTDTM' => $datenow,
            'UPDDTM' => $datenow

        ];
        $UserParam->update($id,$data);
        $data = ['status' => 'data berhasil dihapus'];
        return $this->response->setJson($data);       
        
    }

     public function Update_data()
    {
       
        $datenow = date("Y-m-d H:i:s");
        $pass = $this->request->getPost('password');
        $id = $this->request->getPost('user_id');
        if($pass != "")
        {
            $xpassword = password_hash($pass, PASSWORD_DEFAULT);
            $data = [
            
            'USER_PWD' => $xpassword,
            'USER_LEVEL' => $this->request->getPost('level'),
            'IS_ACTIVE' => $this->request->getPost('active'),
            'UPDBY' => "Admin",          
            'UPDDTM' => $datenow

        ];
       
        }
        else
        {
        $data = [
            
            
            'USER_LEVEL' => $this->request->getPost('level'),
            'IS_ACTIVE' => $this->request->getPost('active'),
            'UPDBY' => "Admin",          
            'UPDDTM' => $datenow

        ];
        }
       
        $UserParam = new UserModel;
        $UserParam->update($id,$data);
        $data = ['status' => 'data berhasil diupdate'];
        return $this->response->setJson($data);    
        
    }

    public function fetch()
    {
             $User = new UserModel();
             $data['data'] = $User->where('IS_DELETE',0)->findAll();
             return $this->response->setJson($data); 

    }


    public function Wherecon()
    {
             $User = new UserModel();
             $where= $this->request->getPost('KONDISI');
           
             $data['data'] = $User->where($where)->where('IS_ACTIVE',1)->where('IS_DELETE',0)->orderby('USER_NAME','ASC')->findAll();
             return $this->response->setJson($data); 

    }

    public function get_detail()
    {
             $User = new UserModel();
             $id= $this->request->getPost('id');
             $data['data'] = $User->find($id);
             return $this->response->setJson($data); 

    }
   
   
}
