<?php
/*-----------------------------------------------*/
/*  EXTHEM.ES
/*  PREMIUM WORDRESS THEMES
/*
/*  STOP DON'T TRY EDIT
/*  IF YOU DON'T KNOW PHP 
/*
/*  As Errors In Your Themes
/*  Are Not The Responsibility
/*  Of The DEVELOPERS
/*  @EXTHEM.ES
/*  
/*  Follow Social Media Exthem.es
/*  Youtube : https://www.youtube.com/channel/UCpcZNXk6ySLtwRSBN6fVyLA
/*  Facebook : https://www.facebook.com/groups/exthem.es
/*  Twitter : https://x.com/bangreyblog
/*  Instagram : https://www.instagram.com/exthem.es/
/*  Telegram : https://t.me/exthemes_helps
/*  TikTok : https://www.tiktok.com/@exthemes
/*	More Premium Themes Visit Now On https://exthem.es/
/*-----------------------------------------------*/
if ( ! defined( 'ABSPATH' ) ) exit; 

/* 
add_action('admin_menu', function () {
    add_menu_page(
        'API Monitor',
        'API Monitor',
        'manage_options',
        'sc-check-api',
        'check_api_scrape_callback',
        'dashicons-chart-area',
        30
    );
});
 */
add_action('wp_ajax_sc_scrape_status', 'sc_scrape_status_callback');

function sc_scrape_status_callback() {
	
	$sc        = new StructurCode(); 
	$api_token = $sc->scrape_do_tokens();
    $api_url   = 'https://api.scrape.do/info?token=' . $api_token;

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $api_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
    ]);

    $response  = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    wp_send_json([
        'http' => $http_code,
        'data' => json_decode($response, true)
    ]);
}

function sc_mask_api_token($token) {
    if (strlen($token) < 10) return str_repeat('*', strlen($token));

    return substr($token, 0, 5)
        . ' ' . str_repeat('* ', 8)
        . substr($token, -4);
}

function check_api_scrape_callback() {
$sc        	= new StructurCode();  
// Ambil token dari pengaturan
$api_token = $sc->scrape_do_tokens();

// Flag apakah ada token
$has_token = !empty($api_token);

if ($has_token) {
    $masked = esc_html($sc->mask_api_token($api_token));
}

?>

<div class="wrap sc-wrap">
    <h2></h2> 
	<h1 class="sc-title" style="margin-bottom: 1rem;">
		<?php _e('API Token Monitor Dashboard', TEXT_DOMAIN); ?>
	</h1>
		
	<div class="sc-notification">
		⚠️
		<?php
		printf(
			/* translators: %s = Api Key link */
			esc_html__(
				'API Token for Sources Apk Extractor is blocked by Cloudflare. Please add your API token on %s.',
				TEXT_DOMAIN
			),
			'<a href="' . esc_url(admin_url('admin.php?page=_options&tab=20')) . '" target="_blank">' .
			esc_html__('API Key', TEXT_DOMAIN) .
			'</a>'
		);
		?>
	</div>

 

	
    <?php if ($has_token): ?>
        <div class="sc-card">

            <!-- API Token -->
            <p class="sc-api-label"><?php _e('Your API Token', TEXT_DOMAIN); ?></p>

            <div class="sc-api-box">
                <span class="sc-api-text"><?php echo $masked; ?></span>
                <span class="sc-api-copy" data-token="<?php echo esc_attr($api_token); ?>" onclick="scCopyToken(this)">
                    <!-- Copy Icon -->
                    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                        <path d="M12 6V3.9C12 3.06 12 2.64 11.84 2.32C11.69 2.04 11.46 1.81 11.18 1.66C10.86 1.5 10.44 1.5 9.6 1.5H3.9C3.06 1.5 2.64 1.5 2.32 1.66C2.04 1.81 1.81 2.04 1.66 2.32C1.5 2.64 1.5 3.06 1.5 3.9V9.6C1.5 10.44 1.5 10.86 1.66 11.18C1.81 11.46 2.04 11.69 2.32 11.84C2.64 12 3.06 12 3.9 12H6" stroke="#9ca3af" stroke-width="1.5" stroke-linecap="round"/>
                        <rect x="6" y="6" width="10.5" height="10.5" rx="2" stroke="#9ca3af" stroke-width="1.5"/>
                    </svg>
                </span>
            </div>

            <!-- Subscription Status -->
            <div class="sc-header">
					<span><?php _e('Subscription Status', TEXT_DOMAIN); ?></span>
					<span id="sc-status" class="sc-badge"><?php _e('Loading…', TEXT_DOMAIN); ?></span>
            </div>

            <!-- Stats Grid -->
            <div class="sc-grid">
                <div class="sc-box">
                    <small><?php _e('Concurrent Limit', TEXT_DOMAIN); ?></small>

                    <strong id="sc-concurrent">-</strong>
                </div>

                <div class="sc-box">
                    <small><?php _e('Remaining Concurrent', TEXT_DOMAIN); ?></small>
                    <strong id="sc-remaining-concurrent">-</strong>
                </div>

                <div class="sc-box">
                    <small><?php _e('Monthly Limit', TEXT_DOMAIN); ?></small>
                    <strong id="sc-monthly-max">-</strong>
                </div>

                <div class="sc-box">
                    <small><?php _e('Remaining Monthly', TEXT_DOMAIN); ?></small>
                    <strong id="sc-monthly-remaining">-</strong>
                    <div class="sc-progress">
                        <div id="sc-progress-bar"></div>
                    </div>
                </div>
            </div>

            <div class="sc-footer" id="sc-footer"><?php _e('Fetching data...', TEXT_DOMAIN); ?></div>
        </div>

    <?php else: ?>
        <div class="sc-card" style="text-align:center;">
            <p style="margin-bottom:20px; font-weight:600; color:#b91c1c;">
            <?php _e('API Token is not set yet!', TEXT_DOMAIN); ?>    
            </p>
            <a href="<?php echo admin_url('admin.php?page=_options&tab=20'); ?>" class="button button-primary" target="_blank">
            <?php _e('Set API Token in Theme Settings (Api Key)', TEXT_DOMAIN); ?>       
            </a>
        </div>
    <?php endif; ?>
</div>

<style>
.sc-wrap{margin:30px auto;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
.sc-title{text-align:center;font-size:26px;font-weight:700;color:#111827;margin-bottom:26px}
.sc-card{background:#ffffff;border-radius:20px;padding:26px;border:1px solid #e5e7eb;box-shadow:0 10px 25px rgba(0,0,0,.06),0 2px 6px rgba(0,0,0,.04)}
.sc-api-label{margin:0 0 6px 6px;font-size:12px;font-weight:600;color:#6b7280}
.sc-api-box{background:#f9fafb;border-radius:14px;border:1px solid #e5e7eb;padding:12px 16px;display:flex;align-items:center;justify-content:space-between;box-shadow:inset 0 1px 2px rgba(0,0,0,.03);margin-bottom:26px}
.sc-api-text{font-size:14px;color:#111827;letter-spacing:.4px}
.sc-api-copy{cursor:pointer;display:flex;align-items:center;opacity:.7;transition:.2s ease}
.sc-api-copy:hover{opacity:1;transform:scale(1.05)}
.sc-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:22px;font-size:14px;font-weight:600;color:#374151}
.sc-badge{padding:6px 14px;border-radius:999px;font-size:12px;font-weight:700;letter-spacing:.4px}
.sc-badge.active{background:#ecfdf5;color:#047857;border:1px solid #a7f3d0}
.sc-badge.inactive{background:#fef2f2;color:#b91c1c;border:1px solid #fecaca}
.sc-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:18px}
.sc-box{background:#f9fafb;border-radius:16px;padding:18px;border:1px solid #e5e7eb;transition:.2s ease}
.sc-box:hover{transform:translateY(-2px);box-shadow:0 6px 14px rgba(0,0,0,.06)}
.sc-box small{display:block;font-size:12px;font-weight:600;color:#6b7280}
.sc-box strong{display:block;font-size:26px;margin-top:8px;color:#111827}
.sc-progress{height:8px;background:#e5e7eb;border-radius:6px;margin-top:12px;overflow:hidden}
.sc-progress div{height:100%;width:0;background:linear-gradient(90deg,#22c55e,#4ade80)}
.sc-footer{text-align:center;color: black;  font-size: 1rem;margin-top:22px}
@media (max-width:640px){.sc-title{font-size:22px}
.sc-box strong{font-size:22px}
}.aps-tab-content.active{display:block}
.sc-notification{margin:30px auto;padding:20px;border:1px solid #e5e7eb;border-radius:16px;text-align:center;font-size:16px;font-weight:500;line-height:1.6;transition:background-color 0.2s ease,transform 0.2s ease}
.sc-notification:hover{background-color:#f9fafb;transform:translateY(-2px)}
.sc-notification a{color:#3b82f6;font-weight:600;text-decoration:underline;transition:color 0.2s ease,transform 0.2s ease}
.sc-notification a:hover{color:#1d4ed8;transform:translateY(-1px)}
@media (max-width:640px){.sc-notification{font-size:14px;padding:16px 20px}
.sc-notification::before{font-size:16px}
}.aps-tab-content.active{display:block}

</style>

<script>
/* =========================================================
   COPY API TOKEN (WP ADMIN SAFE + FALLBACK)
========================================================= */
function scCopyToken(el) {
    const token = el.dataset.token;
    if (!token) return;

    const originalHTML = el.innerHTML;

    // Modern Clipboard (HTTPS / allowed context)
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(token)
            .then(() => copied(el, originalHTML))
            .catch(() => fallbackCopy(token, el, originalHTML));
    } else {
        // Fallback for wp-admin / localhost
        fallbackCopy(token, el, originalHTML);
    }
}

function fallbackCopy(text, el, originalHTML) {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';

    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();

    try {
        document.execCommand('copy');
        copied(el, originalHTML);
    } catch (e) {
        failed(el, originalHTML);
    }

    document.body.removeChild(textarea);
}

function copied(el, originalHTML) {
    el.innerHTML = '✔ Copied';
    el.style.color = '#16a34a';
    el.style.fontWeight = '600';

    setTimeout(() => {
        el.innerHTML = originalHTML;
        el.style.color = '';
        el.style.fontWeight = '';
    }, 1200);
}

function failed(el, originalHTML) {
    el.innerHTML = '✖ Failed';
    el.style.color = '#dc2626';

    setTimeout(() => {
        el.innerHTML = originalHTML;
        el.style.color = '';
    }, 1500);
}

/* =========================================================
   AJAX LOAD SCRAPE.DO STATUS
========================================================= */
function scLoadStatus() {
    fetch(ajaxurl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            action: 'sc_scrape_status'
        })
    })
    .then(res => res.json())
    .then(json => {
        if (!json || !json.data) return;

        const d = json.data;

        /* STATUS BADGE */
        const badge = document.getElementById('sc-status');
        if (badge) {
            badge.textContent = d.IsActive ? 'ACTIVE' : 'INACTIVE';
            badge.className = 'sc-badge ' + (d.IsActive ? 'active' : 'inactive');
        }

        /* STATS */
        setVal('sc-concurrent', d.ConcurrentRequest);
        setVal('sc-remaining-concurrent', d.RemainingConcurrentRequest);
        setVal('sc-monthly-max', format(d.MaxMonthlyRequest));
        setVal('sc-monthly-remaining', format(d.RemainingMonthlyRequest));

        /* PROGRESS BAR */
        if (d.MaxMonthlyRequest > 0) {
            const used = d.MaxMonthlyRequest - d.RemainingMonthlyRequest;
            const percent = Math.max(0, 100 - (used / d.MaxMonthlyRequest * 100));

            const bar = document.getElementById('sc-progress-bar');
            if (bar) bar.style.width = percent + '%';
        }

        /* FOOTER */
        const footer = document.getElementById('sc-footer');
        if (footer) {
            footer.textContent =
                'HTTP ' + json.http + ' • Updated ' + new Date().toLocaleTimeString();
        }
    })
    .catch(() => {
        const footer = document.getElementById('sc-footer');
        if (footer) footer.textContent = 'Failed to load API status';
    });
}

/* =========================================================
   HELPERS
========================================================= */
function setVal(id, val) {
    const el = document.getElementById(id);
    if (el) el.textContent = val;
}

function format(num) {
    return Number(num || 0).toLocaleString();
}

/* =========================================================
   INIT
========================================================= */
document.addEventListener('DOMContentLoaded', () => {
    scLoadStatus();
    setInterval(scLoadStatus, 30000); // auto refresh 30s
});
</script>


<?php
}


