<?php

namespace App\Controllers\Front;

use App\Libraries\Adapter\Auth\Auth as AuthAdapter;
use App\Models\UserModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class UserController extends FrontController
{
    const DEFAULT_CATEGORY = "userinfo";
    private $_adapters = array();
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_model = new UserModel();
        $this->_viewDatas['className'] = 'User';
        $this->_viewPath .= strtolower($this->_viewDatas['className']);
        $this->_viewDatas['title'] = lang($this->_viewDatas['className'] . '.title');
        $this->_viewDatas['class_icon'] = CLASS_ICONS[strtoupper($this->_viewDatas['className'])];
        helper($this->_viewDatas['className']);
        $this->initAdapters();
    }

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

    //Field별 Form Datas 처리용
    protected function getFieldFormData(string $field, $entity = null): array
    {
        switch ($field) {
            case 'passwd':
                $this->_viewDatas['fieldDatas'][$field] = $this->request->getVar($field);
                $this->_viewDatas['fieldDatas']['confirmpassword'] = $this->request->getVar('confirmpassword');
                break;
            default:
                return parent::getFieldFormData($field, $entity);
                break;
        }
        return $this->_viewDatas['fieldDatas'];
    }

    public function getFields(string $action = ""): array
    {
        switch ($action) {
            case 'insert':
                return ["id", "passwd", 'name', "email", "phone", "mobile"];
                break;
            case 'update':
                return ["passwd", 'name', "email", "phone", "mobile"];
                break;
            case "index":
            case "excel":
                return ["id", 'name', "email", "phone", "mobile", 'created_at'];
                break;
            case "view":
                return ["id", 'name', "email", "phone", "mobile", 'updated_at', 'created_at'];
                break;
            default:
                return [];
                break;
        }
    }
    public function getFieldFilters(): array
    {
        return [];
    }
    public function getFieldBatchFilters(): array
    {
        return parent::getFieldBatchFilters();
    }

    //Insert관련
    protected function insert_form_process()
    {
        //Category 확인
        $this->setCategory($this->request->getVar('category') ?: self::DEFAULT_CATEGORY);
        parent::insert_form_process();
    }
    protected function insert_process()
    {
        //Role이 반드시 있어야 하기때문에
        $this->_viewDatas['fieldDatas']['role'] = DEFAULTS['ROLE'] . ',user';
        return parent::insert_process();
    }

    //Update관련
    protected function update_form_process($entity)
    {
        //Category 확인
        $this->setCategory($this->request->getVar('category') ?: self::DEFAULT_CATEGORY);
        return parent::update_form_process($entity);
    }

    //Index관련
    protected function index_process()
    {
        //Category 확인
        $this->setCategory($this->request->getVar('category') ?: self::DEFAULT_CATEGORY);
        parent::index_process();
    }
    //사용자 UID 조건추가
    protected function index_condition()
    {
        $this->_model->where("uid", $this->_viewDatas['auth'][AUTH_FIELDS['ID']]);
        parent::index_condition();
    }

    //추가기능
    public function login_form()
    {
        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($this->_viewPath . '/login' . $this->request->getVar('v') ?: '', ['viewDatas' => $this->_viewDatas]);
    }

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

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