<?php

namespace App\Controllers\CLI;

use App\Libraries\Cloudflare\Adapters\DdosAdapter;
use App\Libraries\Cloudflare\DdosLibrary;
use App\Libraries\Cloudflare\CloudflareLibrary;

use App\Models\Cloudflare\AccountModel;
use App\Entities\Cloudflare\AccountEntity;
use CodeIgniter\Controller;

class Cloudflare extends Controller
{
    public function __constract(){}
    final protected function getAuthKey(AccountEntity $account)
    {
        return new \Cloudflare\API\Auth\APIKey($account->id,$account->authkey);
    }
    
    public function executeddos(string $account_uid,int $page_limit=0){
        try {
            $accountModel = new AccountModel();
            $account = $accountModel->getEntity($account_uid);
            if(is_null($account)){
                echo __FUNCTION__." 해당하는 정보가 없습니다.";
                return false;
            }

            $adapter = new DdosAdapter($this->getAuthKey($account));
            $library = new DdosLibrary($adapter);
            $datas = $library->reload($page_limit);
            echo var_export($datas,true);
            CloudflareLibrary::save_logs("Cloudflare 전체 DDOS Reloading 작업 완료");            
            echo "완료";
        } catch(\Exception $e) {
            CloudflareLibrary::save_logs("Cloudflare 전체 DDOS Reloading 작업 오류\n".$e->getMessage());
            echo "오류\n".$e->getMessage();
        }
    }

    //전체 가져오기
    public function execute(int $page_limit=0)
    {
        try {
            CloudflareLibrary::add_logs("notice","Cloudflare 전체 Reloading 작업 시작");            
            //해당 Account별 Zone처리용
            $accountModel = new AccountModel();
            $accounts = $accountModel->asObject(AccountEntity::class)->where('status','use')->findAll();
            foreach($accounts as $account){ 
                $this->executezone($account->uid);
            }
            CloudflareLibrary::save_logs("Cloudflare 전체 Reloading 작업 완료");            
            echo "완료";
        } catch(\Exception $e) {
            CloudflareLibrary::save_logs("Cloudflare 전체 Reloading 작업 오류\n".$e->getMessage());
            echo "오류\n".$e->getMessage();
        }
    }
}
