<?php

namespace App\Controllers\Common;

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

class AuthController extends BaseController
{
    private $_viewDatas = array();
    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' => '로그인',
            'session' => session()
        ];
        $this->initAdapters();
    }

    private function initAdapters()
    {
        foreach (AUTHS['ADAPTERS'] as $site) {
            $this->getAdapter($site);
        }
    }
    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, AUTHS['DEBUG']);
        }
        return $this->_adapters[$site];
    }

    public function login()
    {
        helper(['form']);
        $this->_viewDatas['forms'] = [
            'attributes' => ['method' => "post",],
            'hiddens' => [],
        ];
        //RETURN_URL 존재하면 추가
        if (!is_null(session()->get(LOGINS['RETURN_URL']))) {
            $this->_viewDatas['forms']['hiddens'][LOGINS['RETURN_URL']] = session()->get(LOGINS['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 = session()->get(LOGINS['RETURN_URL']) ? session()->get(LOGINS['RETURN_URL']) : "/";
            return redirect()->to($this->request->getVar(LOGINS['RETURN_URL']) ? $this->request->getVar(LOGINS['RETURN_URL']) : $return_url);
        } catch (\Exception $e) {
            session()->setFlashdata('error', $e->getMessage());
            return redirect()->back()->withInput();
        }
    }

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