<?php

namespace App\Controllers\Mobile\Auth;

use App\Controllers\Mobile\BC;
use App\Entities\Mobile\User as UserMobileEntity;
use App\Models\Mobile\UserModel as SiswaModel;
use App\Models\Panel\User\StaffModel;
use CodeIgniter\API\ResponseTrait;
use Firebase\JWT\JWT;

class Login extends BC
{
    use ResponseTrait;
    private $nomor_induk;
    private $password;
    private $siswaModel;
    private $staffModel;
    private $user;
    private $sessout;
    private $sessunit;
    private $cookieName;
    private $jwt;
    private $JWTKey;
    private $cr = 'Username atau Password Salah';
    public function index()
    {
        if (logged_in()) return redirect()->to(base_url());
        return view('Mobile/Auth/login', ['no_sidebar' => true, 'no_header' => true, 'no_footer' => true]);
    }
    public function check()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $this->siswaModel = new SiswaModel();
        $this->nomor_induk = $this->request->getVar('nomor_induk');
        $this->password = $this->request->getVar('password');
        $this->user = $this->siswaModel->db->table('m_siswa ms')->select('ms.*,mk.is_alumni')->join('m_kelas mk', 'mk.id=ms.kelas_id', 'left')->where('ms.nomor_induk', $this->nomor_induk)->get()->getRow();
        if ($this->user) return $this->checkSiswa();
        $this->staffModel = new StaffModel();
        $this->user = $this->staffModel->findUsername($this->nomor_induk);
        if ($this->user) return $this->checkStaff();
        return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'Akun Tidak Ditemukan' : $this->cr], 404);
    }

    private function checkSiswa()
    {
        if ($this->user->status != 1)  return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'Akun Tidak Aktif' : $this->cr], 403);
        if ((new UserMobileEntity())->descryptPassword($this->user->password_hash) != $this->password) return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'NIM atau Password Salah' : $this->cr], 404);
        if ($this->user->is_alumni == '1')  return $this->fail(['csrf' => csrf_hash(), 'message' => 'Akun Tidak Aktif'], 403);
        $this->sessout = options('mobile_session_timeout');
        $this->sessunit = options('mobile_session_unit');
        $this->cookieName = options('MOBILECN');
        $this->JWTKey = options('MOBILEJWTKEY');
        $this->generateJWT();
        setLog("Masuk akun", ['user_id' => $this->user->id, 'user_type' => 2, 'fullname' => $this->user->nama]);
        return $this->respond(['message' => 'Berhasil Masuk', 'redirect_url' => base_url()]);
    }

    private function checkStaff()
    {
        if ($this->user->status != 1) return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'Akun Tidak Aktif' : $this->cr], 403);
        if (!$this->user->passwordVerify($this->password)) return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'Username atau Password Salah' : $this->cr], 404);
        if ($this->user->hasRole('admin'))  return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'Akun Tidak Diizinkan' : $this->cr], 403);
        $this->cookieName = options('PANELCN');
        $this->sessout = options('panel_session_timeout');
        $this->sessunit = options('panel_session_unit');
        $this->JWTKey = options('PANELJWTKEY');
        $this->generateJWT();
        $GLOBALS['panel_user'] = $this->user;
        setLog("Masuk akun", ['fullname' => $this->user->fullname, 'user_type' => 1, 'user_id' => $this->user->id]);
        try {
            $du = dashboard_url();
        } catch (\Throwable $th) {
            $du = base_url('pnl');
        }
        return $this->respond(['message' => 'Berhasil Masuk', 'redirect_url' => $du]);
    }

    private function generateJWT()
    {
        $now = time();
        $exp = strtotime("+{$this->sessout} {$this->sessunit}");
        $payload = array(
            "iat" => $now,
            "nbf" => $now,
            "exp" => $exp,
            "user_id" => $this->user->id
        );
        $this->jwt = JWT::encode($payload, $this->JWTKey);
        $timeout = 3600;
        if ($this->sessunit == 'minutes') {
            $timeout = $this->sessout * 60;
        } elseif ($this->sessunit == 'hours') {
            $timeout = $this->sessout * 3600;
        } elseif ($this->sessunit == 'days') {
            $timeout = $this->sessout * 86400;
        }
        set_cookie($this->cookieName, $this->jwt, $timeout, "", "/", "", is_https(), true, "Lax");
    }
}

