<?php

namespace App\Controllers\Admin\Cloudflare;

use App\Libraries\MyCloudflare\Record;
use App\Libraries\MyCloudflare\Zone;
use App\Models\Cloudflare\ZoneModel;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class ZoneController extends CloudflareController
{
    private $_myLibrary = null;
    private $_account_entity = null;
    private $_model = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->class_name = "Zone";
        $this->class_path .= $this->class_name;
        $this->title      = lang("{$this->class_path}.title");
        helper($this->class_path);
    }
    final protected function getModel(): ZoneModel
    {
        if ($this->_model === null) {
            $this->_model = new ZoneModel();
        }
        return $this->_model;
    }
    final protected function getMyLibrary(): Zone
    {
        if ($this->_myLibrary === null) {
            $this->_myLibrary = new Zone($this->_account_entity);
        }
        return $this->_myLibrary;
    }
    protected function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            case $this->getModel()::PARENT:
                $this->getAccountModel()->where('status', DEFAULTS['STATUS']);
                $options[$field] = [
                    DEFAULTS['EMPTY'] => lang($this->_className . '.label.' . $field) . ' 선택',
                    ...$this->getAccountModel()->getFormFieldOption($field, $options),
                ];
                break;
            default:
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    protected function getFormData(string $field, array $formDatas): array
    {
        switch ($field) {
            case 'domains':
                $formDatas[$field] = explode("\n", $this->request->getVar($field));
                if (!is_array($formDatas[$field]) || !count($formDatas[$field])) {
                    throw new \Exception("도메인명이 정의되지 않았습니다.");
                }
                break;
            case 'hosts':
                $formDatas[$field] = explode("\n", $this->request->getVar($field));
                if (!is_array($formDatas[$field]) || !count($formDatas[$field])) {
                    throw new \Exception("호스트명이 정의되지 않았습니다");
                }
                break;
            default:
                $formDatas = parent::getFormData($field, $formDatas);
                break;
        }
        return $formDatas;
    }
    protected function create_init(): void
    {
        $this->action        = 'create';
        $this->fields        = [$this->$this->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied'];
        $this->filter_fields = [$this->$this->getModel()::PARENT, 'type', 'proxied'];
        $this->field_rules   = $this->getModel()->getFieldRules($this->fields);
        $this->field_options = $this->getFormFieldOptions();
        $this->getModel()->setAction($this->action);
    }
    protected function create_validate(): void
    {
        //domains,hosts를 제외한 fields Valid처리
        $this->validateFormDatas(array_diff($this->fields, ['domains', 'hosts']));
    }
    protected function create_process(): void
    {
        $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]);
        if ($this->_account_entity === null) {
            throw new \Exception("해당 계정정보를 찾을수 없습니다.");
        }
        //Zone생성
        $zone_entitys = [];
        foreach ($this->formDatas['domains'] as $domain) {
            $zone_entitys[] = $this->getMyLibrary()->create($domain);
        }
        //Record생성
        foreach ($zone_entitys as $zone_entity) {
            $record = new Record($this->_account_entity, $zone_entity);
            foreach ($this->formDatas['hosts'] as $host) {
                $record->create($host, [
                    'type' => $this->formDatas['type'],
                    'content' => $this->formDatas['content'],
                    'proxied' => $this->formDatas['proxied'],
                ]);
            }
        }
    }
    //수정
    protected function modify_init(): void {}
    //  리스트
    public function list_init(): void
    {
        $this->action          = 'index';
        $this->fields          = [$this->getModel()::PARENT, $this->getModel()::TITLE, 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'created_at'];
        $this->filter_fields   = [$this->getModel()::PARENT, 'development_mode', 'ipv6', 'security_level', 'status'];
        $this->batchjob_fields = ['development_mode', 'ipv6', 'security_level'];
        $this->field_rules     = $this->getModel()->getFieldRules($this->fields);
        $this->field_options   = $this->getFormFieldOptions();
        $this->getModel()->setAction($this->action);
    }
}
