<?php
ini_set('display_errors', 0);
header("Content-type: application/json; charset=utf-8");

include "dna.php";

// Load WHMCS data from JSON file
$whmcsData = json_decode(file_get_contents('../whmcs_data.json'), true);
$tldPricing = isset($whmcsData['tldPricing']['pricing']) ? $whmcsData['tldPricing']['pricing'] : [];

$api = new DomainNameAPI_PHPLibrary();
$api->setUser("ugurakkaya", "Unna_2026**1612#HelloX");
$api->useCaching(true);
$api->useTestMode(false);

$aciklama = ["tr" => "Belgesiz <b>Ön Kayıt</b>"];
$defExts = [$_GET["ext"]];

if (isset($_GET["only"])) {
    $defExts = [($_GET["ext"] ?? "com")];
} else {
    if (isset($_GET["ext"]) && $_GET["ext"] !== "undefined" && !in_array($_GET["ext"], $defExts)) {
        if (isset($_GET["only"])) {
            $defExts = [$_GET["ext"]];
        } else {
            $defExts[] = $_GET["ext"];
        }
    }
}

switch ($_GET["action"] ?? '') {
    case 'queryDomain':
      $json_data = file_get_contents('../domainlist.json');

      // JSON verisini bir diziye çevir
      $edata = json_decode($json_data, true);

      if (isset($_GET["skip"]) && $_GET["skip"] > 0) {
          // skip parametresine göre veri dilimle
          $paged_data = array_slice($edata, $_GET["skip"], 5);

          // uzantılardan noktayı kaldır ve diziyi oluştur
          $defExts = array_map(function ($a) {
              return ltrim($a["uzanti"]);
            }, $paged_data);
          }
        $tc = (isset($_GET["transfer"])) ? "transfer" : "create";
        $query = $api->CheckAvailability([$_GET["domain"] ?? ''], $defExts, 1, $tc);
        $result = [];

        if (isset($query["data"]) && $query["result"] === "OK") {
            foreach ($query["data"] as $res) {
                $tld = strtolower($res["Tld"] ?? $res["TLD"] ?? '');
                $price = isset($tldPricing[$tld]['register']['1']) ? (float)$tldPricing[$tld]['register']['1'] : 0;

                $result[] = [
                    "DomainName" => $res["DomainName"] ?? '',
                    "TLD" => $tld,
                    "Status" => ($res["ClassKey"] ?? '') === "premium" ? "premium" : ($res["Status"] ?? ''),
                    "oldPrice" => number_format($price * 1.2, 2),
                    "Aciklama" => $aciklama[$tld] ?? '',
                    "Price" => number_format($price, 2),
                    "Currency" => "USD"
                ];
            }
        } else {
            $result = $query["error"] ?? ["message" => "An error occurred"];
        }
        echo json_encode($result);
        break;

    case 'checkDomain':
        $query = $api->CheckAvailability([$_GET["domain"] ?? ''], $defExts, 1, "create");
        echo json_encode($query);
        break;

    default:
        echo json_encode(["error" => "Invalid action"]);
        break;
}
?>
