<?php
include "header.php";



if(isset($_POST['get_api_token'])){
    
   
    $bbbyteuserid=$_SESSION['user_id'];
    // Assuming $mobile is already defined in header.php
    $sanitizedMobile = mysqli_real_escape_string($conn, $mobile);

    $uniqueNumber = mt_rand(1000000000, 9999999999);
    $uniqueNumber = str_pad($uniqueNumber, 10, '0', STR_PAD_LEFT); 

    $key = md5($uniqueNumber);
    $keyquery = "UPDATE `users` SET user_token='$key' WHERE mobile = '$sanitizedMobile'";
    $queryres = mysqli_query($conn, $keyquery);
    
    //update token in orders table
    
    $keyqueryorders = "UPDATE `orders` SET user_token='$key' WHERE user_id = $bbbyteuserid";
    $queryorders = mysqli_query($conn, $keyqueryorders);
    
     //update token in reports table
    
    $keyqueryordersreports = "UPDATE `reports` SET user_token='$key' WHERE user_id = $bbbyteuserid";
    $queryordersreports = mysqli_query($conn, $keyqueryordersreports);
    
    
    
    
    //hdfc token update 
    
    $keyqueryhdfc = "UPDATE `hdfc` SET user_token='$key' WHERE user_id = $bbbyteuserid";
    $queryreshdfc = mysqli_query($conn, $keyqueryhdfc);
    
    // Updating user_token in bharatpe_tokens table
    $keyquerybharatpe = "UPDATE `bharatpe_tokens` SET user_token='$key' WHERE user_id = '$bbbyteuserid'";
    $queryresbharatpe = mysqli_query($conn, $keyquerybharatpe);
    
    
    //update for phonepe  Updating user_token in phonepe_tokens  table and store_id table
    
    $keyqueryphonepetoken = "UPDATE `phonepe_tokens` SET user_token='$key' WHERE user_id = '$bbbyteuserid'";
    $queryresphonepetoken = mysqli_query($conn, $keyqueryphonepetoken);
    
    //now to update user_token in table store_id
    
    $keyqueryphonepetoken2 = "UPDATE `store_id` SET user_token='$key' WHERE user_id = '$bbbyteuserid'";
    $queryresphonepetoken2 = mysqli_query($conn, $keyqueryphonepetoken2);
    
    //now to update user_token in table paytm_tokens
    
    $keyquerypaytm2 = "UPDATE `paytm_tokens` SET user_token='$key' WHERE user_id = '$bbbyteuserid'";
    $queryrespaytm = mysqli_query($conn, $keyquerypaytm2);
    
    //now to update user_token in table googlepay_transactions
    
    $keyquerygooglepay = "UPDATE `googlepay_transactions` SET user_token='$key' WHERE user_id = '$bbbyteuserid'";
    $queryresgooglepay = mysqli_query($conn, $keyquerygooglepay);
    
    //now to update user_token in table googlepay_tokens
    
     $keyquerygooglepay1 = "UPDATE `googlepay_tokens` SET user_token='$key' WHERE user_id = '$bbbyteuserid'";
    $queryresgooglepay1 = mysqli_query($conn, $keyquerygooglepay1);
    
    
    if($queryres && $queryreshdfc){
        
        
        
        // Show SweetAlert2 success message
                            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
echo '<script>
    Swal.fire({
        icon: "success",
        title: "New API Key generated!!",
        showConfirmButton: true, // Show the confirm button
        confirmButtonText: "Ok!", // Set text for the confirm button
        allowOutsideClick: false, // Prevent the user from closing the popup by clicking outside
        allowEscapeKey: false // Prevent the user from closing the popup by pressing Escape key
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "apidetails"; // Redirect to "dashboard" when the user clicks the confirm button
        }
    });
</script>';

    exit;
    
    } else {
        
        
        
        
          // Show SweetAlert2 error message
                            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
echo '<script>
    Swal.fire({
        icon: "error",
        title: "API Key Generating Failed!!",
        showConfirmButton: true, // Show the confirm button
        confirmButtonText: "Ok!", // Set text for the confirm button
        allowOutsideClick: false, // Prevent the user from closing the popup by clicking outside
        allowEscapeKey: false // Prevent the user from closing the popup by pressing Escape key
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "apidetails"; // Redirect to "dashboard" when the user clicks the confirm button
        }
    });
</script>';
exit;
    }
}
?>
<?php

// Very light validation - just make sure something was actually typed.
// No protocol requirement, no strict TLD check - any URL the merchant
// wants to use should be accepted (they know their own endpoint).
function isValidUrl($url) {
    return trim($url) !== '';
}

/**
 * Merchants shouldn't need to type "https://" themselves - but curl
 * genuinely cannot deliver to a URL with no scheme, so quietly add one
 * here if it's missing rather than silently failing every delivery.
 */
function normalizeWebhookUrl($url) {
    $url = trim($url);
    if ($url !== '' && !preg_match('#^https?://#i', $url)) {
        $url = 'https://' . $url;
    }
    return $url;
}

if(isset($_POST['update_webhook'])){
    
    
    $bytecallbackurl = mysqli_real_escape_string($conn, normalizeWebhookUrl($_POST['webhook_url']));
    
    // Validate the webhook URL
    // Check if the URL has a valid TLD
    if (!isValidUrl($bytecallbackurl)) {
        
        // Show SweetAlert2 error message
                            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
echo '<script>
    Swal.fire({
        icon: "error",
        title: "Invalid webhook url!!",
        showConfirmButton: true, // Show the confirm button
        confirmButtonText: "Ok!", // Set text for the confirm button
        allowOutsideClick: false, // Prevent the user from closing the popup by clicking outside
        allowEscapeKey: false // Prevent the user from closing the popup by pressing Escape key
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "apidetails"; // Redirect to "dashboard" when the user clicks the confirm button
        }
    });
</script>';

        exit(); // Stop processing the request
    }

    
    
    // Assuming $mobile is already defined in header.php
    $sanitizedMobile = mysqli_real_escape_string($conn, $mobile);


    $key = md5($uniqueNumber);
    $keyquery = "UPDATE `users` SET  callback_url='$bytecallbackurl' WHERE mobile = '$sanitizedMobile'";
    $queryres = mysqli_query($conn, $keyquery);
    if($queryres){
        
        
        
        // Show SweetAlert2 success message
                            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
echo '<script>
    Swal.fire({
        icon: "success",
        title: "Webhook Updated Successfully",
        showConfirmButton: true, // Show the confirm button
        confirmButtonText: "Ok!", // Set text for the confirm button
        allowOutsideClick: false, // Prevent the user from closing the popup by clicking outside
        allowEscapeKey: false // Prevent the user from closing the popup by pressing Escape key
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "apidetails"; // Redirect to "dashboard" when the user clicks the confirm button
        }
    });
</script>';

    exit;
    
    } else {
        
        
        
        
          // Show SweetAlert2 error message
                            echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.18"></script>';
echo '<script>
    Swal.fire({
        icon: "error",
        title: "Error Updating Webhook Try again Later!!",
        showConfirmButton: true, // Show the confirm button
        confirmButtonText: "Ok!", // Set text for the confirm button
        allowOutsideClick: false, // Prevent the user from closing the popup by clicking outside
        allowEscapeKey: false // Prevent the user from closing the popup by pressing Escape key
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = "apidetails"; // Redirect to "dashboard" when the user clicks the confirm button
        }
    });
</script>';
exit;
    }
}

// ---- Test Webhook button ----
$testWebhookResult = null;
if (isset($_POST['test_webhook'])) {
    include_once __DIR__ . '/../includes/webhook_lib.php';
    $testWebhookResult = send_test_webhook($conn, $userdata['id'], $userdata['callback_url'] ?? '');
}

$webhookDeliveries = [];
$wdRes = $conn->query("SELECT * FROM webhook_deliveries WHERE user_id = " . (int)$userdata['id'] . " ORDER BY id DESC LIMIT 10");
if ($wdRes) { while ($r = $wdRes->fetch_assoc()) { $webhookDeliveries[] = $r; } }

// Build the white-label example code as plain strings here (not inline in
// the HTML below) - this keeps the literal "<?php" text that's meant to
// be SHOWN as example code from ever being parsed as real PHP by this
// file itself.
$wlTokenForExample = $userdata['user_token'] ?? 'YOUR_USER_TOKEN';
$wlPhpExampleCode = <<<'PHPEXAMPLE'
<?php
// ============================================================
// NeoPay White-Label Payment Page - poora example, ek hi file me.
// Apne server pe daal dein, CONFIG edit karein, baaki jaisa chahein customize karein.
// ============================================================

$NEOPAY_API_BASE = '__API_BASE__';
$USER_TOKEN       = '__USER_TOKEN__';
$AMOUNT           = isset($_GET['amount']) ? $_GET['amount'] : '1.00';

function neopay_api($base, $path, $params) {
    $ch = curl_init(rtrim($base, '/') . $path);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_TIMEOUT => 15,
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

// Step 1: Order banayein
$orderId = 'ORD' . time() . rand(100, 999);
$order = neopay_api($NEOPAY_API_BASE, '/api/create-order', [
    'user_token'      => $USER_TOKEN,
    'order_id'        => $orderId,
    'amount'          => $AMOUNT,
    'customer_mobile' => '',
    'remark1'         => 'whitelabel-order',
]);

$upiString = $order['result']['upi_string'] ?? null;
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
</head>
<body>
    <h2>Pay Rs. <?php echo htmlspecialchars($AMOUNT); ?></h2>

    <?php if ($upiString): ?>
        <!-- Step 2: QR seedha yahan render hoga -->
        <div id="qr"></div>
        <p id="status">Payment ka intezaar hai...</p>
        <script>
            new QRCode(document.getElementById('qr'), { text: <?php echo json_encode($upiString); ?>, width: 220, height: 220 });

            // Step 3: Polling (webhook ke saath saath, safety ke liye)
            function checkStatus() {
                var body = new URLSearchParams({
                    user_token: <?php echo json_encode($USER_TOKEN); ?>,
                    order_id:   <?php echo json_encode($orderId); ?>
                });
                fetch(<?php echo json_encode(rtrim($NEOPAY_API_BASE, '/')); ?> + '/api/check-order-status', { method: 'POST', body: body })
                    .then(r => r.json())
                    .then(data => {
                        var status = (data.result && data.result.status || '').toUpperCase();
                        if (status === 'SUCCESS') {
                            document.getElementById('status').textContent = 'Payment Successful!';
                        } else if (status === 'FAILURE') {
                            document.getElementById('status').textContent = 'Payment Failed';
                        } else {
                            setTimeout(checkStatus, 3000);
                        }
                    });
            }
            setTimeout(checkStatus, 3000);
        </script>
    <?php else: ?>
        <p>QR generate nahi ho paya - USER_TOKEN check karein, ya FamPay account connect karein.</p>
    <?php endif; ?>
</body>
</html>
PHPEXAMPLE;
$wlPhpExampleCode = str_replace(
    ['__API_BASE__', '__USER_TOKEN__'],
    ['https://' . $server, $wlTokenForExample],
    $wlPhpExampleCode
);

$wlWebhookExampleCode = <<<'WEBHOOKEXAMPLE'
<?php
// receive-webhook.php - is URL ko "Webhook" tab me save karein
$payload = json_decode(file_get_contents('php://input'), true);

if (($payload['status'] ?? '') === 'Success') {
    $order_id = $payload['order_id'];
    $amount   = $payload['amount'];
    $utr      = $payload['utr'];

    // Yahan apna order/invoice activate karne wala code likhein
    // (jaise: database update, email bhejna, service turant on karna)
}

http_response_code(200); // NeoPay ko bata dein ki mil gaya
WEBHOOKEXAMPLE;

$wlTgBotCode = <<<'TGBOTEXAMPLE'
<?php
// telegram-webhook.php
// Yeh URL Telegram ko batayein (BotFather se) ki jab bhi koi user aapke
// bot ko message kare, Telegram isi URL pe POST karega.
//
// Setup command (ek baar chalayein, apna BOT_TOKEN daal ke):
//   https://api.telegram.org/bot<BOT_TOKEN>/setWebhook?url=https://yoursite.com/telegram-webhook.php

$BOT_TOKEN        = 'YOUR_TELEGRAM_BOT_TOKEN';
$NEOPAY_API_BASE  = '__API_BASE__';
$USER_TOKEN       = '__USER_TOKEN__';

$update = json_decode(file_get_contents('php://input'), true);
$chatId = $update['message']['chat']['id'] ?? null;
$text   = trim($update['message']['text'] ?? '');

if (!$chatId) { http_response_code(200); exit; }

function tg_call($botToken, $method, $params) {
    $ch = curl_init("https://api.telegram.org/bot{$botToken}/{$method}");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $params,
        CURLOPT_TIMEOUT => 15,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

function neopay_api($base, $path, $params) {
    $ch = curl_init(rtrim($base, '/') . $path);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($params),
        CURLOPT_TIMEOUT => 15,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

// Example: user types "/pay 100" in the bot chat
if (preg_match('/^\/pay\s+(\d+(\.\d+)?)/', $text, $m)) {
    $amount = $m[1];
    $orderId = 'TG' . $chatId . '_' . time();

    // IMPORTANT: chat_id goes into remark1 - it comes back automatically
    // in the payment webhook later, so we know exactly who to message
    // back without needing to store anything ourselves.
    $order = neopay_api($NEOPAY_API_BASE, '/api/create-order', [
        'user_token'      => $USER_TOKEN,
        'order_id'        => $orderId,
        'amount'          => $amount,
        'customer_mobile' => '',
        'remark1'         => 'tg_chat_' . $chatId,
    ]);

    $upiString = $order['result']['upi_string'] ?? null;

    if ($upiString) {
        // A ready-made QR *image* URL - Telegram's sendPhoto can take this
        // URL directly, no need to generate/download/upload anything.
        $qrImageUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=' . urlencode($upiString);

        tg_call($BOT_TOKEN, 'sendPhoto', [
            'chat_id' => $chatId,
            'photo'   => $qrImageUrl,   // <-- seedha QR image jaayegi, koi link nahi
            'caption' => "Rs. {$amount} pay karne ke liye is QR ko scan karein.\nOrder: {$orderId}",
        ]);
    } else {
        tg_call($BOT_TOKEN, 'sendMessage', [
            'chat_id' => $chatId,
            'text'    => 'QR generate nahi ho paya. Kripya baad me try karein.',
        ]);
    }
} else {
    tg_call($BOT_TOKEN, 'sendMessage', [
        'chat_id' => $chatId,
        'text'    => "Payment karne ke liye likhein: /pay 100",
    ]);
}

http_response_code(200);
TGBOTEXAMPLE;
$wlTgBotCode = str_replace(
    ['__API_BASE__', '__USER_TOKEN__'],
    ['https://' . $server, $wlTokenForExample],
    $wlTgBotCode
);

$wlTgWebhookCode = <<<'TGWEBHOOKEXAMPLE'
<?php
// telegram-payment-webhook.php
// Isi URL ko NeoPay dashboard -> API Details -> Webhook URL me save karein.
// Payment success/fail hote hi NeoPay yahan POST karega, aur yeh script
// seedha usi Telegram user ko turant message bhej degi.

$BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN';

$payload = json_decode(file_get_contents('php://input'), true);

$remark1 = $payload['remark1'] ?? '';
$status  = $payload['status'] ?? '';
$amount  = $payload['amount'] ?? '';
$orderId = $payload['order_id'] ?? '';

// remark1 was set to "tg_chat_<chatId>" when the order was created -
// pulling the chat_id back out of it, no database lookup needed.
if (preg_match('/^tg_chat_(\d+)$/', $remark1, $m)) {
    $chatId = $m[1];

    $text = (strtolower($status) === 'success')
        ? "Payment Successful!\nAmount: Rs. {$amount}\nOrder: {$orderId}"
        : "Payment Failed / Cancelled.\nOrder: {$orderId}\nKripya dobara try karein: /pay {$amount}";

    $ch = curl_init("https://api.telegram.org/bot{$BOT_TOKEN}/sendMessage");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => ['chat_id' => $chatId, 'text' => $text],
        CURLOPT_TIMEOUT => 15,
    ]);
    curl_exec($ch);
    curl_close($ch);
}

http_response_code(200); // NeoPay ko bata dein ki mil gaya
TGWEBHOOKEXAMPLE;

?>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;600&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .api-wrap{padding:20px;max-width:1300px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .api-head{margin-bottom:22px}
    .api-head h1{font-size:1.55rem;font-weight:800;margin:0;color:#fff;display:flex;align-items:center;gap:10px}
    .api-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .api-head p{font-size:.85rem;color:rgba(255,255,255,.45);margin:4px 0 0 48px}

    .glass-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;margin-bottom:20px;
    }
    .card-header{
        padding:18px 22px;border-bottom:1px solid rgba(255,255,255,.07);
        display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;
    }
    .card-header h3{font-size:1.05rem;font-weight:700;margin:0;color:#fff;display:flex;align-items:center;gap:8px}
    .card-header h3 i{color:var(--p)}
    .card-body{padding:22px}

    .form-grid{display:grid;grid-template-columns:1fr auto;gap:16px;align-items:end}
    @media(max-width:640px){.form-grid{grid-template-columns:1fr}}
    .form-label{display:block;font-size:.78rem;font-weight:600;color:rgba(255,255,255,.5);margin-bottom:7px;text-transform:uppercase;letter-spacing:.3px}
    .form-control{
        width:100%;background:rgba(255,255,255,.05);border:1.5px solid rgba(255,255,255,.1);border-radius:10px;
        padding:11px 13px;color:#fff;font-size:.86rem;outline:none;transition:.2s;font-family:'JetBrains Mono',monospace;
    }
    .form-control:focus{border-color:var(--p);background:rgba(108,99,255,.08);box-shadow:0 0 0 3px rgba(108,99,255,.15)}
    .form-control::placeholder{color:rgba(255,255,255,.3);font-family:'Inter',sans-serif}
    /* Readonly fields (API token, endpoint URLs, payload examples) were
       rendering with a white background on some devices — same browser
       autofill/native-styling override seen elsewhere. Pinned with
       !important + the autofill inset-shadow trick so it can't happen here. */
    .api-wrap .form-control[readonly],
    .api-wrap input.form-control[readonly],
    .api-wrap textarea.form-control[readonly]{
        background:rgba(255,255,255,.05) !important;color:rgba(255,255,255,.7) !important;
        -webkit-text-fill-color:rgba(255,255,255,.7) !important;opacity:1 !important;cursor:default;
    }
    .api-wrap input:-webkit-autofill,
    .api-wrap input:-webkit-autofill:hover,
    .api-wrap input:-webkit-autofill:focus{
        -webkit-text-fill-color:#fff !important;
        -webkit-box-shadow:0 0 0 1000px #14141f inset !important;
        box-shadow:0 0 0 1000px #14141f inset !important;
    }
    textarea.form-control{font-size:.8rem;line-height:1.6;resize:vertical}

    .btn-primary-cta{
        background:var(--g);border:none;color:#fff;padding:11px 22px;border-radius:10px;
        font-size:.85rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);white-space:nowrap;
    }
    .btn-primary-cta:hover{transform:translateY(-1px);box-shadow:0 10px 24px rgba(108,99,255,.45);color:#fff}

    .copy-wrap{position:relative}
    .copy-wrap .copy-btn{
        position:absolute;right:8px;top:50%;transform:translateY(-50%);background:rgba(255,255,255,.08);
        border:1px solid rgba(255,255,255,.12);color:#fff;width:32px;height:32px;border-radius:8px;
        cursor:pointer;display:flex;align-items:center;justify-content:center;transition:.2s;font-size:.78rem;
    }
    .copy-wrap .copy-btn:hover{background:var(--g);border-color:transparent}
    .copy-wrap .copy-btn.copied{background:var(--success);border-color:transparent;color:#0a0a12}
    .copy-wrap .form-control{padding-right:46px}
    .copy-wrap textarea ~ .copy-btn{top:20px;transform:none}

    .note-line{font-size:.76rem;color:rgba(255,255,255,.4);margin-top:8px;display:flex;gap:6px;align-items:flex-start}
    .wl-step-card{display:flex;gap:14px;margin-bottom:16px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:12px;padding:14px 16px;font-size:.85rem;color:rgba(255,255,255,.75);line-height:1.5}
    .wl-step-num{width:28px;height:28px;border-radius:50%;background:var(--g);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.85rem;flex-shrink:0}
    .note-line.danger{color:#ffb3c1}
    .note-line i{margin-top:2px;flex-shrink:0}

    /* API Mode toggle */
    .mode-row{display:flex;gap:10px;max-width:420px}
    .mode-box{
        flex:1;text-align:center;padding:16px;border-radius:14px;border:1.5px solid rgba(255,255,255,.1);
        cursor:pointer;font-weight:700;font-size:.9rem;transition:.2s;background:rgba(255,255,255,.03);color:rgba(255,255,255,.6);
    }
    .mode-box:hover{border-color:rgba(255,255,255,.25)}
    .mode-box.active{border-color:var(--p);background:rgba(108,99,255,.1);color:#fff;box-shadow:0 0 0 1px rgba(108,99,255,.3)}

    /* API docs tabs */
    .api-tabs{
        display:flex;gap:6px;background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);
        padding:4px;border-radius:12px;margin-bottom:20px;
        overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:thin;max-width:100%;
    }
    .api-tab{
        flex:0 0 auto;white-space:nowrap;text-align:center;padding:9px 14px;border-radius:9px;font-size:.82rem;font-weight:700;color:rgba(255,255,255,.5);
        cursor:pointer;transition:.2s;
    }
    .api-tab:hover{color:#fff}
    .api-tab.active{background:var(--g);color:#fff;box-shadow:0 4px 14px rgba(108,99,255,.35)}
    .api-doc-panel{display:none}
    .api-doc-panel.active{display:block;animation:fadeUp .3s ease both}
    @keyframes fadeUp{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}

    .doc-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px}
    @media(max-width:768px){.doc-grid{grid-template-columns:1fr}}
    .doc-block-label{display:flex;align-items:center;gap:7px;font-size:.78rem;font-weight:700;color:rgba(255,255,255,.55);margin-bottom:8px;text-transform:uppercase;letter-spacing:.3px}
    .doc-block-label.ok{color:var(--success)}
    .doc-block-label.err{color:var(--danger)}
</style>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<div class="api-wrap">
    <div class="api-head">
        <h1><span class="icn"><i class="fas fa-code"></i></span>API Details</h1>
        <p>Your API token, webhook, and integration documentation</p>
    </div>

    <div class="glass-card">
        <div class="card-header"><h3><i class="fas fa-key"></i> API Token</h3></div>
        <div class="card-body">
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="form-grid">
                    <div>
                        <label class="form-label">Your API Token</label>
                        <div class="copy-wrap">
                            <input type="text" id="apiTokenInput" placeholder="Click Generate Button for API Token" value="<?php echo htmlspecialchars($userdata['user_token'], ENT_QUOTES, 'UTF-8'); ?>" class="form-control" readonly>
                            <button type="button" class="copy-btn" onclick="copyField('apiTokenInput', this)"><i class="fas fa-copy"></i></button>
                        </div>
                    </div>
                    <button type="submit" name="get_api_token" class="btn-primary-cta"><i class="fas fa-arrows-rotate"></i> Generate Token</button>
                </div>
                <div class="note-line danger"><i class="fas fa-triangle-exclamation"></i> Regenerating replaces your existing token everywhere (orders, reports, all connected gateways) — update any app using the old token.</div>
            </form>
        </div>
    </div>

    <?php
    if (isset($_POST['set_api_mode'])) {
        $newMode = ($_POST['api_mode'] === 'test') ? 'test' : 'live';
        $stmt = $conn->prepare("UPDATE users SET api_mode = ? WHERE id = ?");
        if ($stmt !== false) {
            $stmt->bind_param("si", $newMode, $userdata['id']);
            $stmt->execute();
            $stmt->close();
            echo '<script>Swal.fire({title:"Saved!", text:"API Mode updated to ' . ucfirst($newMode) . '.", icon:"success", background:"#14141f", color:"#fff"}).then(()=>{ window.location.href = "apidetails"; });</script>';
        } else {
            echo '<script>Swal.fire({title:"Setup needed", text:"Please run the latest sql/upgrade.sql first.", icon:"error", background:"#14141f", color:"#fff"});</script>';
        }
    }
    $currentApiMode = $userdata['api_mode'] ?? 'live';
    ?>

    <div class="glass-card">
        <div class="card-header"><h3><i class="fas fa-toggle-on"></i> API Mode</h3></div>
        <div class="card-body">
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <div class="mode-row">
                    <label style="flex:1;margin:0">
                        <input type="radio" name="api_mode" value="live" <?= $currentApiMode === 'live' ? 'checked' : '' ?> style="display:none;" class="api-mode-radio">
                        <div class="mode-box <?= $currentApiMode === 'live' ? 'active' : '' ?>" data-mode="live">🌐 Live</div>
                    </label>
                    <label style="flex:1;margin:0">
                        <input type="radio" name="api_mode" value="test" <?= $currentApiMode === 'test' ? 'checked' : '' ?> style="display:none;" class="api-mode-radio">
                        <div class="mode-box <?= $currentApiMode === 'test' ? 'active' : '' ?>" data-mode="test">🧪 Test</div>
                    </label>
                </div>
                <div class="note-line"><i class="fas fa-circle-info"></i> Test Mode lets you simulate payments without moving real money.</div>
                <div style="margin-top:16px">
                    <button type="submit" name="set_api_mode" class="btn-primary-cta"><i class="fas fa-floppy-disk"></i> Save API Mode</button>
                </div>
            </form>
        </div>
    </div>

    <div class="glass-card">
        <div class="card-header"><h3><i class="fas fa-satellite-dish"></i> Webhook URL</h3></div>
        <div class="card-body">
            <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <div class="form-grid">
                    <div>
                        <label class="form-label">Webhook URL</label>
                        <input type="text" name="webhook_url" placeholder="Enter Your Webhook URL" value="<?php echo htmlspecialchars($userdata['callback_url'], ENT_QUOTES, 'UTF-8'); ?>" class="form-control" required>
                    </div>
                    <button type="submit" name="update_webhook" class="btn-primary-cta"><i class="fas fa-cloud-arrow-up"></i> Update URL</button>
                </div>
            </form>

            <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" style="margin-top:14px">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <button type="submit" name="test_webhook" class="btn-primary-cta" style="background:linear-gradient(135deg,#25D366,#128C7E)"><i class="fas fa-paper-plane"></i> Test Webhook</button>
            </form>

            <?php if ($testWebhookResult): ?>
                <div style="margin-top:14px;border-radius:10px;padding:14px 16px;font-size:.85rem;<?php echo $testWebhookResult['ok'] ? 'background:rgba(37,211,102,.1);color:#25D366' : 'background:rgba(255,101,132,.1);color:#ff6584'; ?>">
                    <?php if ($testWebhookResult['ok']): ?>
                        <i class="fas fa-circle-check"></i> Webhook sahi kaam kar raha hai! (HTTP <?php echo $testWebhookResult['http_code']; ?>)
                    <?php else: ?>
                        <i class="fas fa-circle-xmark"></i> Webhook fail ho gaya: <?php echo htmlspecialchars($testWebhookResult['response']); ?>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($webhookDeliveries)): ?>
            <div style="margin-top:22px">
                <div class="note-line" style="font-weight:700;color:#fff;margin-bottom:10px"><i class="fas fa-scroll"></i> Recent Deliveries</div>
                <?php foreach ($webhookDeliveries as $d): ?>
                    <div style="display:flex;justify-content:space-between;align-items:center;background:rgba(255,255,255,.03);border-radius:8px;padding:10px 14px;margin-bottom:8px;font-size:.82rem">
                        <span><?php echo htmlspecialchars($d['event']); ?><?php if ($d['order_id']) echo ' <span style="color:rgba(255,255,255,.4)">#' . htmlspecialchars($d['order_id']) . '</span>'; ?></span>
                        <span style="font-weight:700;<?php echo $d['status'] === 'Delivered' ? 'color:#25D366' : 'color:#ff6584'; ?>">
                            <i class="fas fa-<?php echo $d['status'] === 'Delivered' ? 'circle-check' : 'circle-xmark'; ?>"></i> <?php echo $d['status']; ?>
                        </span>
                    </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="glass-card">
        <div class="card-header"><h3><i class="fas fa-book"></i> API Documentation</h3></div>
        <div class="card-body">
            <div class="api-tabs">
                <div class="api-tab active" data-doc="create">Create Order</div>
                <div class="api-tab" data-doc="check">Check Status</div>
                <div class="api-tab" data-doc="webhook">Webhook</div>
                <div class="api-tab" data-doc="whitelabel">White-Label Guide</div>
                <div class="api-tab" data-doc="telegram">Telegram Bot</div>
            </div>

            <!-- Create Order API -->
            <div class="api-doc-panel active" id="doc-create">
                <label class="form-label">Endpoint URL</label>
                <div class="copy-wrap">
                    <input type="text" id="createOrderUrl" value="https://<?php echo htmlspecialchars($server, ENT_QUOTES, 'UTF-8'); ?>/api/create-order" class="form-control" readonly>
                    <button type="button" class="copy-btn" onclick="copyField('createOrderUrl', this)"><i class="fas fa-copy"></i></button>
                </div>
                <div class="note-line danger"><i class="fas fa-clock"></i> Order timeout is 30 minutes — the order is automatically marked Failed after that.</div>

                <label class="form-label" style="margin-top:18px">Form-Encoded Payload (application/x-www-form-urlencoded)</label>
                <div class="copy-wrap">
                    <textarea id="createOrderPayload" class="form-control" style="height:190px" readonly>{
  "customer_mobile": "9234456535",
  "user_token": "<?php echo htmlspecialchars($userdata['user_token'], ENT_QUOTES, 'UTF-8'); ?>",
  "amount": "1",
  "order_id": "8787772321800",
  "redirect_url": "your website url",
  "remark1": "testremark",
  "remark2": "testremark2"
}</textarea>
                    <button type="button" class="copy-btn" onclick="copyField('createOrderPayload', this)"><i class="fas fa-copy"></i></button>
                </div>

                <div class="doc-grid">
                    <div>
                        <div class="doc-block-label ok"><i class="fas fa-circle-check"></i> Success Response</div>
                        <textarea class="form-control" style="height:200px" readonly>{
    "status": true,
    "message": "Order Created Successfully",
    "result": {
        "orderId": "1234561705047510",
        "payment_url": "https://yourwebsite.com/payment/pay.php?data=MTIzNDU2MTcwNTA0NzUxMkyNTIy"
    }
}</textarea>
                    </div>
                    <div>
                        <div class="doc-block-label err"><i class="fas fa-circle-xmark"></i> Failed Response</div>
                        <textarea class="form-control" style="height:200px" readonly>{
    "status": false,
    "message": "Order_id Already Exist"
}</textarea>
                    </div>
                </div>
            </div>

            <!-- Check Order Status API -->
            <div class="api-doc-panel" id="doc-check">
                <label class="form-label">Endpoint URL</label>
                <div class="copy-wrap">
                    <input type="text" id="checkOrderUrl" value="https://<?php echo htmlspecialchars($server, ENT_QUOTES, 'UTF-8'); ?>/api/check-order-status" class="form-control" readonly>
                    <button type="button" class="copy-btn" onclick="copyField('checkOrderUrl', this)"><i class="fas fa-copy"></i></button>
                </div>

                <label class="form-label" style="margin-top:18px">Form-Encoded Payload (application/x-www-form-urlencoded)</label>
                <div class="copy-wrap">
                    <textarea id="checkOrderPayload" class="form-control" style="height:120px" readonly>{
    "user_token": "2048f66bef68633fa3262d7a398ab577",
    "order_id": "8052313697"
}</textarea>
                    <button type="button" class="copy-btn" onclick="copyField('checkOrderPayload', this)"><i class="fas fa-copy"></i></button>
                </div>

                <div class="doc-grid">
                    <div>
                        <div class="doc-block-label ok"><i class="fas fa-circle-check"></i> Success Response</div>
                        <textarea class="form-control" style="height:210px" readonly>{
    "status": "COMPLETED",
    "message": "Transaction Successfully",
    "result": {
        "txnStatus": "COMPLETED",
        "resultInfo": "Transaction Success",
        "orderId": "784525sdD",
        "status": "SUCCESS",
        "amount": "1",
        "date": "2024-01-12 13:22:08",
        "utr": "454525454245"
    }
}</textarea>
                    </div>
                    <div>
                        <div class="doc-block-label err"><i class="fas fa-circle-xmark"></i> Failed Response</div>
                        <textarea class="form-control" style="height:210px" readonly>{
    "status": "ERROR",
    "message": "Error Message"
}</textarea>
                    </div>
                </div>
            </div>

            <!-- Webhook -->
            <div class="api-doc-panel" id="doc-webhook">
                <div class="note-line"><i class="fas fa-circle-info"></i> Har payment success/failed hone par aapke saved <b>Webhook URL</b> par yeh payload POST hota hai. Aapka server 10 second ke andar HTTP 200 return kare.</div>

                <label class="form-label" style="margin-top:18px">Payload (Success)</label>
                <div class="copy-wrap">
                    <textarea id="webhookPayloadSuccess" class="form-control" style="height:190px" readonly>{
    "order_id": "Abc123",
    "txn_id": "GURU66f10bd3c1f28",
    "status": "Success",
    "amount": "1000.00",
    "pay_amount": "1000.00",
    "utr": "434554555",
    "remark1": "your_custom_remark"
}</textarea>
                    <button type="button" class="copy-btn" onclick="copyField('webhookPayloadSuccess', this)"><i class="fas fa-copy"></i></button>
                </div>

                <label class="form-label" style="margin-top:18px">Payload (Failed)</label>
                <div class="copy-wrap">
                    <textarea id="webhookPayloadFailed" class="form-control" style="height:130px" readonly>{
    "order_id": "Abc123",
    "status": "Failed",
    "amount": "1000.00",
    "reason": "Payment not received"
}</textarea>
                    <button type="button" class="copy-btn" onclick="copyField('webhookPayloadFailed', this)"><i class="fas fa-copy"></i></button>
                </div>

                <label class="form-label" style="margin-top:18px">Trigger a Test Delivery via API</label>
                <div class="copy-wrap">
                    <input type="text" id="testWebhookUrl" value="https://<?php echo htmlspecialchars($server, ENT_QUOTES, 'UTF-8'); ?>/api/test-webhook" class="form-control" readonly>
                    <button type="button" class="copy-btn" onclick="copyField('testWebhookUrl', this)"><i class="fas fa-copy"></i></button>
                </div>
                <div class="note-line" style="margin-top:10px">POST <code>user_token</code> to this endpoint to send a real test payload to your saved Webhook URL (same as the "Test Webhook" button above) - useful for automated checks from your own deploy pipeline.</div>

                <div class="doc-grid" style="margin-top:14px">
                    <div>
                        <div class="doc-block-label ok"><i class="fas fa-circle-check"></i> Success Response</div>
                        <textarea class="form-control" style="height:150px" readonly>{
    "status": true,
    "message": "Test webhook delivered successfully",
    "http_code": 200,
    "response": "OK"
}</textarea>
                    </div>
                    <div>
                        <div class="doc-block-label err"><i class="fas fa-circle-xmark"></i> Failed Response</div>
                        <textarea class="form-control" style="height:150px" readonly>{
    "status": false,
    "message": "Webhook delivery failed",
    "http_code": 302,
    "response": "cURL error / redirect"
}</textarea>
                    </div>
                </div>

                <div class="note-line" style="margin-top:14px"><i class="fas fa-triangle-exclamation"></i> HTTP 200 milna sirf yeh confirm karta hai ki URL live hai aur POST accept kar raha hai - apne server ke logs check karke confirm karein ki payload sahi tarah se process ho raha hai.</div>
            </div>

            <!-- White-Label Guide -->
            <div class="api-doc-panel" id="doc-whitelabel">
                <div class="note-line" style="background:rgba(37,211,102,.08);border-color:rgba(37,211,102,.25);color:#25D366">
                    <i class="fas fa-circle-check"></i> Isme aapko koi DNS record, SSL certificate, ya cPanel setup <b>bilkul nahi karna</b> - poora payment page aapke apne server pe, aapke apne code me chalta hai. Sirf 3 API calls se poora kaam ho jaata hai.
                </div>

                <h4 style="margin:22px 0 10px;font-size:.95rem">Poora Flow (3 Steps)</h4>

                <div class="wl-step-card">
                    <div class="wl-step-num">1</div>
                    <div>
                        <b>Order banayein</b> - <code>/api/create-order</code> ko call karein (upar "Create Order" tab dekhein). Response me ek <code>upi_string</code> field milegi (sirf FamPay-connected accounts ke liye abhi) - yehi wo cheez hai jisse QR banega.
                    </div>
                </div>
                <div class="wl-step-card">
                    <div class="wl-step-num">2</div>
                    <div>
                        <b>QR khud dikhayein</b> - <code>upi_string</code> ko kisi bhi QR-generation library (JS: qrcodejs, PHP: endroid/qr-code, ya koi bhi) me daal dein. Yeh QR <b>seedha aapke page pe</b> banega - customer ko kabhi NeoPay ka naam nahi dikhega, kyunki koi NeoPay page load hi nahi hota.
                    </div>
                </div>
                <div class="wl-step-card">
                    <div class="wl-step-num">3</div>
                    <div>
                        <b>Payment confirm hone ka pata lagayein (2 tareeke, dono use karein):</b>
                        <ul style="margin:8px 0 0 18px;padding:0;font-size:.85rem;color:rgba(255,255,255,.6)">
                            <li><b>Webhook (turant, recommended)</b> - apne server pe ek chhota endpoint banayein jo POST accept kare, aur us URL ko upar "Webhook" tab me save kar dein. Payment confirm hote hi NeoPay khud aapko batayega.</li>
                            <li><b>Polling (safety net)</b> - <code>/api/check-order-status</code> ko har 3 second me call karte rahein jab tak status "SUCCESS" ya "FAILURE" na aa jaaye. Webhook miss ho jaaye to yeh backup ka kaam karega.</li>
                        </ul>
                    </div>
                </div>

                <h4 style="margin:26px 0 10px;font-size:.95rem">Poora Example (PHP)</h4>
                <div class="copy-wrap">
                    <textarea id="wlPhpExample" class="form-control" style="height:520px;font-size:.78rem" readonly><?php echo htmlspecialchars($wlPhpExampleCode, ENT_QUOTES, 'UTF-8'); ?></textarea>
                    <button type="button" class="copy-btn" onclick="copyField('wlPhpExample', this)"><i class="fas fa-copy"></i></button>
                </div>

                <h4 style="margin:26px 0 10px;font-size:.95rem">Webhook ka Simple Example (jo aapke server pe rahega)</h4>
                <div class="copy-wrap">
                    <textarea id="wlWebhookExample" class="form-control" style="height:180px;font-size:.78rem" readonly><?php echo htmlspecialchars($wlWebhookExampleCode, ENT_QUOTES, 'UTF-8'); ?></textarea>
                    <button type="button" class="copy-btn" onclick="copyField('wlWebhookExample', this)"><i class="fas fa-copy"></i></button>
                </div>

                <div class="note-line" style="margin-top:18px"><i class="fas fa-circle-info"></i> Abhi <code>upi_string</code> sirf <b>FamPay-connected accounts</b> ke liye milta hai. Doosre gateways ke liye response me sirf <code>payment_url</code> milega (NeoPay ke apne payment page ka link) - use naye tab me open kar sakte hain button ke through.</div>
            </div>

            <!-- Telegram Bot Guide -->
            <div class="api-doc-panel" id="doc-telegram">
                <div class="note-line" style="background:rgba(37,211,102,.08);border-color:rgba(37,211,102,.25);color:#25D366">
                    <i class="fas fa-circle-check"></i> Bot seedha <b>QR ki photo</b> bhejega (koi link nahi), aur payment confirm hote hi khud user ko message karega - customer ko kabhi bot chhod ke kahi jaane ki zaroorat nahi.
                </div>

                <h4 style="margin:22px 0 10px;font-size:.95rem">Poora Flow</h4>
                <div class="wl-step-card">
                    <div class="wl-step-num">1</div>
                    <div>User bot ko <code>/pay 100</code> jaisa message bhejta hai (Telegram apka webhook ping karta hai).</div>
                </div>
                <div class="wl-step-card">
                    <div class="wl-step-num">2</div>
                    <div>Bot NeoPay se order banata hai - <b>chat_id ko <code>remark1</code> field me daal dete hain</b> (jaise <code>tg_chat_123456</code>), taaki baad me webhook aane par pata chale kis user ko reply karna hai, koi database rakhne ki zaroorat nahi.</div>
                </div>
                <div class="wl-step-card">
                    <div class="wl-step-num">3</div>
                    <div>Bot <code>upi_string</code> se ek QR <b>image URL</b> banata hai (<code>api.qrserver.com</code> use karke), aur Telegram ke <code>sendPhoto</code> API ko seedha wahi URL de deta hai - Telegram khud image fetch karke user ko photo ke roop me bhej deta hai.</div>
                </div>
                <div class="wl-step-card">
                    <div class="wl-step-num">4</div>
                    <div>Payment hote hi NeoPay ka webhook aapke server pe POST karta hai. Payload me wahi <code>remark1</code> (<code>tg_chat_123456</code>) wapas milta hai - usse chat_id nikal ke Telegram ko <code>sendMessage</code> se seedha "Payment Successful!" bhej dete hain.</div>
                </div>

                <h4 style="margin:26px 0 10px;font-size:.95rem">1) Bot Webhook - QR Photo Bhejta Hai</h4>
                <div class="copy-wrap">
                    <textarea id="wlTgBotExample" class="form-control" style="height:480px;font-size:.78rem" readonly><?php echo htmlspecialchars($wlTgBotCode, ENT_QUOTES, 'UTF-8'); ?></textarea>
                    <button type="button" class="copy-btn" onclick="copyField('wlTgBotExample', this)"><i class="fas fa-copy"></i></button>
                </div>

                <h4 style="margin:26px 0 10px;font-size:.95rem">2) Payment Webhook - Turant Confirmation Bhejta Hai</h4>
                <div class="copy-wrap">
                    <textarea id="wlTgWebhookExample" class="form-control" style="height:320px;font-size:.78rem" readonly><?php echo htmlspecialchars($wlTgWebhookCode, ENT_QUOTES, 'UTF-8'); ?></textarea>
                    <button type="button" class="copy-btn" onclick="copyField('wlTgWebhookExample', this)"><i class="fas fa-copy"></i></button>
                </div>

                <div class="note-line" style="margin-top:18px"><i class="fas fa-circle-info"></i> <code>YOUR_TELEGRAM_BOT_TOKEN</code> BotFather se milta hai (Telegram me <code>@BotFather</code> ko message karke naya bot banayein). Dono script me daalna hoga.</div>
                <div class="note-line"><i class="fas fa-circle-info"></i> Bot Webhook set karne ka command (ek baar): <code>https://api.telegram.org/bot&lt;BOT_TOKEN&gt;/setWebhook?url=https://yoursite.com/telegram-webhook.php</code></div>
            </div>
        </div>
    </div>
</div>

<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="./assets/js/scripts/dashboard_1_demo.js" type="text/javascript"></script>
<script src="assets/js/app.min.js" type="text/javascript"></script>
<script>
    document.querySelectorAll('.mode-box').forEach(function(box){
        box.addEventListener('click', function(){
            document.querySelectorAll('.mode-box').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            this.closest('label').querySelector('.api-mode-radio').checked = true;
        });
    });

    document.querySelectorAll('.api-tab').forEach(function(tab){
        tab.addEventListener('click', function(){
            document.querySelectorAll('.api-tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.api-doc-panel').forEach(p => p.classList.remove('active'));
            this.classList.add('active');
            document.getElementById('doc-' + this.dataset.doc).classList.add('active');
        });
    });

    function copyField(id, btn) {
        var el = document.getElementById(id);
        el.select();
        el.setSelectionRange(0, 999999);
        navigator.clipboard.writeText(el.value);
        var original = btn.innerHTML;
        btn.classList.add('copied');
        btn.innerHTML = '<i class="fas fa-check"></i>';
        setTimeout(function(){ btn.classList.remove('copied'); btn.innerHTML = original; }, 1200);
    }
</script>
</body>
</html>
