<?php

namespace App\Controllers\Panel\Auth;

use App\Controllers\Panel\BC;
use App\Models\Panel\UserModel as UserPanelModel;
use App\Models\Mobile\UserModel as UserMobileModel;
use CodeIgniter\API\ResponseTrait;
use Firebase\JWT\JWT;

class Account extends BC
{
    use ResponseTrait;
    private $type, $redirect_url;
    public function switch($type, $id)
    {
        $user = null;
        switch ($type) {
            case base64_encode(1):
                if (!user()->hasRole('admin')) return view('Utils/404', ['page_title' => 'Akses Ditolak', 'code' => 403, 'text' => 'Anda tidak dapat mengakses halaman ini']);
                $this->type = "panel";
                $this->redirect_url = base_url('panel/auth/login');
                $user = (new UserPanelModel())->findId(base64_decode($id));
                break;
            case base64_encode(2):
                $this->type = "mobile";
                $this->redirect_url = base_url();
                $user = (new UserMobileModel())->findId(base64_decode($id));
                break;
            default:
                return "Tidak Valid!";
                break;
        }
        if (!$user) return "Pengguna Tidak Ditemukan!";
        $jwt = $this->generateJWT($user->id);
        set_cookie("rwno" . options($this->type == "panel" ? "PANELCN" : "MOBILECN"), $jwt, 3600 * 24 * 30, "", "/", "", is_https(), true, "Lax");
        if ($this->type == "panel") setLog("Memasuki akun staff " . $user->fullname);
        else setLog("Memasuki akun siswa " . $user->nama);
        return view('Panel/Auth/switch-account', ['redirect_url' => $this->redirect_url]);
    }
    private function generateJWT($userid)
    {
        $now = time();
        $exp = strtotime('+30 days');
        $key = options($this->type == "panel" ? "PANELJWTKEY" : "MOBILEJWTKEY");
        $payload = array(
            "iat" => $now,
            "nbf" => $now,
            "exp" => $exp,
            "user_id" => $userid
        );
        $jwt = JWT::encode($payload, $key);
        return $jwt;
    }
}
