<?php

namespace App\Controllers\CLI\Cloudflare\API;

use App\Entities\Cloudflare\API\ZoneEntity;
use App\Libraries\Log\Log;

class Zone extends API
{
    private function getZones(string $account_uid): array
    {
        if ($account_uid) {
            $entitys = $this->getZoneModel()->asObject(ZoneEntity::class)
                ->where(['status' => 'active', 'account_uid' => $account_uid])
                ->findAll();
        } else {
            $entitys = $this->getZoneModel()->asObject(ZoneEntity::class)
                ->where('status', 'active')
                ->findAll();
        }
        Log::add("error", __FUNCTION__ . "에서 호출:" . $this->getZoneModel()->getLastQuery());
        return $entitys;
    }
    final public function record(int $page_limit = 0, string $account_uid = '')
    {
        try {
            //transation처리
            // $this->getZoneModel()->db->transBegin();
            //Record
            echo __METHOD__ . "에서 Record Reload 시작\n";
            foreach ($this->getZones($account_uid) as $entity) {
                $api = new \App\Libraries\Cloudflare\API\Record($entity);
                $api->reload((int)$page_limit);
            }
            //CDN값 수정 못하는 고정 Record 처리
            $fixedRecordModel = new \App\Models\Cloudflare\API\FixedRecordModel();
            $this->getRecordModel()->setFixedCDNRecord($fixedRecordModel->findColumn("host"));
            echo __METHOD__ . "에서 Record Reload 완료\n";
            //transation 완료
            // $this->getZoneModel()->db->transCommit();
        } catch (\Exception $e) {
            //transaction 오류복구
            // $this->getZoneModel()->db->transRollback();
            $message = __METHOD__ . "에서 Record Reload 오류\n" . $e->getMessage();
            log_message("error", $message);
            echo $message;
        }
    }
    final public function firewall(int $page_limit = 0, string $account_uid = '')
    {
        try {
            //transation처리
            // $this->getZoneModel()->db->transBegin();
            //Firewall
            echo __METHOD__ . "에서 Firewall Reload 시작\n";
            foreach ($this->getZones($account_uid) as $entity) {
                $api = new \App\Libraries\Cloudflare\API\Firewall($entity);
                $api->reload((int)$page_limit);
            }
            echo __METHOD__ . "에서 Firewall Reload 완료\n";
            //transation 완료
            // $this->getZoneModel()->db->transCommit();
        } catch (\Exception $e) {
            //transaction 오류복구
            // $this->getZoneModel()->db->transRollback();
            $message = __METHOD__ . "에서 Firewall Reload 오류\n" . $e->getMessage();
            log_message("error", $message);
            echo $message;
        }
    }
}
