<?php

namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\Controller;

class AuthController extends Controller
{
    public function index()
    {
        helper(['form']);
        return view('auth/login');
    }

    public function login()
    {
        $session = session();
        $model = new UserModel();
        
        $username = $this->request->getVar('username');
        $password = $this->request->getVar('password');
        
        $user = $model->where('username', $username)->first();
        
        if ($user) {
            $pass = $user['password_hash'];
            if (password_verify($password, $pass)) {
                $ses_data = [
                    'id'           => $user['id'],
                    'username'     => $user['username'],
                    'role'         => $user['role'],
                    'nama_lengkap' => $user['nama_lengkap'],
                    'logged_in'    => TRUE
                ];
                $session->set($ses_data);
                
                // Redirect based on role
                if ($user['role'] == 'wali') {
                    return redirect()->to('/wali');
                } elseif ($user['role'] == 'kesantrian') {
                    return redirect()->to('/kesantrian');
                } elseif ($user['role'] == 'satpam') {
                    return redirect()->to('/satpam');
                } elseif ($user['role'] == 'admin') {
                    return redirect()->to('/admin');
                }
            } else {
                $session->setFlashdata('msg', 'Password salah.');
                return redirect()->to('/login');
            }
        } else {
            $session->setFlashdata('msg', 'Username tidak ditemukan.');
            return redirect()->to('/login');
        }
    }

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