<?php

namespace App\Controllers\Admin;

use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;

use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use Psr\Log\LoggerInterface;

use App\Helpers\UserHelper;
use App\Services\UserService;

class UserController extends AdminController
{
    private $_db;
    private $_service = null;
    private $_helper = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->content_title = lang("{$this->getService()->getClassName()}.title");
        $this->class_path .= $this->getService()->getClassName();
        $this->uri_path .= strtolower($this->getService()->getClassName('/')) . '/';
        // $this->view_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
        $this->_db = \Config\Database::connect();
    }
    final public function getService(): UserService
    {
        if (!$this->_service) {
            $this->_service = new UserService();
        }
        return $this->_service;
    }
    public function getHelper(): UserHelper
    {
        if (!$this->_helper) {
            $this->_helper = new UserHelper();
        }
        return $this->_helper;
    }
    //Index,FieldForm관련
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        switch ($this->getAction()) {
            case 'profile_modify':
                $this->getMyLogService()->save($this->getService()->getClassName(), $this->getAction(), $message, $this->getMyAuth()->getUIDByAuthInfo());
                $result = $this->view($this->entity->getPK());
                break;
            case 'profile_modify_form':
                $this->control = $this->getControlDatas();
                $this->getHelper()->setViewDatas($this->getViewDatas());
                $actionTemplate = $this->request->getVar('ActionTemplate') ?? $actionTemplate;
                if ($actionTemplate) {
                    $view_file = $this->view_path . $actionTemplate . DIRECTORY_SEPARATOR . 'modify_form';
                } else {
                    $view_file = $this->view_path . 'modify_form';
                }
                $result = view($view_file, ['viewDatas' => $this->getViewDatas()]);
                break;
            default:
                $result = parent::getResultSuccess($message, $actionTemplate);
                break;
        }
        return $result;
    }
    protected function setValidation(Validation $validation, string $field, string $rule): Validation
    {
        switch ($field) {
            case 'role':
                //아래 Rule Array는 필드명.* checkbox를 사용
                $validation->setRule("{$field}.*", $field, $rule);
                break;
            default:
                $validation = parent::setValidation($validation, $field,  $rule);
                break;
        }
        return $validation;
    }
    //Index,FieldForm관련.
    protected function profile_modify_form_process(mixed $entity): mixed
    {
        return $entity;
    }
    final public function profile_modify_form(mixed $uid): RedirectResponse|string
    {
        try {
            //각 Field 초기화
            $fields = [
                'formFields' => ['id', 'passwd', 'confirmpassword', 'name', 'email', 'mobile'],
            ];
            // $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            $this->initAction(__FUNCTION__, $fields);
            //FieldRule정의
            foreach ($this->getFormFields() as $field) {
                $this->setFieldRule($field, $this->getFormFieldRule($this->getAction(), $field));
            }
            helper(['form']);
            //filter_fields에 해당하는 값이 있을 경우 정의
            $this->setFilterValues();
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->entity = $this->profile_modify_form_process($entity);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
    protected function profile_modify_process(mixed $entity, array $formDatas): mixed
    {
        //데이터 검증
        $validDatas =  $this->doValidate($this->getFieldRules(), $formDatas);
        return $this->getService()->modify($entity, $validDatas);
    }
    final public function profile_modify(int $uid): RedirectResponse|string
    {
        //Transaction Start
        $this->_db->transStart();
        try {
            //각 Field 초기화
            $fields = [
                'formFields' => ['id', 'passwd', 'confirmpassword', 'name', 'email', 'mobile'],
            ];
            $this->initAction(__FUNCTION__, $fields);
            //FieldRule정의
            foreach ($this->getFormFields() as $field) {
                $this->setFieldRule($field, $this->getFormFieldRule($this->getAction(), $field));
            }
            //입력값정의
            $formDatas = [];
            foreach ($this->getFormFields() as $field) {
                $formDatas[$field] = $this->request->getPost($field);
            }
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->entity = $this->profile_modify_process($entity,  $formDatas);
            $this->_db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $this->_db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
}
