<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Services\VmwareClient;
use App\Services\WhmcsService;
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Carbon\Carbon;

class VmwareController extends Controller
{
    protected $whmcs;
    protected $authController;

    public function __construct(WhmcsService $whmcs, AuthController $authController)
    {
        $this->whmcs = $whmcs;
        $this->authController = $authController;
    }

    public function getVmInfo($domain)
    {
        $vmware = new VmwareClient();
        $vm = $vmware->getVM($domain);

        if (!$vm) {
            return response()->json(['error' => 'Bu sanal makine bulunamadı.'], 404);
        }

        return response()->json($vm);
    }

    public function getVmStatus($id)
    {
        $vmware = new VmwareClient();
        $status = $vmware->getVMStatus($id);

        return response()->json(['status' => $status]);
    }

    public function manageVm($id, $action)
    {
        $vmware = new VmwareClient();
        $result = $vmware->manageVM($id, $action);

        return response()->json(['result' => $result]);
    }

    public function getConsoleTicket($id)
    {
        $vmware = new VmwareClient();
        $ticket = $vmware->getConsoleTicket($id);

        return response()->json(['ticket' => $ticket]);
    }

    public function verifyvm(Request $request)
    {
        $clientId = Session::get('client');
        if (!$clientId) {
            return response()->json(['status' => 'error', 'message' => 'Oturum bulunamadı.']);
        }

        $clientDetails = $this->whmcs->getClientDetails($clientId);

        if (!$clientDetails || empty($clientDetails['phonenumber'])) {
            return response()->json(['status' => 'error', 'message' => 'Telefon numarası bulunamadı.']);
        }

        $ad = $clientDetails['firstname'] ?? '';
        $soyad = $clientDetails['lastname'] ?? '';

        try {
            $this->authController->sendVerificationSms($clientDetails['phonenumber'], $clientId, $ad, $soyad);
            return response()->json(['status' => 'success', 'message' => 'SMS gönderildi.']);
        } catch (\Exception $e) {
            return response()->json(['status' => 'error', 'message' => 'SMS gönderilirken hata oluştu.']);
        }
    }

    public function consoleCreate(Request $request)
   {
       $clientId = Session::get('client');
       $verifyCode = $request->input('code');
       $storedCode = Session::get("verification_code_{$clientId}");

       if ($storedCode && $storedCode == $verifyCode) {

           Session::forget("verification_code_{$clientId}");
           Session::forget('verification_sent');

           $vmDomain = $request->input('vmname');
           if (!$vmDomain) {
               return response()->json(['status' => 'error', 'message' => 'Bu sanal makine adı eksik.']);
           }

           $vmProduct = DB::table('tblhosting')
               ->where('domain', $vmDomain)
               ->where('userid', $clientId)
               ->first();

           if (!$vmProduct) {
               return response()->json(['status' => 'error', 'message' => 'Bu sanal makine size ait değil.']);
           }

           $vmware = new VmwareClient();
           $vmInfo = $vmware->getVM($vmDomain);

           if (!$vmInfo || empty($vmInfo['vm'])) {
               return response()->json(['status' => 'error', 'message' => 'Bu sanal makine bulunamadı.']);
           }

           $autokey = Str::random(32);
           $start = Carbon::now();
           $end = $start->copy()->addMinutes(30);

           DB::table('console_links')->insert([
               'user_id' => $clientId,
               'vm_id' => $vmInfo['vm'],
               'hostname' => $vmInfo['name'],
               'autokey' => $autokey,
               'start_date' => $start,
               'end_date' => $end,
               'ip_address' => $request->ip(),
               'used_at' => null,
               'created_at' => now(),
               'updated_at' => now(),
           ]);

           return response()->json([
               'status' => 'success',
               'redirect_url' => route('console.console', ['autokey' => $autokey])
           ]);
       }else {
                return response()->json(['status' => 'error', 'message' => 'Doğrulama kodu hatalı.']);
       }
   }

   public function consoleView(Request $request, $autokey)
   {
       $clientId = Session::get('client');
       if (!$clientId) {
           abort(403, 'Giriş yapmalısınız.');
       }

       $record = DB::table('console_links')
           ->where('autokey', $autokey)
           ->where('user_id', $clientId)
           ->where('end_date', '>=', Carbon::now())
           ->first();

       if (!$record || $record->ip_address !== $request->ip()) {
           return response()->view('console.error', ['message' => 'Oturum geçersiz veya erişim izniniz yok.']);
       }

       if ($record->used_at) {
           return response()->view('console.error', ['message' => 'Bu bağlantı daha önce kullanılmış.']);
       }

       DB::table('console_links')->where('id', $record->id)->update(['used_at' => now()]);

       $clientDetails = $this->whmcs->getClientDetails($clientId);
       $adsoyad = ($clientDetails['firstname'] ?? '') . ' ' . ($clientDetails['lastname'] ?? '');

       $vmware = new VmwareClient();
       $ticket = $vmware->getConsoleTicket($record->vm_id);

       if (!$ticket || empty($ticket['ticket'])) {
           return response()->view('console.error', ['message' => 'Sunucunuz kapalı veya erişim izniniz yok!']);
       }

       $parsedUrl = parse_url($ticket['ticket']);
       $hostMap = [
           '193.3.35.6' => 'vs0.ssctrl.net',
           '193.3.35.7' => 'vs1.ssctrl.net',
           '193.3.35.8' => 'vs2.ssctrl.net',
       ];

       $originalHost = $parsedUrl['host'] ?? '';
       $maskedHost = $hostMap[$originalHost] ?? $originalHost;

       $maskedTicketUrl =
           ($parsedUrl['scheme'] ?? 'wss') . '://' .
           $maskedHost . ':' .
           ($parsedUrl['port'] ?? 443) .
           ($parsedUrl['path'] ?? '/');

       $remaining_minutes = Carbon::now()->diffInMinutes(Carbon::parse($record->end_date));

       return view('console.console', [
           'ticket_url' => $maskedTicketUrl,
           'vm_name' => $record->hostname,
           'adsoyad' => $adsoyad,
           'minuten' => $remaining_minutes,
       ]);
   }
   public function processConsoleAction(Request $request)
   {
       $clientId = Session::get('client');
       if (!$clientId) {
           return response()->json(['status' => 'error', 'message' => 'Giriş yapılmamış.']);
       }

       $action = $request->input('action'); // start / stop / reset
       $domain = $request->input('domain'); // vm name olacak

       if (!in_array($action, ['start', 'stop', 'reset'])) {
           return response()->json(['status' => 'error', 'message' => 'Geçersiz işlem.']);
       }

       if (!$domain) {
           return response()->json(['status' => 'error', 'message' => 'Domain eksik.']);
       }

       // Kullanıcının bu VM'e sahip olup olmadığını kontrol et
       $vmProduct = DB::table('tblhosting')
           ->where('domain', $domain)
           ->where('userid', $clientId)
           ->first();

       if (!$vmProduct) {
           return response()->json(['status' => 'error', 'message' => 'Bu sanal makine size ait değil.']);
       }

       // VMware API'den vm_id'yi bulalım
       $vmware = new VmwareClient();
       $vm = $vmware->getVM($domain);

       if (!$vm || empty($vm['vm'])) {
           return response()->json(['status' => 'error', 'message' => 'VM bulunamadı.']);
       }

       // İşlemi uygula
       $response = $vmware->manageVM($vm['vm'], $action);

       return response()->json(['status' => 'success', 'message' => $response]);
   }
}
