<?php

namespace App\Controllers\Admin\Cloudflare\API;

use App\Entities\Cloudflare\API\FirewallEntity;
use App\Models\Cloudflare\API\FirewallModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Libraries\Cloudflare\API\Firewall;

class FirewallController extends APIController
{
    private $_zone_uids = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_className .= '/Firewall';
        $this->_model = new FirewallModel();
        $this->_defines = [
            'index' => [
                'fields' => ['zone_uid', 'description', 'action', 'paused', 'updated_at', 'created_at'],
                'fieldFilters'  => ['zone_uid', 'action', 'paused'],
                'batchjobFilters' => ['action', 'paused'],
            ],
            'excel' => [
                'fields' => ['zone_uid', 'description', 'action', 'paused', 'updated_at', 'created_at'],
                'fieldFilters'  => ['zone_uid', 'action', 'paused',],
            ],
        ];
        helper($this->_className);
        $this->_viewPath = strtolower($this->_className);
        $this->_viewDatas['title'] = lang($this->_className . '.title');
        $this->_viewDatas['className'] = $this->_className;
    }

    //Field별 Form Option용
    protected function getFieldFormOption(string $field): array
    {
        switch ($field) {
            case 'zone_uid':
                if (is_null($this->_zone_uids)) {
                    //모든 필요한 FormOption등 조기화작업 필요
                    $this->_zone_uids = [DEFAULT_EMPTY => lang($this->_className . '.label.' . $field) . ' 선택'];
                    foreach ($this->getZoneModel()->orderBy('domain', 'asc')->findAll() as $zone) {
                        $this->_zone_uids[$zone['uid']] = $zone['domain'];
                    }
                }
                return $this->_zone_uids;
                break;
            default:
                return parent::getFieldFormOption($field);
                break;
        }
    }

    //Update관련
    protected function update_process($entity)
    {
        $api = new Firewall($this->getZoneModel()->getEntity($entity->getParentFieldData()));
        $entity = $api->update($entity, $this->_viewDatas['fieldDatas']);
        return parent::update_process($entity);
    }
    //Toggle관련
    protected function toggle_process($entity)
    {
        $api = new Firewall($this->getZoneModel()->getEntity($entity->getParentFieldData()));
        $entity = $api->update($entity, $this->_viewDatas['fieldDatas']);
        return parent::toggle_process($entity);
    }
    //Batchjob관련
    protected function batchjob_process($entity)
    {
        $api = new Firewall($this->getZoneModel()->getEntity($entity->getParentFieldData()));
        $entity = $api->update($entity, $this->_viewDatas['fieldDatas']);
        return parent::batchjob_process($entity);
    }
    //Index관련
    private function index_setCondition_builder($builder)
    {
        foreach ($this->_viewDatas['fieldFilters'] as $field) {
            $value = $this->request->getVar($field) ? $this->request->getVar($field) : false;
            if ($value) {
                $builder->where("cloudflarefirewall.{$field}", $value);
            }
        }
        $word = $this->request->getVar('word') ? $this->request->getVar('word') : '';
        if (isset($word) && $word !== '') {
            $builder->like('cloudflarefirewall.description', $word, 'both'); //befor , after , both
        }
        $start = $this->request->getVar('start') ? $this->request->getVar('start') : '';
        $end = $this->request->getVar('end') ? $this->request->getVar('end') : '';
        if (isset($start) && $start !== '' && isset($end) && $end !== '') {
            $builder->where('cloudflarefirewall.created_at >=', $start);
            $builder->where('cloudflarefirewall.created_at <=', $end);
        }
        return $builder;
    }
    private function index_getRows_builder(int $page = 0, int $per_page = 0): array
    {
        //Totalcount 처리
        $builder = $this->_model->builder();
        $builder->select("cloudflarefirewall.*");
        $builder->join("cloudflarezone", "cloudflarezone.uid = cloudflarefirewall.zone_uid");
        $builder = $this->index_setCondition_builder($builder);
        // log_message("debug", __METHOD__ . "에서 호출\n" . $builder->getCompiledSelect(false));
        $this->_viewDatas['total_count'] = $builder->countAllResults();
        //Rows 처리
        $builder = $this->_model->builder();
        $builder->select("cloudflarefirewall.*");
        $builder->join("cloudflarezone", "cloudflarezone.uid = cloudflarefirewall.zone_uid");
        $builder = $this->index_setCondition_builder($builder);
        //OrderBy
        $order_field = $this->request->getVar('order_field') ? $this->request->getVar('order_field') : 'uid';
        $order_value = $this->request->getVar('order_value') ? $this->request->getVar('order_value') : 'DESC';
        $builder->orderBy("cloudflarezone.domain ASC, cloudflarefirewall.description ASC, cloudflarefirewall.{$order_field} {$order_value}");
        //Limit
        $builder->limit($per_page, $page * $per_page - $per_page);
        // log_message("debug", __METHOD__ . "에서 호출\n" . $builder->getCompiledSelect(false));

        return $builder->get()->getResultArray();
    }
    protected function index_getRows(int $page = 0, int $per_page = 0): array
    {
        return $this->index_getRows_builder($page, $per_page);
    }

    ////Action 모음
    //Insert관련
    // final public function insert()
    // {
    //     return $this->insert_procedure();
    // }
    //Update관련
    // final public function update($uid)
    // {
    //     return $this->update_procedure($uid);
    // }
    //Toggle관련
    final public function toggle($uid, string $field)
    {
        return $this->toggle_procedure($uid, $field);
    }
    //Batchjob 관련
    final public function batchjob()
    {
        return $this->batchjob_procedure();
    }
    //Delete 관련
    // final public function delete($uid)
    // {
    //     return $this->delete_procedure($uid);
    // }
    //View 관련
    // final public function view($uid)
    // {
    //     return $this->view_procedure($uid);
    // }
    //Index 관련
    final public function index()
    {
        return $this->index_procedure();
    }
    //Excel 관련
    final public function excel()
    {
        return $this->excel_procedure();
    }
    ////API Action
    //Sync관련
    protected function sync_process($entity)
    {
        $api = new Firewall($this->getZoneModel()->getEntity($entity->getParentFieldData()));
        $entity = $api->sync($entity);
        return parent::sync_process($entity);
    }
    final public function sync($uid)
    {
        return $this->sync_procedure($uid);
    }
    ////추가 Action
}
