<?php

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

class Auth extends BaseController
{
    public function login()
    {
        return view('login');
    }

    public function attemptLogin()
    {
        $model = new UserModel();
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $user = $model->where('email', $email)->first();

        if (!$user || !password_verify($password, $user['password'])) {
            return redirect()->back()->with('error', 'Invalid login');
        }
        session()->set([
            'user_id' => $user['id'],
            'role'    => $user['role'],
            'isLoggedIn' => true
        ]);

        if ($user['role'] === 'employee') {
            return redirect()->to('employee/dashboard');
        }

        return redirect()->to('admin/dashboard');
    }

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