<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\LoginModel;

class Login extends BaseController
{
    protected $loginModel;

    public function __construct()
    {
        $this->loginModel = new LoginModel();
    }

    public function index()
    {
        return view('admin/login');
    }

    public function authenticate()
    {
        $rules = [
            'username' => 'required',
            'password' => 'required'
        ];

        if (! $this->validate($rules)) {
            return view('admin/login', [
                'validation' => $this->validator
            ]);
        }

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

        $user = $this->loginModel->verify($username, $password);

        if ($user) {

            
            session()->set([
                'user_id'    => $user->id,
                'role'       => $user->role,
                'name'       => $user->name,
                'isLoggedIn' => true
            ]);

            return redirect()->to(base_url('home'));


        } else {

            session()->setFlashdata('error', 'Invalid Username Or Password');
            return redirect()->back();
        }
    }
	
	
	public function logout()
{
    // Destroy session
    session()->destroy();

    // Redirect to login page
    return redirect()->to(base_url('/'));
}
}
