<?php
// ─── Domains API ──────────────────────────────────────────────────────────
// Domains are never sold standalone on this platform — only as part of a
// hosting order (see orders.php@checkout's domain_action: own/free/buy).
// This file manages domains already attached to an order (nameservers, info)
// plus the customer-facing TLD allow-list + availability/price check used at
// checkout. Actual registrar communication is via core/registrars.php, which
// shops every active registrar and returns the cheapest — the customer never
// picks one, and orders.php records which one gets used at registration time.

function domainList() {
    $uid = require_login();
    global $conn;
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";

    $rss = mysqli_query($conn, "SELECT * FROM h_order WHERE status!='4' $uidok ORDER BY id DESC LIMIT 50");
    $items = [];
    while ($row = mysqli_fetch_assoc($rss)) {
        $dom = explode(',', decode($row['domain'] ?? '', KEY_ONE));
        $inv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT exdate FROM h_invoice WHERE id='{$row['iid']}'")) ?: [];
        $items[] = [
            'id'     => $row['id'],
            'id_enc' => encode($row['id'], KEY_ONE),
            'domain' => $dom[0] ?? '',
            'status' => (int)$row['status'] === 1 ? 'Active' : 'Pending',
            'exdate' => $inv['exdate'] ?? '',
            'ns1'    => $row['ns1'] ?? '',
            'ns2'    => $row['ns2'] ?? ''
        ];
    }
    success_response(['items' => $items]);
}

function nameservers() {
    $uid = require_login();
    global $conn;

    $oid = (int)($_POST['oid'] ?? 0);
    $ns1 = strtolower(trim($_POST['ns1'] ?? ''));
    $ns2 = strtolower(trim($_POST['ns2'] ?? ''));

    if (empty($ns1) || empty($ns2) || $ns1 === $ns2) error_response('Please provide two different nameservers.');
    if (!preg_match('/^[a-z0-9.-]+\.[a-z]{2,}$/', $ns1) || !preg_match('/^[a-z0-9.-]+\.[a-z]{2,}$/', $ns2)) {
        error_response('Nameservers must look like valid hostnames.');
    }

    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";
    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT domain, registrar_id FROM h_order WHERE id='$oid' $uidok"));
    if (!$row) error_response('Domain not found', 404);
    $domain = explode(',', decode($row['domain'] ?? '', KEY_ONE))[0] ?? '';

    require_once __DIR__ . '/../core/registrars.php';
    $registrarNote = '';
    if ($domain !== '' && !empty($row['registrar_id'])) {
        $result = registrar_change_nameservers_via($row['registrar_id'], $domain, $ns1, $ns2);
        if (!$result['ok']) $registrarNote = ' (Registrar update failed: ' . $result['message'] . ' — saved locally only.)';
    }

    $ns1Safe = mysqli_real_escape_string($conn, $ns1);
    $ns2Safe = mysqli_real_escape_string($conn, $ns2);
    mysqli_query($conn, "UPDATE h_order SET ns1='$ns1Safe', ns2='$ns2Safe' WHERE id='$oid'");

    success_response([], 'Nameservers updated.' . $registrarNote);
}

function tldList() {
    global $conn;
    $rss = mysqli_query($conn, "SELECT id, tld FROM h_tld WHERE status='1' ORDER BY sort_order ASC, tld ASC");
    $items = [];
    while ($row = mysqli_fetch_assoc($rss)) { $items[] = $row; }
    success_response(['items' => $items]);
}

function checkAvailability() {
    $domain = strtolower(trim($_GET['domain'] ?? ''));
    if (!preg_match('/^[a-z0-9-]+\.[a-z]{2,}$/', $domain)) error_response('Please enter a valid domain name.');

    require_once __DIR__ . '/../core/registrars.php';
    $result = shop_domain($domain);
    if (!$result['ok']) error_response($result['message']);

    if (empty($result['available'])) {
        success_response(['available' => false, 'price' => null], $result['message'] ?? 'That domain is already taken.');
    }

    success_response(['available' => true, 'price' => $result['price']], 'This domain is available!');
}

function info() {
    $uid = require_login();
    global $conn;
    $oid = (int)($_GET['oid'] ?? 0);
    $uidok = is_admin($uid) ? '' : "AND uid='$uid'";

    $row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT domain, ns1, ns2, registrar_id FROM h_order WHERE id='$oid' $uidok"));
    if (!$row) error_response('Domain not found', 404);
    $domain = explode(',', decode($row['domain'] ?? '', KEY_ONE))[0] ?? '';

    $registrarInfo = [];
    require_once __DIR__ . '/../core/registrars.php';
    if ($domain !== '' && !empty($row['registrar_id'])) {
        $result = registrar_get_domain_info_via($row['registrar_id'], $domain);
        if ($result['ok']) $registrarInfo = $result['data'];
    }

    success_response([
        'domain'         => $domain,
        'ns1'            => $row['ns1'] ?? '',
        'ns2'            => $row['ns2'] ?? '',
        'registrar_info' => $registrarInfo
    ]);
}
