<?php include "header.php"; ?>
<?php
include_once __DIR__ . '/../includes/white_label_lib.php';

$userId = $userdata['id'];
$message = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_domain'])) {
    $domain = strtolower(trim($_POST['custom_domain'] ?? ''));
    $domain = preg_replace('#^https?://#i', '', $domain);
    $domain = rtrim($domain, '/');

    if ($domain === '') {
        $stmt = $conn->prepare("UPDATE users SET custom_domain = NULL, custom_domain_verified = 0 WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $message = ['type' => 'success', 'text' => 'White-label domain hata diya gaya - ab default domain use hoga.'];
    } elseif (!preg_match('/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/', $domain)) {
        $message = ['type' => 'error', 'text' => 'Yeh domain sahi format me nahi hai (jaise: pay.aapkicompany.com).'];
    } else {
        $stmt = $conn->prepare("UPDATE users SET custom_domain = ?, custom_domain_verified = 0 WHERE id = ?");
        if (!$stmt) {
            $message = ['type' => 'error', 'text' => 'Setup incomplete - sql/RUN_THIS_ALL_IN_ONE.sql run karein.'];
        } else {
            $stmt->bind_param("si", $domain, $userId);
            $stmt->execute();
            $message = ['type' => 'success', 'text' => 'Domain save ho gaya. Ab neeche diye steps follow karke verify karein.'];
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_verification'])) {
    $userRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT custom_domain FROM users WHERE id = " . (int)$userId));
    $domain = $userRow['custom_domain'] ?? '';
    $expectedToken = get_domain_verification_token($conn, $userId);

    $verified = false;
    if ($domain !== '') {
        $records = @dns_get_record($domain, DNS_TXT);
        if (is_array($records)) {
            foreach ($records as $r) {
                if (isset($r['txt']) && trim($r['txt']) === $expectedToken) {
                    $verified = true;
                    break;
                }
            }
        }
    }

    if ($verified) {
        $stmt = $conn->prepare("UPDATE users SET custom_domain_verified = 1 WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();

        include_once __DIR__ . '/../includes/cpanel_lib.php';
        if (cpanel_configured($conn)) {
            $cpanelResult = cpanel_add_addon_domain($conn, $domain);
            if ($cpanelResult['ok']) {
                $conn->query("UPDATE users SET custom_domain_cpanel_added = 1 WHERE id = " . (int)$userId);
                cpanel_request_autossl($conn); // best-effort, ignore failure
                $message = ['type' => 'success', 'text' => 'Domain verify ho gaya aur cPanel me automatically add bhi ho gaya! Kuch minute me SSL bhi ban jaayega, uske baad aapke payment links is domain se kaam karne lagenge.'];
            } else {
                $message = ['type' => 'error', 'text' => 'Domain DNS se verify ho gaya, lekin cPanel me automatically add nahi ho paaya: ' . $cpanelResult['message'] . ' - admin se manually add karwane ko bolein.'];
            }
        } else {
            $message = ['type' => 'success', 'text' => 'Domain verify ho gaya! Aapke naye payment links ab is domain se banenge (cPanel Addon Domain manually add karna hoga - admin se contact karein).'];
        }
    } else {
        $message = ['type' => 'error', 'text' => 'TXT record abhi nahi mila. DNS update hone me kabhi kabhi 30-60 minute lag sakte hain - thodi der baad dobara try karein.'];
    }
}

$userRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT custom_domain, custom_domain_verified FROM users WHERE id = " . (int)$userId));
$currentDomain = $userRow['custom_domain'] ?? '';
$isVerified = (int)($userRow['custom_domain_verified'] ?? 0) === 1;
$verificationToken = get_domain_verification_token($conn, $userId);

// Root domains (2 labels, e.g. "com00.cyou") use "@" for the record Name.
// Subdomains (3+ labels, e.g. "pay.com00.cyou") need that first label
// ("pay") - most DNS providers auto-append the base domain themselves.
$domainLabelParts = $currentDomain ? explode('.', $currentDomain) : [];
$dnsRecordName = (count($domainLabelParts) > 2) ? $domainLabelParts[0] : '@';
include_once __DIR__ . '/../includes/cpanel_lib.php';
$cpanelAutoConfigured = cpanel_configured($conn);
$serverName = $_SERVER['SERVER_NAME'];
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
    .wl-card{background:#14141f;border:1px solid rgba(255,255,255,.08);border-radius:16px;padding:24px;margin-bottom:20px;color:#fff}
    .wl-card h3{margin:0 0 14px;font-size:1.05rem}
    .wl-fg{margin-bottom:14px}
    .wl-fg label{display:block;font-size:.8rem;color:rgba(255,255,255,.6);margin-bottom:6px}
    .wl-fg input{width:100%;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);border-radius:8px;padding:10px 12px;color:#fff;font-size:.9rem}
    .wl-btn{background:linear-gradient(135deg,#6c63ff,#e040fb);border:none;color:#fff;font-weight:700;padding:10px 20px;border-radius:8px;cursor:pointer;font-size:.85rem}
    .wl-msg{border-radius:10px;padding:12px 16px;margin-bottom:16px;font-size:.85rem}
    .wl-msg.success{background:rgba(37,211,102,.12);color:#25D366}
    .wl-msg.error{background:rgba(255,101,132,.12);color:#ff6584}
    .wl-badge{font-size:.72rem;font-weight:700;padding:3px 10px;border-radius:20px;margin-left:8px}
    .wl-badge.verified{background:rgba(37,211,102,.15);color:#25D366}
    .wl-badge.pending{background:rgba(245,185,59,.15);color:#f5b93b}
    .wl-code{background:rgba(255,255,255,.06);border-radius:8px;padding:10px 14px;font-family:monospace;font-size:.82rem;word-break:break-all;color:#a78bfa}
    .wl-copy-wrap{display:flex;align-items:center;gap:8px}
    .wl-copy-wrap .wl-code{flex:1}
    .wl-copy-btn{background:rgba(108,99,255,.15);border:1px solid rgba(108,99,255,.3);color:#a78bfa;border-radius:8px;padding:8px 12px;cursor:pointer;flex-shrink:0;font-size:.82rem}
    .wl-copy-btn:hover{background:rgba(108,99,255,.28)}
    .wl-copy-btn.copied{background:rgba(37,211,102,.2);border-color:rgba(37,211,102,.4);color:#25D366}
    .wl-step{display:flex;gap:12px;margin-bottom:16px}
    .wl-step-num{width:26px;height:26px;border-radius:50%;background:rgba(108,99,255,.2);color:#a78bfa;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.8rem;flex-shrink:0}
</style>

<div class="wl-card">
    <h3><i class="fas fa-globe"></i> White-Label Domain
        <?php if ($currentDomain): ?>
            <span class="wl-badge <?php echo $isVerified ? 'verified' : 'pending'; ?>"><?php echo $isVerified ? 'Verified' : 'Not Verified'; ?></span>
        <?php endif; ?>
    </h3>
    <p style="color:rgba(255,255,255,.5);font-size:.85rem;margin:0 0 16px">Apna khud ka domain (jaise <code>pay.aapkicompany.com</code>) use karein payment links/QR ke liye - customer ko kahi bhi "NeoPay" ka naam nahi dikhega.</p>

    <div style="background:rgba(245,185,59,.1);border:1px solid rgba(245,185,59,.25);border-radius:10px;padding:12px 16px;margin-bottom:16px;font-size:.82rem;color:#f5b93b">
        <i class="fas fa-triangle-exclamation"></i> <b>Root domain (jaise <code>aapkicompany.com</code>) mat daalein</b> agar wahan aapki asli website already chal rahi hai - ek domain sirf ek jagah point ho sakta hai. Iske jagah ek <b>naya subdomain</b> banayein sirf payment ke liye, jaise <code>pay.aapkicompany.com</code> - aapki asli website bilkul waise hi chalti rahegi, kuch nahi hilta.
    </div>

    <?php if ($message): ?><div class="wl-msg <?php echo $message['type']; ?>"><?php echo htmlspecialchars($message['text']); ?></div><?php endif; ?>

    <form method="POST" action="">
        <div class="wl-fg">
            <label>Aapka Domain</label>
            <input type="text" name="custom_domain" placeholder="pay.aapkicompany.com" value="<?php echo htmlspecialchars($currentDomain); ?>">
        </div>
        <button type="submit" name="save_domain" class="wl-btn"><i class="fas fa-save"></i> Save</button>
    </form>
</div>

<?php if ($currentDomain && !$isVerified): ?>
<div class="wl-card">
    <h3><i class="fas fa-list-check"></i> Verify Karein (ek baar ka setup)</h3>

    <div class="wl-step">
        <div class="wl-step-num">1</div>
        <div>
            <b>Apne domain ka DNS kholen</b> (jaha aapne <?php echo htmlspecialchars($currentDomain); ?> khareeda hai - GoDaddy, Namecheap, Cloudflare, waghera)
        </div>
    </div>
    <div class="wl-step">
        <div class="wl-step-num">2</div>
        <div>
            <b>Ek TXT record add karein:</b><br>
            Host/Name:
            <div class="wl-copy-wrap" style="display:inline-flex;margin:4px 0">
                <span class="wl-code" id="wlTxtHost"><?php echo htmlspecialchars($dnsRecordName); ?></span>
                <button type="button" class="wl-copy-btn" onclick="wlCopy('wlTxtHost', this)"><i class="fas fa-copy"></i></button>
            </div>
            <br>
            Value:
            <div class="wl-copy-wrap" style="margin-top:6px">
                <div class="wl-code" id="wlTxtValue"><?php echo htmlspecialchars($verificationToken); ?></div>
                <button type="button" class="wl-copy-btn" onclick="wlCopy('wlTxtValue', this)"><i class="fas fa-copy"></i> Copy</button>
            </div>
        </div>
    </div>
    <div class="wl-step">
        <div class="wl-step-num">3</div>
        <div>
            <b>Ek CNAME record bhi add karein</b> taaki domain actually payment page tak pahunche:<br>
            Host/Name:
            <div class="wl-copy-wrap" style="display:inline-flex;margin:4px 0">
                <span class="wl-code" id="wlCnameHost"><?php echo htmlspecialchars($dnsRecordName); ?></span>
                <button type="button" class="wl-copy-btn" onclick="wlCopy('wlCnameHost', this)"><i class="fas fa-copy"></i></button>
            </div><br>
            Value:
            <div class="wl-copy-wrap" style="margin-top:4px">
                <span class="wl-code" id="wlCnameValue"><?php echo htmlspecialchars($serverName); ?></span>
                <button type="button" class="wl-copy-btn" onclick="wlCopy('wlCnameValue', this)"><i class="fas fa-copy"></i> Copy</button>
            </div>
        </div>
    </div>
    <div class="wl-step">
        <div class="wl-step-num">4</div>
        <div>
            <?php if ($cpanelAutoConfigured): ?>
                <b>cPanel me domain automatically add ho jaayega</b> - DNS verify hote hi (neeche "Check Verification" dabate hi), system khud cPanel me Addon Domain bana dega. Koi manual kaam nahi. SSL (https) cPanel ka AutoSSL khud kuch der me generate kar dega.
            <?php else: ?>
                <b>cPanel me is domain ko Addon Domain ke roop me add karwayein</b> (isi account ke docroot se) - yeh step aapko apne hosting provider/admin se karwana hoga, taaki server is domain ka traffic sahi jagah bheje. SSL (https) bhi cPanel ka AutoSSL khud generate kar dega, DNS sahi hone ke kuch der baad.
            <?php endif; ?>
        </div>
    </div>

    <form method="POST" action="" style="margin-top:10px">
        <button type="submit" name="check_verification" class="wl-btn"><i class="fas fa-rotate"></i> Check Verification</button>
    </form>
    <p style="color:rgba(255,255,255,.4);font-size:.78rem;margin-top:10px">DNS update duniya bhar me failne me kabhi kabhi 30-60 minute lagte hain - turant verify na ho to thodi der baad try karein.</p>
</div>
<?php endif; ?>

<?php if ($currentDomain && $isVerified): ?>
<div class="wl-card">
    <h3><i class="fas fa-circle-check" style="color:#25D366"></i> Active</h3>
    <p style="color:rgba(255,255,255,.6);font-size:.85rem">Aapke naye payment links, static paylinks, aur QR codes ab <b><?php echo htmlspecialchars($currentDomain); ?></b> se generate ho rahe hain.</p>
</div>
<?php endif; ?>

<script>
function wlCopy(elId, btn) {
    var text = document.getElementById(elId).textContent.trim();
    navigator.clipboard.writeText(text).then(function() {
        var original = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i> Copied';
        btn.classList.add('copied');
        setTimeout(function() {
            btn.innerHTML = original;
            btn.classList.remove('copied');
        }, 1500);
    });
}
</script>
