<?php
// ==========================================
// POPUP V2 - LIBRARY MODE
// ==========================================

// Your API Token
$apiToken = '0020a9f557233c'; 
$api_key = 'sk_live_558d0ee83d2d585e3cf436814a7a9557';

// Global state to store data between functions
global $IP_POPUP_STATE;
$IP_POPUP_STATE = [
    'ip' => '',
    'details' => null,
    'needs_proxy' => false,
    'checked' => false
];

// Helper: Get Real IP
if (!function_exists('get_safe_user_ip')) {
    function get_safe_user_ip() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($ipList[0]);
        } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
            return $_SERVER['REMOTE_ADDR'];
        }
        return '127.0.0.1';
    }
}

/**
 * Checks IP location and determines if access is allowed.
 * @param string $remark Optional remark for tracking (unused in this function, but kept for consistency)
 * @return bool True if access is granted, False if proxy is needed (IN/BD).
 */
if (!function_exists('checkIpAccess')) {
    function checkIpAccess($remark = '') {
        global $apiToken, $IP_POPUP_STATE;

        // 1. Get IP
        $ip = get_safe_user_ip();
        $IP_POPUP_STATE['ip'] = $ip;

        // 2. If no token, fail safely (or assume access denied to force config)
        if (empty($apiToken) || $apiToken === 'YOUR_IPINFO_ACCESS_TOKEN') {
            return false;
        }

        // 3. Fetch IP Details
        $url = "https://ipinfo.io/{$ip}?token={$apiToken}";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode === 200 && $response) {
            $details = json_decode($response, true);
            $IP_POPUP_STATE['details'] = $details;
            
            // 4. Check Restricted Countries (IN, BD)
            $country = $details['country'] ?? '';
            if (in_array($country, ['IN', 'BD'])) {
                $IP_POPUP_STATE['needs_proxy'] = true;
            } else {
                $IP_POPUP_STATE['needs_proxy'] = false;
            }
        } else {
            // If API fails, you might want to default to Allow or Block. 
            // Here we default to Allow to prevent blocking valid users on API error.
            $IP_POPUP_STATE['needs_proxy'] = false; 
        }

        $IP_POPUP_STATE['checked'] = true;

        // Return TRUE if NO proxy is needed (Access Granted)
        // Return FALSE if proxy IS needed (Access Denied)
        return !$IP_POPUP_STATE['needs_proxy'];
    }
}

/**
 * Generates and displays the Proxy Popup HTML.
 * @param string $remark The remark string to send to the proxy API.
 */
if (!function_exists('showProxyPopup')) {
    function showProxyPopup($remark = 'default') {
        global $IP_POPUP_STATE, $api_key;

        // Ensure checkIpAccess was called
        if (!$IP_POPUP_STATE['checked']) {
            checkIpAccess($remark);
        }

        // If Access is actually allowed, we shouldn't show the popup, 
        // but if this function is forced called, we proceed or return.
        // Uncomment next line if you want to strictly prevent showing it for allowed IPs:
        // if (!$IP_POPUP_STATE['needs_proxy']) return;

        $details = $IP_POPUP_STATE['details'];
        $ip = $IP_POPUP_STATE['ip'];
        $proxyData = null;
        $proxyError = null;

        // 1. Fetch Proxy Credentials
        // Updated URL with remark and ip parameters
        $encodedRemark = urlencode($remark);
        $encodedIp = urlencode($ip);
        
        $proxyApiUrl = "https://somtek.site/Somnath/api/v1/index.php?api_key={$api_key}&action=generate_auth&remark={$encodedRemark}&ip={$encodedIp}";
        
        $ch2 = curl_init();
        curl_setopt($ch2, CURLOPT_URL, $proxyApiUrl);
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch2, CURLOPT_TIMEOUT, 8);
        curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
        $proxyResponse = curl_exec($ch2);
        curl_close($ch2);
        
        $proxyResult = json_decode($proxyResponse, true);
        
        if (isset($proxyResult['status']) && $proxyResult['status'] === 'success' && !empty($proxyResult['data']['proxies'])) {
            $proxyString = $proxyResult['data']['proxies'][0];
            $parts = explode(':', $proxyString);
            $proxyData = [
                'full' => $proxyString,
                'host' => $parts[0] ?? '',
                'port' => $parts[1] ?? '',
                'user' => $parts[2] ?? '',
                'pass' => $parts[3] ?? ''
            ];
        } else {
            $proxyError = $proxyResult['message'] ?? "No proxies available.";
        }

        // 2. Output HTML
        // Note: We use unique IDs/Classes to avoid conflicts, scoped styles included.
?>
<!-- START OF PROXY POPUP -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    /* Scoped Styles for Popup V2 - Fixed Text Sizes */
    #pv2-overlay {
        font-family: 'Inter', system-ui, -apple-system, sans-serif;
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background-color: rgba(15, 15, 19, 0.92);
        backdrop-filter: blur(6px);
        z-index: 999999;
        display: flex; justify-content: center; align-items: center;
        opacity: 0; visibility: hidden; animation: pv2-fade-in 0.3s forwards;
        
        /* Force base text settings to prevent auto-scaling */
        font-size: 16px; 
        line-height: 1.5;
        -webkit-text-size-adjust: 100%;
    }
    @keyframes pv2-fade-in { to { opacity: 1; visibility: visible; } }

    .pv2-card {
        /* Responsive Width: 90% of screen width, but cap at 400px */
        width: 90vw; 
        max-width: 400px;
        
        /* Responsive Height: Ensure it doesn't overflow screen height */
        max-height: 90vh;
        overflow-y: auto; /* Scroll if content is too tall */
        
        background: linear-gradient(145deg, #1e1e24, #141419);
        border: 1px solid rgba(255, 255, 255, 0.08);
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.7);
        border-radius: 16px; padding: 24px;
        color: white; text-align: left; position: relative;
    }
    /* Hide scrollbar for clean UI */
    .pv2-card::-webkit-scrollbar { width: 4px; }
    .pv2-card::-webkit-scrollbar-thumb { background: #333; border-radius: 4px; }
    
    .pv2-card * { box-sizing: border-box; }

    /* Close Button Styles */
    .pv2-close {
        position: absolute; top: 15px; right: 15px;
        background: none; border: none;
        color: #777; font-size: 24px; line-height: 1;
        cursor: pointer; transition: color 0.2s;
        z-index: 10; padding: 5px;
    }
    .pv2-close:hover { color: #fff; }

    .pv2-header { text-align: center; margin-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.05); padding-bottom: 15px; }
    
    /* Fixed sizes */
    .pv2-title { font-size: 20px; font-weight: 700; margin: 0; color: #fff; }
    .pv2-sub { font-size: 12px; text-transform: uppercase; letter-spacing: 1px; color: #ff4757; }

    /* Adjust sizing for smaller screens/DPI scaling */
    @media (max-width: 480px) {
        .pv2-card { padding: 20px; width: 92vw; } /* Less padding, wider card on mobile */
        /* Note: Text sizes remain FIXED here now */
    }

    .pv2-alert {
        background: rgba(255, 71, 87, 0.1); border: 1px solid rgba(255, 71, 87, 0.3);
        color: #ffbdc3; padding: 12px; border-radius: 8px; text-align: center; margin-bottom: 20px; 
        font-size: 14px;
    }

    .pv2-field {
        background: rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.1);
        border-radius: 8px; padding: 10px; margin-bottom: 8px;
        display: flex; justify-content: space-between; align-items: center;
    }
    /* Fixed sizes for fields */
    .pv2-lbl { font-size: 11px; color: #888; display: block; margin-bottom: 2px; }
    .pv2-val { font-family: monospace; color: #eee; font-size: 15px; }
    .pv2-copy {
        background: transparent; border: 1px solid #444; color: #aaa;
        border-radius: 6px; padding: 6px 10px; cursor: pointer; transition: 0.2s;
    }
    .pv2-copy:hover { border-color: #00d2ff; color: #00d2ff; }

    .pv2-btn {
        width: 100%; padding: 14px; border: none; border-radius: 10px;
        color: white; font-weight: 600; cursor: pointer; margin-top: 12px;
        font-size: 15px; display: flex; align-items: center; justify-content: center; gap: 8px;
        transition: 0.2s;
    }
    .pv2-btn:hover { transform: translateY(-2px); filter: brightness(1.1); }
    .pv2-btn-super { background: linear-gradient(90deg, #ff9f43, #ff6b6b); }
    .pv2-btn-con { background: linear-gradient(90deg, #2ed573, #26de81); }
    .pv2-btn-opt { background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #ccc; font-size: 13px; padding: 10px; }

    .pv2-opts { margin-top: 15px; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 10px; }
    .pv2-opts-content { display: none; margin-top: 10px; gap: 8px; flex-direction: column; }
    .pv2-opts-content.show { display: flex; }
</style>

<div id="pv2-overlay">
    <div class="pv2-card">
        <!-- Close Button -->
        <button class="pv2-close" onclick="document.getElementById('pv2-overlay').style.display='none'">&times;</button>
        
        <div class="pv2-header">
            <span class="pv2-sub">Connct Proxy to Start Work</span>
            <h2 class="pv2-title">Connect Below Proxy</h2>
        </div>

        <div class="pv2-alert">
            Access from <strong><?php echo htmlspecialchars($details['country'] ?? 'Unknown'); ?></strong> requires a proxy.<br>
            <span style="font-size:12px; opacity:0.7;">Ref: <?php echo htmlspecialchars($remark); ?></span>
        </div>

        <?php if ($proxyData): ?>
            <div style="margin-bottom: 20px;">
                <div class="pv2-field">
                    <div><span class="pv2-lbl">Host/Server</span><span class="pv2-val" id="pv-h"><?php echo htmlspecialchars($proxyData['host']); ?></span></div>
                    <button class="pv2-copy" onclick="pv2Copy('pv-h')"><i class="fas fa-copy"></i></button>
                </div>
                <div class="pv2-field">
                    <div><span class="pv2-lbl">Port</span><span class="pv2-val" id="pv-p"><?php echo htmlspecialchars($proxyData['port']); ?></span></div>
                    <button class="pv2-copy" onclick="pv2Copy('pv-p')"><i class="fas fa-copy"></i></button>
                </div>
                <?php if(!empty($proxyData['user'])): ?>
                <div class="pv2-field">
                    <div><span class="pv2-lbl">User</span><span class="pv2-val" id="pv-u"><?php echo htmlspecialchars($proxyData['user']); ?></span></div>
                    <button class="pv2-copy" onclick="pv2Copy('pv-u')"><i class="fas fa-copy"></i></button>
                </div>
                <?php endif; ?>
                <?php if(!empty($proxyData['pass'])): ?>
                <div class="pv2-field">
                    <div><span class="pv2-lbl">Pass</span><span class="pv2-val" id="pv-pw"><?php echo htmlspecialchars($proxyData['pass']); ?></span></div>
                    <button class="pv2-copy" onclick="pv2Copy('pv-pw')"><i class="fas fa-copy"></i></button>
                </div>
                <?php endif; ?>
            </div>

            <button class="pv2-btn pv2-btn-super" onclick="pv2OpenSuper()">
                <i class="fas fa-rocket"></i> Open Super Proxy
            </button>
            <button class="pv2-btn pv2-btn-con" onclick="window.location.reload()">
                <i class="fas fa-check-circle"></i> I Have Connected
            </button>

            <div class="pv2-opts">
                <div style="cursor: pointer; color: #777; font-size: 13px; display: flex; justify-content: space-between;" onclick="document.getElementById('pv2-more').classList.toggle('show')">
                    <span>More Options</span> <i class="fas fa-chevron-down"></i>
                </div>
                <div id="pv2-more" class="pv2-opts-content">
                    <button class="pv2-btn pv2-btn-opt" onclick="window.open('https://somtek.site/support', '_blank')">Contact Support</button>
                    <button class="pv2-btn pv2-btn-opt" onclick="window.location.reload()">Generate New Proxy</button>
                </div>
            </div>

        <?php else: ?>
            <div style="text-align: center; color: #ff4757; padding: 20px;">
                <i class="fas fa-wifi fa-2x"></i><br><br>
                <?php echo htmlspecialchars($proxyError ?: "Service unavailable"); ?>
            </div>
            <button class="pv2-btn pv2-btn-opt" onclick="window.location.reload()">Retry</button>
        <?php endif; ?>
    </div>
</div>

<script>
function pv2OpenSuper() {
    // Call this from your HTML/JS inside the WebView
    if (typeof Android !== 'undefined' && Android.openSuperProxy) {
        Android.openSuperProxy();
    } else {
        alert("Super Proxy interface not found. Ensure you are in the App.");
    }
}

function pv2Copy(id) {
    var txt = document.getElementById(id).innerText;
    navigator.clipboard.writeText(txt).then(() => {
        var btn = document.querySelector(`button[onclick="pv2Copy('${id}')"]`);
        btn.innerHTML = '<i class="fas fa-check"></i>';
        btn.style.color = '#2ed573'; btn.style.borderColor = '#2ed573';
        setTimeout(() => { 
            btn.innerHTML = '<i class="fas fa-copy"></i>';
            btn.style.color = '#aaa'; btn.style.borderColor = '#444';
        }, 1500);
    });
}
</script>
<!-- END OF PROXY POPUP -->
<?php
    }
}
?>