<?php

namespace App\Controllers;

use App\Models\CompanyModel;
use Exception;

class LoginController extends BaseController
{
    public function index()
    {
        $session = session();

        // Cek apakah user sudah login
        if ($session->get('loggedIn')) {
            // Pengguna sudah login, arahkan ke dashboard
            return redirect()->to('company/vacancies');
        }

        // Tampilkan halaman login jika belum login
        return view('company/login');
    }

    public function auth()
    {
        $session = session();
        $model = new CompanyModel();
        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
        $data = $model->login($email, $password);

        if ($data && $data->status == 'Success') {
            $ses_data = [
                'userId'     => $data->id,
                'name'     => $data->name,
                'logo'     => $data->logo,
                'userEmail'  => $email,
                'roleId'     => $data->roleId,
                'token'      => $data->token,
                'loggedIn'   => true
            ];
            $session->set($ses_data);
            return redirect()->to('company/vacancies');
        } else {
            $session->setFlashdata('error', 'Email atau Password salah');
            return redirect()->to('company/login');
        }
    }


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