<?php

namespace App\Controllers;

use App\Models\AdminModel;

class Auth extends BaseController
{
    public function login()
    {
        if (session()->get('admin_id')) {
            return redirect()->to('/kas');
        }

        return view('auth/login', [
            'title' => 'Login Admin',
        ]);
    }

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

        if ($username === '' || $password === '') {
            return redirect()->back()->withInput()->with('error', 'Username dan password wajib diisi.');
        }

        $admin = (new AdminModel())->where('username', $username)->first();

        if (! $admin || ! password_verify($password, $admin['password'])) {
            return redirect()->back()->withInput()->with('error', 'Username atau password salah.');
        }

        session()->regenerate(true);
        session()->set([
            'admin_id'       => $admin['id'],
            'admin_nama'     => $admin['nama'],
            'admin_username' => $admin['username'],
        ]);

        return redirect()->to('/kas')->with('success', 'Login berhasil. Selamat datang, ' . $admin['nama'] . '.');
    }

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

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