<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class cPanelController extends Controller
{
  public function login(Request $request)
{
  $username = $request->input('username');
  $type = $request->input('type');
  $app = $request->input('app');
  $whmusername = "root";

  $serverId = $request->input('serverid');

  // WHMCS veri tabanından accesshash değerini al
  try {
      $accessHash = DB::connection('whmcs')->table('tblservers')
          ->where('id', $serverId)
          ->value('accesshash');
          $servername = DB::connection('whmcs')->table('tblservers')
              ->where('id', $serverId)
              ->value('hostname');

      if (!$accessHash) {
          throw new Exception("Sunucu ID $serverId için accesshash bulunamadı.");
      }
  } catch (Exception $e) {
      error_log('Veri tabanı hatası: ' . $e->getMessage());
      die('Access hash bilgisi alınamadı.');
  }

  if ($type == "reselleraccount") {
    $query = "https://$servername:2087/json-api/create_user_session?api.version=1&user=$username&service=whostmgrd";
  }else {
    $query = "https://$servername:2087/json-api/create_user_session?api.version=1&user=$username&service=cpaneld&app=$app";
  }


  // cURL oturumunu başlat ve seçenekleri ayarla
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

  // Yetkilendirme başlığını ekle
  $header[0] = "Authorization: WHM $whmusername:" . preg_replace("'(\r|\n)'", "", $accessHash);
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_URL, $query);

  // cURL yürüt ve sonucu al
  $result = curl_exec($curl);

  // Hata kontrolü
  if ($result === false) {
      error_log('cURL error: ' . curl_error($curl));
      curl_close($curl);
      die('Error occurred during cURL execution.');
  }

  // Sonucu işleme
  $decoded_response = json_decode($result, true);
  if (isset($decoded_response['data']['url'])) {
      $url = $decoded_response['data']['url'];
      curl_close($curl);
      return redirect($url);
  } else {
      error_log('Failed to create user session: ' . $result);
      curl_close($curl);
      die('Failed to create user session.');
  }
}

public function getResellerDomains($serverId, $resellerUsername)
{
    $whmusername = "root";

    try {
        $accessHash = DB::connection('whmcs')->table('tblservers')
            ->where('id', $serverId)
            ->value('accesshash');
        $servername = DB::connection('whmcs')->table('tblservers')
            ->where('id', $serverId)
            ->value('hostname');

        if (!$accessHash || !$servername) {
            throw new \Exception("AccessHash ya da Servername alınamadı.");
        }
    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage()], 500);
    }

    $url = "https://$servername:2087/json-api/listaccts?api.version=1&searchtype=owner&search={$resellerUsername}";

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: WHM $whmusername:" . preg_replace("'(\r|\n)'", '', $accessHash)
        ],
        CURLOPT_URL => $url
    ]);

    $response = curl_exec($curl);
    if ($response === false) {
        return response()->json(['error' => curl_error($curl)], 500);
    }
    curl_close($curl);

    $data = json_decode($response, true);

    if (isset($data['data']['acct'])) {
        // Sadece domain isimlerini döndürmek istiyorsan:
        $domains = array_map(fn($item) => $item['domain'], $data['data']['acct']);
        return response()->json(['domains' => $domains]);
    } else {
        return response()->json(['error' => 'Reseller domainleri alınamadı.', 'raw' => $data], 500);
    }
}
}
