<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\UserModel;

class Auth extends BaseController
{


    private $UserModel;


    public function __construct()
    {
        $this->UserModel = new UserModel();
    }


    public function index()
    {
            
        return view('auth/login');

    }


    public function login()
    {
        $data = json_decode(json_encode($this->request->getPOST()));
        
        $rules = [
            'username' => [
                'rules'     => 'required|min_length[6]',
                'errors'    => [
                    'required'      => 'Username wajib diisi.',
                    'min_length'   => 'Username tidak valid',
                ]
            ],
            'password'  => [
                'rules'     => 'required|min_length[6]',
                'errors'    => [
                    'required'      => 'Password wajib diisi.',
                    'min_length'    => 'Panjang password minimal 6 karakter'
                ]
            ]
        ];

        if (!$this->validate($rules)) {
            $message = $this->validator->getErrors();
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => $message]);
        }

        $this->UserModel->select('tbl_user.*, tbl_role.name AS role_name');
        $this->UserModel->join('tbl_role','tbl_role.id=tbl_user.role_id');
        $this->UserModel->where('username',$data->username);
        $user = $this->UserModel->first();
        
        if ($user) {
            if((int) $user->is_active<=0){
                return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => "Akun anda tidak aktif. silahkan hubungi admin"]);
            }else{
                if (password_verify($data->password, $user->password)) {

                    $userData = [
                        'id'                => $user->id,
                        'name'              => $user->name,
                        'role_id'           => $user->role_id,
                        'role_name'           => $user->role_name,
                    ];
                    
                    session()->set($userData);
                    $userData  = [];
                    $twuuidow = $this->_generate_uuid();
                    $userData['cookies_uuid'] = $twuuidow;

                    $cookieOptions = [
                        'name'   => 'rtuuidinds',
                        'value'  => $twuuidow,
                        'expire' => 2592000, 
                        'path'   => '/',
                        'secure' => false,
                        'httponly' => true,
                    ];

                    $this->response->setCookie($cookieOptions);

                    $cookieOptions['_rtuuidinds'] = [
                        'name'   => '_rtuuidinds',
                        'value'  => $user->id,
                        'expire' => 2592000,
                        'path'   => '/',
                        'secure' => false,
                        'httponly' => true,
                    ];

                    $this->response->setCookie($cookieOptions['_rtuuidinds']);


                    $this->UserModel->set('cookies_uuid',$userData['cookies_uuid']);
                    $this->UserModel->where('id',$user->id);
                    if(!$this->UserModel->update()){
                        return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => "Login gagal. pastikan anda terkoneksi dengan internet"]);
                    }
                     
                    insertLog("Auth","Login","User $user->name berhasil login dan masuk ke aplikasi ",$user->id);                       
                    return $this->response->setJSON(['code' => 200, 'success' => true, 'message' => "Login berhasil"]);
                }else{
                    
                    return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => "Password yang anda masukan salah"]);
                }
            }
        } else {
            return $this->response->setJSON(['code' => 200, 'success' => false, 'message' => "Username tersebut tidak terdaftar"]);
        }

    }



    private function _generate_uuid()
    {
        return sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0C2f) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0x2Aff),
            mt_rand(0, 0xffD3),
            mt_rand(0, 0xff4B)
        );
    }

    public function logout()
    {
        $id = session()->get('id');
        $name = session()->get('name');
        insertLog("Auth","Logout","User $name telah logout dari aplikasi  ",$id);
        
        session()->destroy();
        setcookie('rtuuidinds', "", [
            'expires' => -1,
            'path' => '/',
            'domain' => '',      
            'secure' => false,    
            'httponly' => true,
            'samesite' => 'Lax',  
        ]);

        setcookie('_rtuuidinds', "", [
            'expires' => -1,
            'path' => '/',
            'domain' => '',
            'secure' => false,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);

        return redirect()->to(base_url().'auth');

    }



}
