<?php

namespace App\Controllers;

use App\Controllers\BaseController;

use App\Libraries\LogCollector;
use CodeIgniter\HTTP\DownloadResponse;

use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use PhpOffice\PhpSpreadsheet\IOFactory;

use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use Psr\Log\LoggerInterface;

abstract class CommonController extends BaseController
{
    private $_myAuth = null;
    private $_viewDatas = [];
    abstract public function getService(): mixed;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->isLoggedIn = false;
        $this->uri    = $request->getUri();
        if ($this->getMyAuth()->isLoggedIn()) {
            $this->isLoggedIn = true;
            $this->myAuthName = $this->getMyAuth()->getNameByAuthInfo();
            $this->myAuthUID = $this->getMyAuth()->getUIDByAuthInfo();
        }
    }
    final public function __get($name)
    {
        if (!array_key_exists($name, $this->_viewDatas)) {
            return null;
        }
        return $this->_viewDatas[$name];
    }
    final public function __set($name, $value): void
    {
        $this->_viewDatas[$name] = $value;
    }
    final public function getMyAuth(): mixed
    {
        if (!$this->_myAuth) {
            $this->_myAuth = service('myauth');
        }
        return $this->_myAuth;
    }
    final protected function getViewDatas(): array
    {
        return $this->_viewDatas;
    }
    //Index,FieldForm관련
    //FormDatas 전달값,Default값
    //FormDatas 검증
    final protected function doValidations(): void
    {
        //변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요
        $validation = service('validation');
        foreach ($this->getService()->getControlDatas('field_rules') as $field => $rule) {
            $validation = $this->doValidation($validation, $field, $rule);
        }
        if (!$validation->run($this->getService()->getFormDatas())) {
            throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode(
                "\n",
                $validation->getErrors()
            ));
        }
        // return $validation->getValidated();
    }
    //공통 필수기능
    //FormData Field별 전달값 처리
    protected function doValidation(Validation $validation, string $field, string $rule): Validation
    {
        switch ($field) {
            default:
                $validation->setRule($field, $field, $rule);
                break;
        }
        return $validation;
    }
    //Process Result처리
    protected function getResultFail(string $message = MESSAGES["FAILED"]): RedirectResponse
    {
        if ($this->request->getMethod() === 'POST') {
            return redirect()->back()->withInput()->with('error', $message);
        }
        return redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
    }
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        helper(['form']);
        switch ($this->getService()->getControlDatas('action')) {
            case 'create':
            case 'modify':
                $result = $this->view($this->entity->getPK());
                break;
            case 'create_form':
            case 'modify_form':
            case 'login_form':
            case 'view':
            case 'index':
            case 'download':
                $this->service = $this->getService();
                $this->control = $this->getService()->getControlDatas();
                $this->getService()->getHelper()->setViewDatas($this->getViewDatas());
                $actionTemplate = $this->request->getVar('ActionTemplate') ?? $actionTemplate;
                if ($actionTemplate) {
                    $view_file = $this->view_path . $actionTemplate . DIRECTORY_SEPARATOR . $this->getService()->getAction();
                } else {
                    $view_file = $this->view_path . $this->getService()->getAction();
                }
                $result = view($view_file, ['viewDatas' => $this->getViewDatas()]);
                break;
            default:
                $result = redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
                break;
        }
        return $result;
    }
    //Index,FieldForm관련
    //생성 기본기능
    protected function create_form_process(): void {}
    public function create_form(): RedirectResponse|string
    {
        try {
            //초기화
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getGet());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            $this->create_form_process();
            helper(['form']);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
    protected function create_process(array $formDatas): mixed
    {
        return $this->getService()->create($formDatas);
    }
    public function create(): RedirectResponse|string
    {
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getPost());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->doValidations();
            $this->entity = $this->create_process($this->getService()->getFormDatas());
            $db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //수정 기본기능
    protected function modify_form_process(mixed $entity): mixed
    {
        return $entity;
    }
    public function modify_form(mixed $uid): RedirectResponse|string
    {
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getGet());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->entity = $this->modify_form_process($entity);
            helper(['form']);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
    protected function modify_process(mixed $entity, array $formDatas): mixed
    {
        return $this->getService()->modify($entity, $formDatas);
    }
    public function modify(int $uid): RedirectResponse|string
    {
        //Transaction Start
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getPost());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->doValidations();
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->entity = $this->modify_process($entity, $this->getService()->getFormDatas());
            $db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //단일필드작업기능
    protected function toggle_process(mixed $entity, array $formDatas): mixed
    {
        return $this->getService()->toggle($entity, $formDatas);
    }
    public function toggle(mixed $uid, string $field): RedirectResponse|string
    {
        //Transaction Start
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields([$field]);
            //전달값정의
            $this->getService()->setFormDatas($this->request->getGet());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            $this->doValidations();
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->entity = $this->toggle_process($entity, $this->getService()->getFormDatas());
            $db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //일괄처리작업기능
    protected function batchjob_process(mixed $entity, array $formDatas): mixed
    {
        return $this->getService()->batchjob($entity, $formDatas);
    }
    private function batchjob_pre_process(): array
    {
        $selectedFields = [];
        $formDatas = [];
        foreach ($this->getService()->getBatchjobFields() as $field) {
            $value = $this->request->getPost($field);
            if ($value) {
                $selectedFields[] = $field;
                $formDatas[$field] = $value;
            }
        }
        if (!count($selectedFields)) {
            throw new \Exception("변경할 조건항목을 선택하셔야합니다.");
        }
        //변경할 UIDS 정의
        $uids = $this->request->getPost('batchjob_uids[]');
        if (!is_array($uids) || !count($uids)) {
            throw new \Exception("적용할 리스트을 선택하셔야합니다.");
        }
        return [$selectedFields, $formDatas, $uids];
    }
    public function batchjob(): RedirectResponse|string
    {
        //Transaction Start
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            $this->getService()->setAction(__FUNCTION__);
            list($selectedFields, $formDatas, $uids) = $this->batchjob_pre_process();
            $this->getService()->setFormFields($selectedFields);
            //전달값정의
            $this->getService()->setFormDatas($this->request->getPost());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            $this->doValidations();
            $entities = [];
            foreach ($uids as $uid) {
                //기존 Entity 가져오기
                $entity = $this->getService()->getEntity($uid);
                if (!$entity) {
                    throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
                }
                $entities[] = $this->batchjob_process($entity, $formDatas);
            }
            $this->entities = $entities;
            $db->transCommit();
            LogCollector::debug(sprintf("%s에서 총 %s개중 %s개 일괄작업을 완료하였습니다.", __METHOD__, count($uids), count($this->entities)));
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //삭제관련
    protected function delete_process(mixed $entity): mixed
    {
        return $this->getService()->delete($entity);
    }
    public function delete(mixed $uid): RedirectResponse|string
    {
        //Transaction Start
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            $this->getService()->setAction(__FUNCTION__);
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->delete_process($entity);
            $db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //일괄삭제관련
    protected function batchjob_delete_process(mixed $entity): mixed
    {
        return $this->getService()->delete($entity);
    }
    private function batchjob_delete_pre_process(): array
    {
        //변경할 UIDS
        $uids = $this->request->getPost('batchjob_uids[]');
        if (!is_array($uids) || !count($uids)) {
            throw new \Exception("적용할 리스트를 선택하셔야합니다.");
        }
        return $uids;
    }
    public function batchjob_delete(): RedirectResponse|string
    {
        //Transaction Start
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            $this->getService()->setAction(__FUNCTION__);
            $uids = $this->batchjob_delete_pre_process();
            $entities = [];
            foreach ($uids as $uid) {
                //기존 Entity 가져오기
                $entity = $this->getService()->getEntity($uid);
                if (!$entity) {
                    throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
                }
                $entities[] = $this->batchjob_delete_process($entity);
            }
            $this->entities = $entities;
            $db->transCommit();
            LogCollector::debug(sprintf("%s에서 총 %s개중 %s개 일괄삭제를 완료하였습니다.", __METHOD__, count($uids), count($this->entities)));
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //View 관련
    protected function view_process(mixed $entity): mixed
    {
        return $entity;
    }
    public function view(string $uid): RedirectResponse|string
    {
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getGet());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            //기존 Entity 가져오기
            $entity = $this->getService()->getEntity($uid);
            if (!$entity) {
                throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
            }
            $this->entity = $this->view_process($entity);
            helper(['form']);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
    //리스트관련
    //조건절 처리
    protected function index_condition_process(): void
    {
        //Filter조건절 처리
        $index_filters = [];
        foreach ($this->getService()->getControlDatas('actionFilters') as $field) {
            $value = $this->getService()->getFormDatas()[$field] ?? null;
            if ($value) {
                $this->getService()->index_condition_filterField($field, $value);
                $index_filters[$field] = $value;
            }
        }
        $this->getService()->setControlDatas('index_filters', $index_filters);
        //검색어조건절 처리
        $index_word = $this->request->getVar('index_word');
        if ($index_word !== null && $index_word !== '') {
            $this->getService()->index_condition_filterWord($index_word);
        }
        $this->getService()->setControlDatas('index_word', $index_word);
        //날자검색
        $index_start  = $this->request->getVar('index_start');
        $index_end  = $this->request->getVar('index_end');
        if ($index_start !== null && $index_start !== '' && $index_end !== null && $index_end !== '') {
            $this->getService()->index_condition_filterDate($index_start, $index_end);
        }
        $this->getService()->setControlDatas('index_start', $index_start);
        $this->getService()->setControlDatas('index_end', $index_end);
    }
    //PageNation 처리
    protected function index_pagenation_process($pager_group = 'default', int $segment = 0, $template = 'bootstrap_full')
    {
        //Page, Per_page필요부분
        $this->page = (int) $this->request->getVar('page') ?: 1;
        $this->per_page = (int) $this->request->getVar('per_page') ?: intval(DEFAULT_LIST_PERPAGE ?? 20);
        // 1.Views/Pagers/에 bootstrap_full.php,bootstrap_simple.php 생성
        // 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full',
        // 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가
        $pager = service("pager");
        $pager->makeLinks($this->page, $this->per_page, $this->total_count, $template, $segment, $pager_group);
        $this->page = $pager->getCurrentPage($pager_group);
        $this->total_page = $pager->getPageCount($pager_group);
        return $pager->links($pager_group, $template);
    }
    //Page출력 처리
    protected function index_pageOptions_process(): array
    {
        $page_options = ["" => "줄수선택"];
        for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) {
            $page_options[$i] = $i;
        }
        $page_options[$this->total_count] = $this->total_count;
        return $page_options;
    }
    //Entities처리
    protected function index_process(array $entities = []): array
    {
        foreach ($this->getService()->getEntities() as $entity) {
            $entities[] = $entity;
        }
        return $entities;
    }
    public function index(): RedirectResponse|string
    {
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getGet());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            //일괄작업용 Fields정의
            $this->getService()->setControlDatas('batchjob_fields', $this->getService()->getBatchjobFields());
            //일괄작업용 버튼정의
            $this->getService()->setControlDatas('batchjob_buttions', $this->getService()->getBatchjobButtons());
            helper(['form']);
            //Return Url정의
            $this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
            //조건절 처리
            $this->index_condition_process();
            //TotalCount (SoftDelete적용이 되려면 countAllResults를 사용해야함)
            $this->total_count = $this->getService()->getTotalCount();
            //Pagination 처리
            $this->pagination = $this->index_pagenation_process();
            //줄수 처리용
            $this->page_options = $this->index_pageOptions_process();
            //조건절 처리
            //OrcerBy , Limit 처리
            $this->order_field = $this->request->getVar('order_field');
            $this->order_value = $this->request->getVar('order_value');
            $this->getService()->setOrderBy($this->order_field, $this->order_value);
            $this->getService()->setLimit($this->per_page);
            $this->getService()->setOffset(($this->page - 1) * $this->per_page);
            $this->index_condition_process();
            $this->entities = $this->index_process();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
    //OUPUT Document 관련
    protected function download_process(string $document_type, mixed $loaded_data): array
    {
        $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "excel";
        switch ($document_type) {
            case 'excel':
                $file_name = sprintf("%s_%s.xlsx", $this->getService()->getClassName(), date('Y-m-d_Hm'));
                $writer = IOFactory::createWriter($loaded_data, 'Xlsx');
                $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
                break;
            case 'pdf':
                $file_name = sprintf("%s_%s.pdf", $this->getService()->getClassName(), date('Y-m-d_Hm'));
                $writer = new Mpdf($loaded_data);
                $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
                break;
        }
        return array($full_path, $file_name);
    }
    // Download
    public function download(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse|string
    {
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getGet());
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            //URL처리
            // $this->uri = $this->request->getUri();
            switch ($output_type) {
                case 'excel':
                case 'pdf':
                    helper(['form']);
                    foreach ($this->getService()->getEntities() as $entity) {
                        $entities[] = $entity;
                    }
                    $this->entities = $entities;
                    $html = $this->getResultSuccess();
                    //data loading
                    $reader = new Html();
                    $loaded_data = $reader->loadFromString($html);
                    list($full_path, $file_name) = $this->download_process($output_type, $loaded_data);
                    $full_path .= DIRECTORY_SEPARATOR . $file_name;
                    break;
                default:
                    if (!$uid) {
                        throw new \Exception("{$output_type}은 반드시 uid의 값이 필요합니다.");
                    }
                    $entity = $this->getService()->getEntity($uid);
                    if (!$entity) {
                        throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
                    }
                    $this->entity = $entity;
                    list($file_name, $uploaded_filename) = $entity->getDownlaodFile();
                    $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $uploaded_filename;
                    break;
            }
            return $this->response->download($full_path, null)->setFileName($file_name);
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
}
