<?php

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

use ModulesGarden\ProxmoxAddon\App\Models\KeyPair;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Cloud\UserService;
use ModulesGarden\Servers\ProxmoxCloudVps\App\UI\Home\Pages\DetailsContainer;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\Http\AbstractClientController;
use ModulesGarden\Servers\ProxmoxCloudVps\Core\UI\Traits\WhmcsParams;
use Symfony\Component\HttpFoundation\StreamedResponse;


class SshKey extends AbstractClientController
{

    use WhmcsParams;
    use ProductService;
    use BaseClientController;
    use UserService;


    public function sshPublicKeyDownload()
    {
        $response = new StreamedResponse();
        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'application/x-pem-file; charset=utf-8');
        $response->headers->set('Content-Transfer-Encoding', 'Binary');
        $response->setCallback(function ()
        {
            /**
             * @var $keyPair KeyPair
             */
            $keyPair = KeyPair::ofHostingId($this->getWhmcsParamByKey("serviceid"))
                ->ofVmId($this->getRequestValue('vm'))
                ->firstOrFail();
            echo $keyPair->getPublic();
        });
        $response->headers->set(
            'Content-Disposition', 'attachment; filename="id_rsa.pub"'
        );
        $response->send();
    }

    public function sshPrivateKeyDownload()
    {
        $response = new StreamedResponse();
        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'application/x-pem-file; charset=utf-8');
        $response->headers->set('Content-Transfer-Encoding', 'Binary');
        $response->setCallback(function ()
        {
            /**
             * @var $keyPair KeyPair
             */
            $keyPair = KeyPair::ofHostingId($this->getWhmcsParamByKey("serviceid"))
                ->ofVmId($this->getRequestValue('vm'))
                ->firstOrFail();
            echo $keyPair->getPrivate();
            //delete private key
            if ($this->configuration()->isSshDeletePrivateKey())
            {
                $keyPair->setPrivate(null);
                $keyPair->save();
            }
        });
        $response->headers->set(
            'Content-Disposition', 'attachment; filename="id_rsa"'
        );
        $response->send();
    }
}
