<?php

namespace App\Controllers\Admin\Cloudflare\API;

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

class AuthController extends APIController
{
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_className .= '/Auth';
        $this->_model = new AuthModel();
        $this->_defines = [
            'insert' => [
                'fields' => ['id', 'authkey', 'status'],
                'fieldFilters'  => ['status'],
                'fieldRules' => [
                    'id'                => 'required|valid_email|is_unique[auth.id]',
                    'authkey'           => 'required|min_length[10]|max_length[200]',
                    'status'            => 'required|in_list[use,unuse]',
                ],
            ],
            'update' => [
                'fields' => ['id', 'authkey', 'status'],
                'fieldFilters'  => ['status'],
                'fieldRules' => [
                    'id'                => 'required|valid_email',
                    'authkey'           => 'required|min_length[10]|max_length[200]',
                    'status'            => 'required|in_list[use,unuse]',
                ],
            ],
            'view' => [
                'fields' => ['id', 'authkey', 'oldkey', 'status', 'updated_at', 'created_at'],
                'fieldFilters'  => ['status'],
                'fieldRules' => [],
            ],
            'index' => [
                'fields' => ['id', 'oldkey', 'status', 'updated_at', 'created_at'],
                'fieldFilters'  => ['status'],
                'batchjobFilters' => ['status'],
            ],
            'excel' => [
                'fields' => ['id', 'oldkey', '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;
    }

    //Insert관련
    protected function insert_process()
    {
        //oldkey임시생성
        $this->_viewDatas['fieldDatas']['oldkey'] = uniqid();
        return parent::insert_process();
    }
    //Update관련
    protected function update_process($entity)
    {
        //기존 AuthKey를 OldKey로 백업
        $entity->oldkey = $entity->authkey;
        //Auth에 속해있는 Account의 상태 Syn작업
        $this->getAccountModel()->setStatusByAuth($entity->getPrimaryKey(), $this->_viewDatas['fieldDatas']['status']);
        return parent::update_process($entity);
    }
    //Toggle 관련
    protected function toggle_process($entity)
    {
        //Auth에 속해있는 Account의 상태 Syn작업
        $this->getAccountModel()->setStatusByAuth($entity->getPrimaryKey(), $this->_viewDatas['fieldDatas']['status']);
        return parent::toggle_process($entity);
    }
    //Batchjob 관련
    protected function batchjob_process($entity)
    {
        //Auth에 속해있는 Account의 상태 Syn작업
        $this->getAccountModel()->setStatusByAuth($entity->getPrimaryKey(), $this->_viewDatas['fieldDatas']['status']);
        return parent::batchjob_process($entity);
    }
    //Reload관련
    final public function reload($uid)
    {
        try {
            $entity = $this->_model->getEntity($uid);
            $accountApi = new \App\Libraries\Cloudflare\API\Account($entity);
            $accountApi->reload();
            return alert_CommonHelper("{$this->_viewDatas['title']} " . __FUNCTION__ . " 완료하였습니다.", session()->get(RETURN_URL));
        } catch (\Exception $e) {
            return alert_CommonHelper($e->getMessage(), 'back');
        }
    }
}
