<?php

namespace App\Controllers\Common;

use App\Controllers\BaseController;
use App\Entities\UserEntity;
use App\Models\UserModel;

class AuthController extends BaseController
{
    public function login()
    {
        helper(['form']);
        $viewDatas = [
            'layout' => LAYOUTS['empty'],
            'title' => '로그인',
            'forms' => [
                'attributes' => ['action' => 'post', 'class' => 'row g-3'],
                'hiddens' => [RETURN_URL => session()->get(RETURN_URL)],
            ]
        ];
        return view('auth/login', $viewDatas);
    }

    public function signin()
    {
        $id        = $this->request->getVar('id');
        $passwd    = $this->request->getVar('passwd');
        $model = new UserModel();
        $user = $model->asObject(UserEntity::class)->where('id', $id)->first();
        if (is_null($user) || !isset($user->passwd)) {
            session()->setFlashdata('error', "사용자ID: {$id}가 존재하지 않습니다.");
            return redirect()->back()->withInput();
        }
        if (password_verify($passwd, $user->passwd)) {
            //Session에 Login 정보전달
            $authData = [
                'uid' => $user->uid,
                'name' => $user->name,
                'email' => $user->email,
                'role' => $user->role,
                ISLOGIN => true
            ];
            session()->set($authData);
            return redirect()->to($this->request->getVar(RETURN_URL) ? $this->request->getVar(RETURN_URL) : "/");
        } else {
            session()->setFlashdata('error', '암호가 맞지 않습니다.');
            return redirect()->back()->withInput();
        }
    }

    public function logout()
    {
        //Session에 Login 정보 삭제
        session()->set([ISLOGIN => false]);
        session_destroy();
        return redirect()->route('/');
    }
}
