<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;

class Auth extends BaseController
{
    protected $userModel;

    public function __construct()
    {
        helper(['form', 'url']);

        $this->userModel = new UserModel();
    }

    public function login()
    {
        if (session()->get('logged_in')) {

            if (session()->get('role') == 'admin') {
                return redirect()->to('/admin/dashboard');
            }
        }

        return view('auth/login');
    }

    public function prosesLogin()
    {
        $username = trim($this->request->getPost('username'));
        $password = $this->request->getPost('password');

        $user = $this->userModel
            ->where('username', $username)
            ->first();

        if (!$user) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Username tidak ditemukan');
        }

        if (!password_verify($password, $user['password'])) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Password salah');
        }

        // HANYA ADMIN YANG BOLEH LOGIN
        if ($user['role'] != 'admin') {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Akun ini tidak memiliki akses sebagai admin');
        }

        session()->set([
            'id_user'      => $user['id'],
            'nama_lengkap' => $user['nama_lengkap'],
            'username'     => $user['username'],
            'role'         => $user['role'],
            'logged_in'    => true
        ]);

        return redirect()->to('/admin/dashboard');
    }

    public function register()
    {
        if (session()->get('logged_in')) {
            return redirect()->to('/');
        }

        return view('auth/register');
    }

    public function prosesRegister()
    {
        $username = trim($this->request->getPost('username'));

        $cekUser = $this->userModel
            ->where('username', $username)
            ->first();

        if ($cekUser) {
            return redirect()->back()
                ->withInput()
                ->with('error', 'Username sudah digunakan');
        }

        $this->userModel->save([
            'nama_lengkap' => $this->request->getPost('nama_lengkap'),
            'username'     => $username,
            'password'     => password_hash(
                $this->request->getPost('password'),
                PASSWORD_DEFAULT
            ),
            'role'         => 'user'
        ]);

        return redirect()->to('/login')
            ->with('success', 'Registrasi berhasil, silakan login');
    }

    public function logout()
    {
        session()->destroy();

        return redirect()->to('/login')
            ->with('success', 'Logout berhasil');
    }
}
