<?php

namespace KupShop\AdminBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\System\CurlUtil;

class CertManagerScript extends Script
{
    protected static $name = '[Bunny] - zapnutí DisableLetsEncrypt';
    protected static $defaultParameters = ['pullzoneID' => null, 'state' => true];

    public function run(array $arguments)
    {
        $curlutil = ServiceContainer::getService(CurlUtil::class);
        $client = $curlutil->getClient();

        if ($arguments['pullzoneID'] == null) {
            $response = $client->request('GET', 'https://api.bunny.net/pullzone?page=0&perPage=1000&includeCertificate=false', [
                'headers' => [
                    'AccessKey' => '1cfc3971-2fa2-4110-907a-43e6edf74e6cedbf97b2-bfb8-421c-8911-a2835f1837d2',
                    'accept' => 'application/json',
                ],
            ]);
            $data = json_decode($response->getContent(), true);
            foreach ($data as $item) {
                $this->letEncryptState($client, $item['Id'], $arguments['state']);
            }
        } else {
            $this->letEncryptState($client, $arguments['pullzoneID'], $arguments['state']);
        }

        return true;
    }

    private function letEncryptState($client, mixed $pullzoneID, mixed $state)
    {
        $response = $client->request('POST', 'https://api.bunny.net/pullzone/'.$pullzoneID, [
            'body' => json_encode(['DisableLetsEncrypt' => $state]),
            'headers' => [
                'AccessKey' => '1cfc3971-2fa2-4110-907a-43e6edf74e6cedbf97b2-bfb8-421c-8911-a2835f1837d2',
                'accept' => 'application/json',
                'content-type' => 'application/json',
            ],
        ]);
        $this->log('RUN SCRIPT - Pro e-shop s pullzoneID: '.$pullzoneID.' nastavuji DisableLetsEncrypt na '.$state);
    }
}

return CertManagerScript::class;
