<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/includes/api_helpers.php';

$db = gpc_db();
$body = gpc_parse_body();

if (!is_array($body) || !gpc_validate_key(isset($body['app_key_dev']) ? (string) $body['app_key_dev'] : null)) {
    gpc_json_out(['data' => []]);
    exit;
}

$providedCod = isset($body['codRevenda']) ? trim((string) $body['codRevenda']) : '';
$today = date('Y-m-d');
$items = [];

$activeWhere = "ds.status = 1 AND (ds.validity = '' OR ds.validity IS NULL OR ds.validity >= :today) AND (ds.reseller_id IS NULL OR (r.active = 1 AND (r.validity = '' OR r.validity IS NULL OR r.validity >= :today)))";

if ($providedCod !== '') {
    $stmt = $db->prepare("SELECT ds.id, ds.url FROM dns_servers ds LEFT JOIN resellers r ON r.id = ds.reseller_id WHERE ds.code = :code AND $activeWhere ORDER BY ds.id DESC LIMIT 1");
    $stmt->execute([':code' => $providedCod, ':today' => $today]);
    $row = $stmt->fetch();
    if ($row) {
        $base = gpc_base_url((string) $row['url']);
        if ($base !== '') $items[] = ['id' => (int) $row['id'], 'dns' => $base];
    }
} else {
    $stmt = $db->prepare("SELECT ds.id, ds.url FROM dns_servers ds LEFT JOIN resellers r ON r.id = ds.reseller_id WHERE ds.reseller_id IS NULL AND $activeWhere ORDER BY ds.id ASC");
    $stmt->execute([':today' => $today]);
    while ($row = $stmt->fetch()) {
        $base = gpc_base_url((string) $row['url']);
        if ($base !== '') $items[] = ['id' => (int) $row['id'], 'dns' => $base];
    }
}

gpc_json_out(['data' => $items]);
