<?php

namespace App\Controllers\Panel\Auth;

use App\Controllers\Panel\BC;
use App\Models\Panel\UserModel;
use CodeIgniter\API\ResponseTrait;
use Exception;
use Firebase\JWT\JWT;

class Login extends BC
{
    use ResponseTrait;
    public function index()
    {
        if (logged_in()) return redirect()->to(dashboard_url());
        $errMsg = "";
        if (!(strpos(current_url(), "install") !== false)) {
            if (!(options('licensekey') ?? "")) $errMsg = "Kode Lisensi Tidak Valid";
            elseif ((options('eat') ?? 0) < time()) $errMsg = "Kode Lisensi Kedaluwarsa";
        }
        try {
            db_connect()->tableExists('options');
            if (!options('appname')) throw new Exception("App Configuration doesn't exist");
        } catch (\Throwable $th) {
            $bu = base_url();
            if (strpos($th->getMessage(), 'Unable to connect to the database') !== false) {
                $errMsg = "Database belum terhubung <a href='$bu/pnli'>Hubungkan</a>";
            }
            if (strpos($th->getMessage(), "doesn't exist") !== false) {
                $errMsg = "Aplikasi belum diinstal lanjutkan untuk melakukan installasi <a href='$bu/pnli'>Install</a>";
            }
        }
        return view('Panel/Auth/login', ['page_title' => "Masuk", 'errMsg' => $errMsg]);
    }
    public function check()
    {
        if (!$this->request->isAJAX() && ENVIRONMENT != 'development') {
            exit('No direct script access allowed');
        }
        $common_response = 'Username atau Password Salah';
        $pcn = options('PANELCN');
        if (!$pcn) return $this->fail(['csrf' => csrf_hash(), 'message' => 'Instalasi tidak sempurna, silahkan hapus file .env dan install ulang'], 403);
        $userModel = new UserModel();
        $username = $this->request->getVar('username');
        $password = $this->request->getVar('password');
        $user = $userModel->where(['username' => $username])->first();
        if (!$user) return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'Akun Tidak Ditemukan' : $common_response], 404);
        if ($user->status != 1) return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'Akun Tidak Aktif' : $common_response], 403);
        if (!$user->passwordVerify($password)) return $this->fail(['csrf' => csrf_hash(), 'message' => ENVIRONMENT != 'production' ? 'Password Salah' : $common_response], 404);

        $jwt = $this->generateJWT($user->id);
        $sessout = options('panel_session_timeout');
        $sessunit = options('panel_session_unit');
        $timeout = 3600;
        if ($sessunit == 'minutes') {
            $timeout = $sessout * 60;
        } elseif ($sessunit == 'hours') {
            $timeout = $sessout * 3600;
        } elseif ($sessunit == 'days') {
            $timeout = $sessout * 86400;
        }
        set_cookie($pcn, $jwt, $timeout, "", "/", "", is_https(), true, "Lax");
        $user = (new UserModel())->findId($user->id);
        $GLOBALS['panel_user'] = $user;
        setLog("Masuk akun", ['fullname' => $user->fullname]);
        return $this->respond(['message' => 'Berhasil Masuk', 'redirect_url' => dashboard_url()]);
    }

    private function generateJWT($userid)
    {
        $now = time();
        $sessout = options('panel_session_timeout');
        $sessunit = options('panel_session_unit');
        $exp = strtotime("+$sessout $sessunit");
        $key = options('PANELJWTKEY');
        $payload = array(
            "iat" => $now,
            "nbf" => $now,
            "exp" => $exp,
            "user_id" => $userid
        );
        $jwt = JWT::encode($payload, $key);
        return $jwt;
    }
}
