<?php

namespace App\Controllers\Admin;

use App\Models\MapurlModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class MapurlController extends \App\Controllers\Admin\AdminController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_className .= '/Mapurl';
        $this->_model = new MapurlModel();
        $this->_defines = [
            'insert' => [
                'fields' => ['oldurl', 'newurl', 'status'],
                'fieldFilters'  => ['status'],
                'fieldRules' => [
                    'oldurl'            => 'required|valid_url_strict|is_unique[mapurl.oldurl]',
                    'newurl'            => 'required|valid_url_strict',
                    'status'            => 'required|in_list[use,unuse]',
                ]
            ],
            'update' => [
                'fields' => ['oldurl', 'newurl', 'status'],
                'fieldFilters'  => ['status'],
                'fieldRules' => [
                    'oldurl'            => 'required|valid_url_strict',
                    'newurl'            => 'required|valid_url_strict',
                    'status'            => 'required|in_list[use,unuse]',
                ]
            ],
            'view' => [
                'fields' => ['oldurl', 'newurl', 'status', 'updated_at', 'created_at'],
                'fieldFilters'  => ['status'],
                'fieldRules' => [],
            ],
            'index' => [
                'fields' => ['oldurl', 'newurl', 'status', 'updated_at', 'created_at'],
                'fieldFilters'  => ['status'],
                'batchjobFilters' => ['newurl', 'status'],
            ],
            'excel' => [
                'fields' => ['oldurl', 'newurl', 'status', 'updated_at', 'created_at'],
                'fieldFilters'  => ['status'],
            ],
        ];
        helper($this->_className);
        $this->_viewPath = strtolower($this->_className);
        $this->_viewDatas['title'] = lang($this->_className . '.title');
        $this->_viewDatas['className'] = $this->_className;
    }

    private function remapurl()
    {
        //모든 필요한 FormOption등 조기화작업 필요
        $rows = $this->_model->where('status', 'use')->orderBy('oldurl', 'asc')->findAll();
        //html의 case문 설정
        $urls = array("");
        foreach ($rows as $row) {
            $temp_oldurl = sprintf("case '%s':", trim($row['oldurl']));
            //한글을 포함하고 있는지 체크
            if (preg_match("/[\xE0-\xFF][\x80-\xFF][\x80-\xFF]/", $row['oldurl'])) {
                //도메인 URL 분리
                preg_match("/^(https?:\/\/)(.*)/", $row['oldurl'], $matches);
                $temp_oldurl = sprintf("case '%s%s':\ncase '%s':", $matches[1], idn_to_ascii($matches[2]), trim($row['oldurl']));
            }
            array_push($urls, sprintf("\t\t\t%s\n \t\t\twindow.location.href='%s';\n \t\tbreak;", $temp_oldurl, trim($row['newurl'])));
        }
        $remapPage = view($this->_viewPath . '/' . __FUNCTION__, array("urls" => $urls));

        //디렉토리 생성 여부 확인
        $path = 'mapurl';
        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }
        //htmlBuild용

        if (!file_put_contents($path . '/index.html', $remapPage)) {
            throw new \Exception(__FUNCTION__ . "에서 " . $path . "/index.html Write 실패");
        }
    }

    //Insert관련
    protected function insert_process()
    {
        parent::insert_process();
        $this->remapurl(); //MapURL용 index.html 생성
    }
    //Update관련
    protected function update_process($entity)
    {
        $entity = parent::update_process($entity);
        $this->remapurl(); //MapURL용 index.html 생성
        return $entity;
    }
    //Toggle관련
    protected function toggle_process($entity)
    {
        $entity = parent::toggle_process($entity);
        $this->remapurl(); //MapURL용 index.html 생성
        return $entity;
    }
    //Batchjob관련
    protected function batchjob_process($entity)
    {
        $entity = parent::batchjob_process($entity);
        $this->remapurl(); //MapURL용 index.html 생성
        return $entity;
    }
    //Delete관련
    protected function delete_process($entity)
    {
        $entity = parent::delete_process($entity);
        $this->remapurl(); //MapURL용 index.html 생성
    }
}
