<?php

namespace App\Controllers;
use App\Models\UserModel;

class Auth extends BaseController
{
    public function index()
    {
        // Jika sudah login, langsung arahkan ke Dashboard
        if (session()->get('sudah_login')) {
            return redirect()->to('/');
        }
        return view('login');
    }

    public function proses_login()
    {
        $userModel = new UserModel();
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

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

        if ($cekUser) {
            // Cocokkan password
            if (password_verify($password, $cekUser['password'])) {
                // Buat sesi login
                session()->set([
                    'id_user'      => $cekUser['id_user'],
                    'nama_lengkap' => $cekUser['nama_lengkap'],
                    'role'         => $cekUser['role'],
                    'sudah_login'  => true
                ]);
                return redirect()->to('/');
            } else {
                return redirect()->to('/login')->with('error', 'Password salah!');
            }
        } else {
            return redirect()->to('/login')->with('error', 'Username tidak ditemukan!');
        }
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login');
    }
}