<?php

namespace App\Controllers\Auth;

use App\Controllers\AbstractWebController;
use App\Entities\UserEntity;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

abstract class AuthController extends AbstractWebController
{
    private $_layout = 'auth';
    protected $layouts = [];
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->addActionPaths($this->_layout);
        $this->layouts = LAYOUTS[$this->_layout];
    }
    protected function action_init_process(string $action, array $formDatas = []): void
    {
        parent::action_init_process($action, $formDatas);
        $this->addViewDatas('layout', $this->layouts);
        $this->addViewDatas('helper', $this->service->getHelper());
        //Fields,Rules,Filters,Options등 초기화
        $this->service->getActionForm()->form_init_process($action, $formDatas);
        $this->addViewDatas('formFields', $this->service->getActionForm()->getFormFields());
        $this->addViewDatas('formRules', $this->service->getActionForm()->getFormRules());
        $this->addViewDatas('formFilters', $this->service->getActionForm()->getFormFilters());
        $this->addViewDatas('formOptions', $this->service->getActionForm()->getFormOptions());
    }
    //로그인화면
    final public function login_form(): string|RedirectResponse
    {
        $action = __FUNCTION__;
        try {
            //초기화
            $this->action_init_process($action);
        } catch (\Throwable $e) {
            log_message('error', $e->getMessage());
            session()->setFlashdata('message', $e->getMessage());
        }
        return $this->action_render_process($action, $this->getViewDatas());
    }
    //로그인처리
    abstract protected function login_process(): UserEntity;
    final public function login(): RedirectResponse
    {
        try {
            $this->login_process();
            $redirect_url = $this->getAuthContext()->popPreviousUrl() ?? implode(DIRECTORY_SEPARATOR, $this->getActionPaths());
            return redirect()->to($redirect_url)->with('message', MESSAGES['LOGIN']);
        } catch (\Throwable $e) {
            return redirect()->back()->withInput()->with('message', "로그인 중 오류발생:" . $e->getMessage());
        }
    }
    //로그아웃
    abstract protected function logout_process(): void;
    final public function logout(): RedirectResponse
    {
        try {
            $this->logout_process();
            // 홈페이지로 리다이렉트
            $redirect_url = $this->getAuthContext()->popPreviousUrl() ?? "/";
            return redirect()->route($redirect_url)->with('message', MESSAGES['LOGOUT']);
        } catch (\Throwable $e) {
            return redirect()->back()->withInput()->with('message', "로그아웃 중 오류발생:" . $e->getMessage());
        }
    }
}
