<?php
// app/Controllers/Backend/AuthController.php
namespace App\Controllers\Backend;

use App\Controllers\BaseController;
use App\Models\AdminModel;
use App\Models\AdminRoleModel;

class AuthController extends BaseController
{
    public function showLoginForm()
    {
        // Tampilkan view login untuk backend
        return view('backend/auth/login');
    }

    public function processLogin()
    {
        $rules = ['email' => 'required|valid_email', 'password' => 'required'];
        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        $adminModel = new AdminModel();
        $admin = $adminModel->where('email', $email)->first();

        if (!$admin || !password_verify($password, $admin->password)) {
            return redirect()->route('admin.login.show')->with('error', lang('Admin/Login.errorInvalid'));
        }

        // Jika kredensial benar, buat sesi admin
        $this->logAdminIn($admin);

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

    private function logAdminIn(object $admin): void
    {
        // Ambil role ID untuk disimpan di session
        $adminRoleModel = new AdminRoleModel();
        $role = $adminRoleModel->where('admin_id', $admin->id)->first();

        $sessionData = [
            'user_id'    => $admin->id,
            'user_name'  => $admin->name,
            'user_email' => $admin->email,
            'role_id'    => $role['role_id'] ?? null,
            'user_type'  => 'admin', // Tandai sebagai 'admin'
            'isLoggedIn' => true,
        ];

        session()->set($sessionData);
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to(route_to('admin.login.show'))->with('success', lang('Admin/Login.successLogout'));
    }
}