<?php
/**
 * white_label_lib.php
 * One place that decides "which domain should this merchant's links use" -
 * their own verified custom domain if they've set one up, otherwise the
 * default site domain (whatever the current request came in on).
 */

/**
 * The domain the browser actually asked for, read straight from the Host
 * header. On some shared/LiteSpeed hosting setups where multiple
 * subdomains point at the same document root (e.g. panel.mgamer.online
 * and neopay.mgamer.online both serving this same codebase),
 * $_SERVER['SERVER_NAME'] can silently resolve to the account's primary
 * domain instead of the subdomain that was actually requested - which is
 * why payment links kept generating on neopay.mgamer.online even while
 * testing from panel.mgamer.online with no white-label domain configured
 * at all. HTTP_HOST is the literal Host header the browser sent, so it
 * doesn't have that ambiguity.
 */
function current_host() {
    $host = $_SERVER['HTTP_HOST'] ?? '';
    $host = preg_replace('/:\d+$/', '', $host); // strip a port if present
    return $host !== '' ? $host : ($_SERVER['SERVER_NAME'] ?? '');
}

function get_merchant_domain($conn, $userId, $fallbackDomain = null) {
    $fallbackDomain = $fallbackDomain ?: current_host();

    $res = mysqli_query($conn, "SELECT custom_domain, custom_domain_verified FROM users WHERE id = " . (int)$userId);
    $row = $res ? mysqli_fetch_assoc($res) : null;

    if ($row && !empty($row['custom_domain']) && (int)$row['custom_domain_verified'] === 1) {
        return $row['custom_domain'];
    }
    return $fallbackDomain;
}

/**
 * Verification token a merchant must publish (as a DNS TXT record or a
 * file on their domain) to prove they actually control it before we'll
 * start putting their brand's domain into live payment links.
 */
function get_domain_verification_token($conn, $userId) {
    $userIdInt = (int)$userId;
    return 'neopay-verify-' . substr(md5('domain-verify-salt-' . $userIdInt), 0, 16);
}

/**
 * True if the current request's Host header matches a merchant's VERIFIED
 * white-label domain. Since a white-label Addon Domain shares the exact
 * same docroot as the main site, every page (login, dashboard, admin
 * panel) is technically reachable under it unless it's explicitly blocked
 * - white-label domains should only ever serve payment pages.
 */
function is_white_label_request($conn) {
    $host = strtolower($_SERVER['HTTP_HOST'] ?? '');
    $host = preg_replace('/:\d+$/', '', $host); // strip a port if present
    if ($host === '') return false;

    $res = mysqli_query($conn, "SELECT id FROM users WHERE custom_domain = '" . mysqli_real_escape_string($conn, $host) . "' AND custom_domain_verified = 1 LIMIT 1");
    return $res && mysqli_num_rows($res) > 0;
}

/**
 * Call this at the top of any page that is NOT a payment page. If the
 * request came in on a merchant's white-label domain, blocks it (that
 * domain should only show payment pages, never login/admin/register).
 */
function block_if_white_label_domain($conn) {
    if (is_white_label_request($conn)) {
        http_response_code(404);
        echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Not Found</title>
        <style>body{font-family:sans-serif;background:#0a0a12;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;text-align:center;padding:20px}</style>
        </head><body><div><h2>404 - Not Found</h2><p style="color:rgba(255,255,255,.5)">Yeh page is domain par available nahi hai.</p></div></body></html>';
        exit;
    }
}
