<?php

namespace App\Controllers\Admin\Cloudflare\API;

use App\Libraries\Log\Log;
use App\Models\Cloudflare\API\AccountModel;
use App\Models\Cloudflare\API\AuthModel;
use App\Models\Cloudflare\API\ZoneModel;
use App\Models\Cloudflare\API\RecordModel;

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

class APIController extends \App\Controllers\Admin\Cloudflare\CloudflareController
{
    private $_authModel = null;
    private $_accountModel = null;
    private $_zoneModel = null;
    private $_recordModel = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_className .= '/API';
        $this->_viewPath = strtolower($this->_className);
    }
    final protected function getAuthModel(): AuthModel
    {
        return is_null($this->_authModel) ? new AuthModel() : $this->_authModel;
    }
    final protected function getAccountModel(): AccountModel
    {
        return is_null($this->_accountModel) ? new AccountModel() : $this->_accountModel;
    }
    final protected function getZoneModel(): ZoneModel
    {
        return is_null($this->_zoneModel) ? new ZoneModel() : $this->_zoneModel;
    }
    final protected function getRecordModel(): RecordModel
    {
        return is_null($this->_recordModel) ? new RecordModel() : $this->_recordModel;
    }

    //Zone입력
    final protected function insert_Zone(
        \App\Entities\Cloudflare\API\AccountEntity $account,
        string $domain
    ): \App\Entities\Cloudflare\API\ZoneEntity {
        $fieldDatas = array('account_uid' => $account->getPrimaryKey(), 'domain' => $domain);
        $api = new \App\Libraries\Cloudflare\API\Zone($account);
        $zone = $api->insert($fieldDatas);
        if (!$this->getZoneModel()->save($zone)) {
            Log::add("error", __FUNCTION__ . "에서 호출:" . $this->getZoneModel()->getLastQuery());
            Log::add("error", implode("\n", $this->getZoneModel()->errors()));
            throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->getZoneModel()->errors(), true));
        }
        Log::add("info", "Zone: {$zone->getTitle()} 등록");
        return $zone;
    }
    //Record입력
    final protected function insert_Host(
        \App\Entities\Cloudflare\API\ZoneEntity $zone,
        string $host,
        string $type,
        string $content,
        string $proxied
    ): \App\Entities\Cloudflare\API\RecordEntity {
        $fieldDatas = array('zone_uid' => $zone->getPrimaryKey(), 'host' => $host);
        $fieldDatas['type'] = $type;
        $fieldDatas['content'] = $content;
        $fieldDatas['proxied'] = $proxied;

        $api = new \App\Libraries\Cloudflare\API\Record($zone);
        $record = $api->insert($fieldDatas);
        $record->fixed = 'off'; //초기값
        if (!$this->getRecordModel()->save($record)) {
            Log::add("error", __FUNCTION__ . "에서 호출:" . $this->getRecordModel()->getLastQuery());
            Log::add("error", implode("\n", $this->getRecordModel()->errors()));
            throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->getRecordModel()->errors(), true));
        }
        Log::add("info", "Host: {$record->getTitle()} 등록");
        return $record;
    }

    //Sync관련
    protected function sync_process($entity)
    {
        return $entity;
    }
    final public function sync($uid)
    {
        try {
            $entity = $this->_model->getEntity($uid);
            $entity = $this->sync_process($entity);
            return alert_CommonHelper("{$this->_viewDatas['title']} " . __FUNCTION__ . " 완료하였습니다.", session()->get(RETURN_URL));
        } catch (\Exception $e) {
            return alert_CommonHelper($e->getMessage(), 'back');
        }
    }
}
