<?php

namespace App\Controllers;

use App\Libraries\Adapter\Auth\Adapter;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class AuthController extends BaseController
{
    private $_adapters = array();
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        helper('Common');
        $this->_viewDatas = [
            'layout' => LAYOUTS['empty'],
            'title' => '로그인',
        ];
        $this->initAdapters();
    }

    private function initAdapters()
    {
        foreach (array_keys(AUTH_ADAPTERS) as $adapter) {
            $this->getAdapter($adapter);
        }
    }
    private function getAdapter(string $site): Adapter
    {
        $site = ucfirst($site);
        if (!array_key_exists($site, $this->_adapters)) {
            $adapterClass = sprintf("\App\Libraries\Adapter\Auth\%sAdapter", $site);
            $this->_adapters[$site] = new $adapterClass($site, AUTH_ADAPTERS[$site]['DEBUG']);
        }
        return $this->_adapters[$site];
    }

    public function login()
    {
        helper(['form']);
        $this->_viewDatas['forms'] = [
            'attributes' => ['method' => "post",],
            'hiddens' => [],
        ];
        //RETURN_URL 존재하면 추가
        if (!$this->_session->get(SESSION_NAMES['RETURN_URL'])) {
            $this->_viewDatas['forms']['hiddens'][SESSION_NAMES['RETURN_URL']] = $this->_session->get(SESSION_NAMES['RETURN_URL']);
        }
        $this->_viewDatas['login_buttons'] = array();
        foreach ($this->_adapters as $key => $adapter) {
            $this->_viewDatas['login_buttons'][$key] = $adapter->getAuthButton();
        }
        return view('auth/login', $this->_viewDatas);
    }

    public function signin(string $site)
    {
        try {
            //각 Adapter별 인층체크 후 Session에 인증정보 설정
            $this->getAdapter($site)->signin($this->request->getVar());
            $return_url = $this->_session->get(SESSION_NAMES['RETURN_URL']) ?: "/";
            return redirect()->to($this->request->getVar(SESSION_NAMES['RETURN_URL']) ?: $return_url);
        } catch (\Exception $e) {
            $this->_session->setFlashdata('error', $e->getMessage());
            return redirect()->back()->withInput();
        }
    }

    public function logout()
    {
        //로그인 여부 확인후 Session에 Login 정보 삭제
        if ($this->_session->get(SESSION_NAMES['USER'])) {
            session_destroy();
        }
        return redirect()->route('/');
    }
}
