<?php

namespace App\Controllers;

use App\Models\AdminModel;

class LoginAdminController 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('admin/dashboard');
        }

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

    public function auth()
    {
        $session = session();
        $model = new AdminModel();
        $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,
                'userEmail' => $email,
                'loggedIn' => true
            ];
            $session->set($ses_data);
            return redirect()->to('admin/dashboard');
        } else {
            $session->setFlashdata('error', 'Email atau Password salah');
            return redirect()->to('admin/login');
        }
    }

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