<?php
/* * ********************************************************************
*  ProxmoxVPS Product developed. (27.03.19)
* *
*
*  CREATED BY MODULESGARDEN       ->       http://modulesgarden.com
*  CONTACT                        ->       contact@modulesgarden.com
*
*
* This software is furnished under a license and may be used and copied
* only  in  accordance  with  the  terms  of such  license and with the
* inclusion of the above copyright notice.  This software  or any other
* copies thereof may not be provided or otherwise made available to any
* other person.  No title to and  ownership of the  software is  hereby
* transferred.
*
*
* ******************************************************************** */

namespace ModulesGarden\Servers\ProxmoxVps\App\UI\BackupJob\Providers;

use MGProvision\Proxmox\v2\models\BackupSchedule;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use ModulesGarden\ProxmoxAddon\App\Enum\Vps\ConfigurableOption;
use function ModulesGarden\Servers\ProxmoxVps\Core\Helper\sl;

class BackupJobProvider extends BaseDataProvider implements ClientArea
{
    use ApiService;
    use ProductService;

    public function read()
    {
        if ($this->actionElementId)
        {
            $this->data = json_decode(base64_decode($this->actionElementId), true);
            $this->data['starttime'] == "" ?  : "off";
            //down
            $dow               = $this->data['dow'];
            $this->data['dow'] = explode(",", $dow);
            //mailto
            $mailto               = $this->data['mailto'];
            $this->data['mailto'] = $mailto ? "on" : "off";
        }
        $this->availableValues['compress'] = [
//            "0"    => sl("lang")->abtr("None"),
//            "lzo"  => sl("lang")->abtr("LZO (fast)"),
//            "gzip" => sl("lang")->abtr("GZIP (good)"),
            "zstd" => sl("lang")->abtr("ZSTD (fast and good)")
        ];
        $optionBackupCompress = $this->configuration()->getPermissionBackupCompress();
        if(empty($optionBackupCompress)){
            return;
        }
        foreach ($this->availableValues['compress'] as $k => $option){
            if($k=="0" && !in_array("none", $optionBackupCompress)){
                unset($this->availableValues['compress'][$k]);
            }
            if(!in_array($k, $optionBackupCompress)){
                unset($this->availableValues['compress'][$k]);
            }
        }
    }

    public function create()
    {
        $this->acl()->backupJob();
        $this->resourceGuard()->backupJobLimit();
        $storage        = $this->configuration()->getBackupStorage();
        $routing        = $this->configuration()->isBackupRouting() ? 1 : 0;
        $maxFiles       =  $this->configuration()->getBackupMaxFiles();
        if($this->isWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES) &&  $this->getWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES)!="-1"){
            $maxFiles       = $this->getWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES);
        }else if($this->getWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES)=="-1"){
            $maxFiles       = null;
        }
        $backupSchedule = new BackupSchedule();
        $backupSchedule->setApi($this->api());
        $backupSchedule->setAttributes([
            "vmid"      => $this->vm()->getVmid(),
            "storage"   => $storage,
            "remove"    => $routing,
            "maxfiles"  => $maxFiles,
            "starttime" => $this->formData['starttime'],
            "dow"       => implode(",", $this->formData['dow']),
            "mode"      => $this->formData['mode'],
            "compress"  => $this->formData['compress'],
            "mailto"    => $this->formData['mailto'] == "on" ? $this->getWhmcsParamByKey('clientsdetails')['email'] : null,
        ]);
        $backupSchedule->create();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The backup job has been created successfully')
            ->setRefreshTargetIds(['dackupJobDataTable'])
            ->addData('createButtonStatus', $this->resourceGuard()->hasBackupJobLimit())
            ->setCallBackFunction('toggleBackupButton');
    }

    public function update()
    {
        $this->acl()->backupJob();
        $storage        = $this->configuration()->getBackupStorage();
        $routing        = $this->configuration()->isBackupRouting() ? 1 : 0;
        $maxFiles       =  $this->configuration()->getBackupMaxFiles();
        if($this->isWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES) &&  $this->getWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES)!="-1"){
            $maxFiles       = $this->getWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES);
        }else if($this->getWhmcsConfigOption(ConfigurableOption::BACKUPS_FILES)=="-1"){
            $maxFiles       = null;
        }
        $backupSchedule = new BackupSchedule();
        $backupSchedule->setApi($this->api());
        $backupSchedule->setAttributes([
            "id"        => $this->formData['backupScheduleId'],
            "vmid"      => $this->vm()->getVmid(),
            "storage"   => $storage,
            "remove"    => $routing,
            "maxfiles"  => $maxFiles,
            "starttime" => $this->formData['starttime'],
            "dow"       => implode(",", $this->formData['dow']),
            "mode"      => $this->formData['mode'],
            "compress"  => $this->formData['compress'],
            "mailto"    => $this->formData['mailto'] == "on" ? $this->getWhmcsParamByKey('clientsdetails')['email'] : null,
        ]);
        $backupSchedule->update();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The backup job has been updated successfully');
    }

    public function delete()
    {
        $this->acl()->backupJob();
        $backupSchedule = new BackupSchedule();
        $backupSchedule->setApi($this->api());
        $backupSchedule->setId($this->formData['backupScheduleId']);
        $backupSchedule->delete();
        return (new HtmlDataJsonResponse())
            ->setStatusSuccess()
            ->setMessageAndTranslate('The backup job has been deleted successfully')
            ->setRefreshTargetIds(['dackupJobDataTable'])
            ->addData('createButtonStatus', 1)
            ->setCallBackFunction('toggleBackupButton');
    }


}