<?php

namespace App\Controllers\Admin\Cloudflare\API;

use App\Models\Cloudflare\API\AccountModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class AccountController extends APIController
{
    private $_auth_uids = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_className .= '/Account';
        $this->_model = new AccountModel();
        $this->_defines = [
            'index' => [
                'fields' => ['auth_uid', 'title', 'type', 'status', 'updated_at', 'created_at'],
                'fieldFilters'  => ['auth_uid', 'type', 'status'],
                'batchjobFilters' => [],
            ],
            'excel' => [
                'fields' => ['auth_uid', 'title', 'type', 'status', 'updated_at', 'created_at'],
                'fieldFilters'  => ['auth_uid', 'type', 'status'],
            ],
        ];
        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 'auth_uid':
                if (is_null($this->_auth_uids)) {
                    //모든 필요한 FormOption등 조기화작업 필요
                    $this->_auth_uids = [DEFAULT_EMPTY => lang($this->_className . '.label.' . $field) . ' 선택'];
                    foreach ($this->getAuthModel()->orderBy('id', 'asc')->findAll() as $auth) {
                        $this->_auth_uids[$auth['uid']] = $auth['id'];
                    }
                }
                return $this->_auth_uids;
                break;
            default:
                return parent::getFieldFormOption($field);
                break;
        }
    }

    //Reload관련
    final public function reload($uid)
    {
        try {
            $entity = $this->_model->getEntity($uid);
            $zoneApi = new \App\Libraries\Cloudflare\API\Zone($entity);
            $zoneApi->reload();
            return alert_CommonHelper("{$this->_viewDatas['title']} " . __FUNCTION__ . " 완료하였습니다.", session()->get(RETURN_URL));
        } catch (\Exception $e) {
            return alert_CommonHelper($e->getMessage(), 'back');
        }
    }
}
