<?php

namespace App\Controllers;

use App\Controllers\BaseController;

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

    public function process()
    {
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $db = \Config\Database::connect();

        $user = $db->table('users')->where('email', $email)->get()->getRow();

        if (!$user)
            return redirect()->back()->with('error', 'Email tidak ditemukan');

        if (!password_verify($password, $user->password))
            return redirect()->back()->with('error', 'Password salah');

        if ($user->status != 1)
            return redirect()->back()->with('error', 'Akun belum aktif');

        session()->set([
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'role_id' => $user->role_id,
            'login' => true
        ]);

        return redirect()->to(site_url('dashboard'));
    }

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