<?php

namespace App\Services;

class VmwareClient
{
    private $username;
    private $password;
    private $esxiUrl;
    private $sessionId;

    public function __construct()
    {
        $this->username = env('VMWARE_USERNAME');
        $this->password = env('VMWARE_PASSWORD');
        $this->esxiUrl  = env('VMWARE_ESXI_URL');
        $this->sessionId = $this->getSessionId();
    }

    private function getSessionId()
    {
        $url = $this->esxiUrl . '/rest/com/vmware/cis/session';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, "{$this->username}:{$this->password}");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true)['value'] ?? null;
    }

    public function getVM($domain)
    {
        $url = $this->esxiUrl . '/rest/vcenter/vm';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "vmware-api-session-id: {$this->sessionId}",
            "Accept: application/json"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        $vms = json_decode($response, true)['value'] ?? [];

        foreach ($vms as $vm) {
            if ($vm['name'] === $domain) {
                return $vm;
            }
        }
        return null;
    }

    public function getVMStatus($vmId)
    {
        $url = $this->esxiUrl . "/rest/vcenter/vm/$vmId/power";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "vmware-api-session-id: {$this->sessionId}",
            "Accept: application/json"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true)['value']['state'] ?? 'UNKNOWN';
    }

    public function manageVM($vmId, $action) {
        $url = $this->esxiUrl . "/rest/vcenter/vm/{$vmId}/power/{$action}";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "vmware-api-session-id: {$this->sessionId}"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $messages = [
            'start' => 'Cihaz başarıyla başlatıldı.',
            'stop' => 'Cihaz başarıyla kapatıldı.',
            'reset' => 'Cihaz başarıyla yeniden başlatıldı.',
        ];

        if ($httpCode == 200 || $httpCode == 204) {
            return $messages[$action] ?? "✅ VM '$action' işlemi başarıyla tamamlandı.";
        } else {
            return "❌ Hata! HTTP Kod: $httpCode\nYanıt: $response";
        }
    }

    public function getConsoleTicket($vmId)
    {
        $url = $this->esxiUrl . "/rest/vcenter/vm/{$vmId}/console/tickets";

        $body = json_encode([
            "spec" => [
                "type" => "WEBMKS"
            ]
        ]);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "vmware-api-session-id: {$this->sessionId}",
            "Content-Type: application/json"
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return json_decode($response, true)['value'] ?? null;
    }
}
