<?php namespace App\Controllers;

use App\Models\UserModel;

class AuthController extends BaseController
{
    public function login()
    {
        return view('auth/login');
    }

    public function processLogin()
    {
        $session = session();
        $model = new UserModel();
        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
        $user = $model->where('email', $email)->first();

        if ($user && password_verify($password, $user['password'])) {
            $session->set(['id' => $user['id'], 'Fname' => $user['Fname'],'Lname' => $user['Lname'], 'email' => $user['email'], 'role' => $user['role'], 'isLoggedIn' => true]);
            return redirect()->to("/{$user['role']}/dashboard");
        } else {
            return redirect()->back()->with('fail', 'Invalid login');
        }
    }

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