<?php

namespace ModulesGarden\Servers\ProxmoxVps\App\Http\Client;

use MGProvision\Proxmox\v2\repository\FirewallRulesRepository;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\Servers\ProxmoxVps\App\Helpers\AppParams;
use ModulesGarden\Servers\ProxmoxVps\App\UI\Firewall\Pages\FirewallDataTable;
use ModulesGarden\Servers\ProxmoxVps\Core\Helper;
use ModulesGarden\Servers\ProxmoxVps\Core\Http\AbstractClientController;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Traits\WhmcsParams;
use Symfony\Component\HttpFoundation\StreamedResponse;

class Firewall extends AbstractClientController
{
    use WhmcsParams;
    use ProductService;
    use ApiService;

    public function index()
    {
        (new AppParams())->initFromWhmcsParams();
        $this->acl()->firewall();
        Helper\sl("sidebar")->getSidebar("managementProxmoxVps")->getChild("firewall")->setActive(true);
        return Helper\view()->addElement(FirewallDataTable::class);
    }

    public function download()
    {
        $response = new StreamedResponse();
        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'application/json; charset=utf-8');
        $response->headers->set('Content-Transfer-Encoding', 'Binary');
        $filename = sprintf("%s-firewal-rules.json",$this->getWhmcsParamByKey("domain"));
        $response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"');
        $firewalRules = new FirewallRulesRepository();
        $firewalRules->setApi($this->api());
        $firewalRules->findByVm($this->vm());
        $response->setCallback(function () use( $firewalRules)
        {
            echo  \json_encode($firewalRules->fetchAsArray());
            die();
        });
        $response->send();
    }
}
