<?php

namespace App\Controllers;

use App\Core\View;
use App\Helpers\UserMapper;
use App\Models\StatusAkun;
use App\Repositories\UserRepo;

class LoginController
{

  private View $view;
  private UserRepo $userRepo;

  public function __construct()
  {
    $this->view = new View();
    $this->userRepo = new UserRepo();
  }

  public function index(): void
  {
    if (isset($_SESSION['user'])) {
      redirect("HOME");
    }
    $this->view->renderAuthPage("login/index", [
      "title" => "Login"
    ]);
  }

  public function login(): void
  {
    $usernameOrEmail = $_POST['usernameOrEmail'];
    $password = $_POST['password'];

    // find by username or email
    $user = $this->userRepo->getByUsername($usernameOrEmail);
    if (!$user) {
      $user = $this->userRepo->getByEmail($usernameOrEmail);
    }

    if (!$user) {
      $_SESSION['error'] = 'User tidak terdaftar';
      redirect("LOGIN");
    }

    $active = $user->getStatusAkun() === StatusAkun::AKTIF;
    if (!$active) {
      $_SESSION['error'] = 'User tidak aktif';
      redirect("LOGIN");
    }

    if (password_verify($password, $user->getPassword())) {

      $userRole = $user->getRole()->value;
      $_SESSION['user'] = UserMapper::excludePassword($user);

      // dd($_SESSION);

      switch ($userRole) {
        case 'ADMIN':
          redirect("DASHBOARD");
        case 'USER':
          redirect("HOME");
        case 'TEKNISI':
          redirect("TEKNISI");
        default:
          redirect("LOGOUT");
      }
    } else {
      $_SESSION['error'] = 'Username atau password salah';
      redirect("LOGIN");
    }
  }

  public function logout(): void
  {
    unset($_SESSION['user']);
    redirect("LOGIN");
  }
}
