<?php

namespace App\Controllers;

use App\Models\UserModel;

class AuthController extends BaseController
{
    public function login()
    {
        // If already logged in, redirect to correct dashboard
        if (session()->get('logged_in')) {
            return $this->redirectUserBasedOnRole(session()->get('role'));
        }

        return view('auth/login', ['title' => 'Login - Sistem Perizinan IBK']);
    }

    public function attemptLogin()
    {
        $session = session();
        $userModel = new UserModel();

        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');

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

        if ($user) {
            if (password_verify($password, $user['password'])) {
                $sessionData = [
                    'user_id'      => $user['id'],
                    'username'     => $user['username'],
                    'role'         => $user['role'],
                    'nama_lengkap' => $user['nama_lengkap'],
                    'logged_in'    => true,
                ];
                $session->set($sessionData);
                
                return $this->redirectUserBasedOnRole($user['role'])
                    ->with('success', 'Selamat datang kembali, ' . $user['nama_lengkap']);
            }
        }

        return redirect()->to('/login')->with('error', 'Username atau password salah.')->withInput();
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/login')->with('success', 'Anda telah berhasil logout.');
    }

    private function redirectUserBasedOnRole($role)
    {
        switch ($role) {
            case 'admin':
                return redirect()->to('/admin/dashboard');
            case 'kesantrian':
                return redirect()->to('/kesantrian/dashboard');
            case 'satpam':
                return redirect()->to('/satpam/dashboard');
            case 'wali':
                return redirect()->to('/wali/dashboard');
            default:
                session()->destroy();
                return redirect()->to('/login')->with('error', 'Role tidak valid.');
        }
    }
}
