<?php
/**********************************************************************
 * ProxmoxVPS developed. (26.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\Http\Actions;


use MGProvision\Proxmox\v2\models\Lxc;
use MGProvision\Proxmox\v2\repository\BackupScheduleRepository;
use MGProvision\Proxmox\v2\repository\FileRepository;
use MGProvision\Proxmox\v2\repository\FirewallRulesRepository;
use ModulesGarden\ProxmoxAddon\App\Models\KeyPair;
use ModulesGarden\ProxmoxAddon\App\Models\SnapshotJob;
use ModulesGarden\ProxmoxAddon\App\Models\TaskHistory;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HighAvailabilityClusterService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\HostingService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\NetworkService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\ProductService;
use ModulesGarden\ProxmoxAddon\App\Services\Vps\UserService;
use ModulesGarden\ProxmoxAddon\App\Traits\Vps\SnippetTrait;
use ModulesGarden\ProxmoxAddon\Core\Models\ModuleSettings\Model as ModuleSettings;
use ModulesGarden\ProxmoxAddon\Core\Queue\Models\Job;
use ModulesGarden\Servers\ProxmoxVps\App\Helpers\AppParams;
use ModulesGarden\Servers\ProxmoxVps\App\Helpers\ProxmoxAddonValidator;
use ModulesGarden\Servers\ProxmoxVps\Core\App\Controllers\Instances\AddonController;
use ModulesGarden\Servers\ProxmoxVps\Core\UI\Traits\WhmcsParams;

class TerminateAccount extends AddonController
{
    use WhmcsParams;
    use ProductService;
    use ApiService;
    use UserService;
    use HostingService;
    use SnippetTrait;
    /**
     * @var HighAvailabilityClusterService
     */
    private $highAvailabilityClusterService;

    public function __construct()
    {
        $this->highAvailabilityClusterService = new HighAvailabilityClusterService();
    }

    public function execute($params = null)
    {
        if(!ProxmoxAddonValidator::isInstalled()){
            return ProxmoxAddonValidator::failAsString();
        }
        (new AppParams())->initFromWhmcsParams();
        try
        {
            if (!$this->getWhmcsParamByKey('serviceid'))
            {
                throw new \InvalidArgumentException("The Service Id cannot be empty");
            }
            //Cron delete active jobs
            Job::whereIn("status", ['waiting', "running", "", "error"])
                ->where("rel_id", $this->getWhmcsParamByKey("serviceid"))
                ->where("rel_type", "hosting")
                ->update(["status" => 'cancelled']);
            //snapshot jobs
            SnapshotJob::ofHostingId($this->getWhmcsParamByKey("serviceid"))->delete();
            //User delete
            if ($this->isUser())
            {
                $this->deleteUser();
            }
            //Unassing IP
            $networkService = new NetworkService();
            $networkService->deleteIpAddresses();
            //vmid validation
            if (!$this->getWhmcsParamByKey('customfields')['vmid'])
            {
                throw new \InvalidArgumentException("Custom Field \"VMID\" cannot be empty");
            }
            //node
            if (!$this->getWhmcsParamByKey('customfields')['node'])
            {
                throw new \InvalidArgumentException("Custom Field \"VMID\" cannot be empty");
            }
            //Delete HA
            if ($this->highAvailabilityClusterService->exist())
            {
                $this->highAvailabilityClusterService->delete();
            }
            //Stop VM
            if ($this->vm()->isRunning())
            {
                $this->vm()->stop();
                sleep(4);
            }
            //VM Protection LXC
            if ($this->vm() instanceof Lxc && $this->vm()->config()['protection'] == "1")
            {
                $this->vm()->protectionOff();
                KeyPair::ofHostingId($this->getWhmcsParamByKey("serviceid"))->delete();

            }
            //Destroy firewall rules
            if (version_compare($this->api()->getVersion(), "3.2", '>'))
            {
                $rules = new FirewallRulesRepository();
                $rules->findByVm($this->vm())
                    ->delete();
            }
            //Destroy Backups
            if ($this->configuration()->isDeleteBackups())
            {
                $storage        = $this->configuration()->getBackupStorage() ? $this->configuration()->getBackupStorage() : 'local';
                $fileRepository = new FileRepository();
                $fileRepository->findBackup($this->vm())
                    ->findByStorages([$storage])
                    ->delete();
            }
            //Destroy Backup Jobs
            $schedule = new BackupScheduleRepository();
            $schedule->findByVm($this->vm());
            $schedule->delete();
            //Destroy VM
            $upid = $this->vm()->delete();
            //Create Task History
            $type = str_replace(["qemu", "lxc"], ["VM", "CT"], $this->vm()->getVirtualization());
            $task = new TaskHistory();
            $task->fill([
                'hosting_id' => $this->getWhmcsParamByKey("serviceid"),
                'upid'       => $upid,
                'name'       => sprintf("%s %s - %s", $type, $this->vm()->getVmid(), "Delete"),
                'vmid'       => $this->vm()->getVmid(),
                'node'       => $this->vm()->getNode(),
                'status'     => 0
            ])->save();
            //snippets
            if($this->hasSnippet() && $snippet = $this->getSnippetFile()){
                $snippet->delete();
            }
            //Reset Custom Fields
            $this->customFieldUpdate("vmid", "");
            $this->customFieldUpdate("node", "");
            //Reset VLAN Tag
            if ($this->getWhmcsParamByKey('customfields')['VLAN Tag'])
            {
                $this->customFieldUpdate("VLAN Tag", "");
            }
            //Cache
            $serviceId = $this->getWhmcsParamByKey('serviceid');
            ModuleSettings::where('setting', "LIKE", "%{$serviceId}_cacheData%")->delete();
            return "success";
        }
        catch (\Exception $ex)
        {
            if (\ModulesGarden\ProxmoxAddon\App\Models\ModuleSettings::isDebug())
            {
                logModuleCall(
                    'ProxmoxVps',
                    __CLASS__,
                    [],
                    null,
                    $ex->getMessage() . " " . $ex->getTraceAsString()
                );
            }
            return $ex->getMessage();
        }
    }
}