<?php

namespace App\Controllers;

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


class AuthController extends Controller
{
    /**
     * Instance of the main Request object.
     *
     * @var CLIRequest|IncomingRequest
     */
    protected $request;

    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    protected $helpers = ['Common'];

    /**
     * Be sure to declare properties for any property fetch you initialized.
     * The creation of dynamic property is deprecated in PHP 8.2.
     */
    // protected $session;

    /**
     * Constructor.
     */
    private $_session = null;
    private $_viewDatas = array();
    private $_adapters = array();
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_session = \Config\Services::session();
        $this->_viewDatas['title'] = 'Auth';
        $this->_viewDatas['layout'] = LAYOUTS['empty'];
        $this->_viewDatas['session'] = $this->_session;
        $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()
    {
        foreach ($this->_adapters as $key => $adapter) {
            $this->_viewDatas['login_buttons'][$key] = $adapter->getAuthButton();
        }
        $this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => []];
        helper(['form']);
        $this->_session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
        return view('auth/login', $this->_viewDatas);
    }

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

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