<?php
/**
 * Plugin Name:       Google Play App Info (Nelexa) Pro
 * Description:       Fetch real-time Google Play app details with stunning animated UI + icon reveal
 * Version:           2.0.0
 * Author:            Your Name
 * License:           GPL-2.0+
 * Text Domain:       gplay-nelexa
 * Requires PHP:      7.4+
 */

if (!defined('ABSPATH')) exit;

define('GPLAY_NELEXA_PATH', get_template_directory().'/libs/addons/');
define('GPLAY_NELEXA_URL', plugin_dir_url(__FILE__));
require_once get_template_directory().'/libs/addons/vendor/autoload.php';

// Safe autoloader
function gplay_nelexa_autoload() {
    $file = GPLAY_NELEXA_PATH . 'vendor/autoload.php';
    if (file_exists($file)) {
        require_once $file;
        return true;
    }
    return false;
}

// Admin notice if missing
add_action('admin_notices', function () {
    if (current_user_can('manage_options') && !gplay_nelexa_autoload() && (!empty($_GET['page']) && $_GET['page'] === 'gplay-nelexa')) {
        echo '<div class="notice notice-error"><p>
            <strong>Google Play App Info Pro:</strong> Library missing!<br>
            Run: <code>composer require nelexa/google-play-scraper</code> in plugin folder.
        </p></div>';
    }
});

// Menu
add_action('admin_menu', function () {
    add_menu_page(
        'Google Play App Info Pro',
        'Play Store Pro',
        'manage_options',
        'gplay-nelexa',
        'gplay_nelexa_page',
        'dashicons-google',
        82
    );
});

// Main Page
function gplay_nelexa_page() {
    if (!current_user_can('manage_options')) wp_die('No permission');

    $app_info = $error = null;

    if (isset($_POST['nonce']) && wp_verify_nonce($_POST['nonce'], 'gplay_fetch')) {
        $package = sanitize_text_field($_POST['package'] ?? '');
        $locale  = sanitize_text_field($_POST['lang'] ?? 'en_US');
        $country = sanitize_text_field($_POST['country'] ?? 'us');

        if ($package) {
            $result = gplay_nelexa_get_app($package, $locale, $country);
            $app_info = is_object($result) ? $result : null;
            $error    = is_string($result) ? $result : null;
        } else {
            $error = 'Package name required.';
        }
    }
    ?>
    <div class="wrap">
        <h1>Google Play App Info <span style="font-size:16px;color:#666;">Pro v2.0</span></h1>

        <!-- CINEMATIC PROGRESS UI -->
        <div id="gplay-progress" style="display:none;position:fixed;inset:0;background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);z-index:99999;color:#fff;overflow:hidden;">
            <div style="position:absolute;inset:0;opacity:0.15;background:radial-gradient(circle at 20% 80%,#00ff88,transparent 50%),radial-gradient(circle at 80% 20%,#00ffff,transparent 50%);"></div>
            <div style="position:relative;z-index:2;display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;">
                <div id="gplay-icon-box" style="width:120px;height:120px;background:#ffffff18;border-radius:28px;backdrop-filter:blur(10px);margin-bottom:40px;display:flex;align-items:center;justify-content:center;overflow:hidden;">
                    <div class="spinner"></div>
                </div>
                <div id="gplay-text" style="font-size:24px;font-weight:600;margin-bottom:20px;text-shadow:0 2px 10px #000;">Connecting to Google Play...</div>
                <div style="width:520px;max-width:90vw;height:18px;background:#ffffff18;border-radius:50px;overflow:hidden;box-shadow:inset 0 4px 15px #0004;">
                    <div id="gplay-fill" style="width:0%;height:100%;background:linear-gradient(90deg,#00c9ff,#92fe9d,#00c9ff);background-size:200%;border-radius:50px;animation:shimmer 4s infinite;box-shadow:0 0 30px rgba(0,201,255,0.6);transition:width .6s ease;"></div>
                </div>
                <div style="margin-top:18px;font-size:14px;opacity:0.8;" id="gplay-percent">0%</div>
            </div>
        </div>

        <style>
            @keyframes spin {to{transform:rotate(360deg)}}
            @keyframes shimmer {0%{background-position:-200%}100%{background-position:200%}}
            .spinner{width:80px;height:80px;border:6px solid #fff3;border-top-color:#00c9ff;border-radius:50%;animation:spin 1.2s cubic-bezier(0.4,0,0.2,1) infinite;}
            .gplay-card{background:#fff;padding:30px;border-radius:16px;box-shadow:0 10px 40px rgba(0,0,0,.12);margin:25px 0;max-width:720px;}
            .gplay-card input{font-size:15px;padding:12px;}
            img.screenshot{width:220px;margin:8px;border-radius:12px;box-shadow:0 8px 25px rgba(0,0,0,.15);transition:transform .2s;}
            img.screenshot:hover{transform:scale(1.05);}
        </style>

        <form method="post" id="gplay-form" class="gplay-card">
            <?php wp_nonce_field('gplay_fetch', 'nonce'); ?>
            <table class="form-table">
                <tr>
                    <th><label>Package Name</label></th>
                    <td>
                        <input type="text" name="package" class="regular-text" required placeholder="com.whatsapp" value="<?php echo esc_attr($_POST['package'] ?? ''); ?>">
                        <p class="description">Example: com.instagram.android • com.mojang.minecraftpe</p>
                    </td>
                </tr>
                <tr><th>Language</th><td><input type="text" name="lang" value="<?php echo esc_attr($_POST['lang'] ?? 'en_US'); ?>" placeholder="en_US"></td></tr>
                <tr><th>Country</th><td><input type="text" name="country" value="<?php echo esc_attr($_POST['country'] ?? 'us'); ?>" placeholder="us"></td></tr>
            </table>
            <?php submit_button('Fetch App Info', 'primary large'); ?>
        </form>

        <?php if ($error): ?>
            <div class="notice notice-error" style="padding:20px;font-size:16px;margin-top:20px;">
                <strong>Error:</strong> <?php echo esc_html($error); ?>
            </div>
        <?php endif; ?>

        <?php if ($app_info): ?>
            <script>
                // SUCCESS: Reveal real icon + finish animation
                document.addEventListener('DOMContentLoaded', () => {
                    const box = document.getElementById('gplay-icon-box');
                    const fill = document.getElementById('gplay-fill');
                    const text = document.getElementById('gplay-text');
                    const percent = document.getElementById('gplay-percent');
                    const progress = document.getElementById('gplay-progress');

                    fill.style.width = '100%';
                    percent.textContent = '100%';
                    text.textContent = 'Success! Loaded <?php echo addslashes($app_info->getName()); ?>';

                    const img = new Image();
                    img.onload = () => {
                        box.innerHTML = `<img src="${img.src}" style="width:100%;height:100%;object-fit:cover;border-radius:24px;">`;
                    };
                    img.src = <?php echo wp_json_encode($app_info->getIcon()?->getUrl() ?: ''); ?> || '<?php echo GPLAY_NELEXA_URL; ?>placeholder.png';

                    setTimeout(() => {
                        progress.style.opacity = '0';
                        setTimeout(() => progress.style.display = 'none', 600);
                    }, 1000);
                });
            </script>

            <!-- IMPORT BUTTON -->
            <div style="text-align:center;margin:40px 0;">
                <button type="button" id="import-btn" onclick="gplayImportPost()">
                    Import as WordPress Post
                </button>
            </div>
			
            <h2 style="color:#1da1f2;font-size:28px;">
                <?php echo esc_html($app_info->getName()); ?>
                <small style="color:#666;font-size:16px;">by <?php echo esc_html($app_info->getDeveloperName()); ?></small>
            </h2>

            <table class="widefat fixed striped" style="font-size:15px;">
                <tr><th width="180">Package</th><td><code><?php echo esc_html($app_info->getId()); ?></code></td></tr>
                <tr><th>Version</th><td><?php echo esc_html($app_info->getAppVersion() ?: 'Varies'); ?></td></tr>
                <tr><th>Updated</th><td><?php echo $app_info->getUpdated()?->format('d M Y'); ?></td></tr>
                <tr><th>Installs</th><td><?php echo esc_html($app_info->getInstalls()); ?></td></tr>
                <tr><th>Rating</th><td><?php echo number_format($app_info->getScore(), 1); ?> / 5 (<?php echo number_format_i18n($app_info->getNumberVoters()); ?>)</td></tr>
                <tr><th>Price</th><td><?php echo $app_info->isFree() ? 'Free' : esc_html($app_info->getPrice() . ' ' . $app_info->getCurrency()); ?></td></tr>
                <tr><th>Contains Ads</th><td><?php echo $app_info->isContainsAds() ? 'Yes' : 'No'; ?></td></tr>
                <?php if ($icon = $app_info->getIcon()): ?>
                <tr><th>Icon</th><td><img src="<?php echo esc_url($icon->getUrl()); ?>" style="max-width:144px;border-radius:24px;"></td></tr>
                <?php endif; ?>
                <?php if ($screenshots = $app_info->getScreenshots()): ?>
                <tr>
                    <th>Screenshots</th>
                    <td style="padding:20px 0;">
                        <?php foreach ($screenshots as $ss): ?>
                            <img src="<?php echo esc_url($ss->getUrl()); ?>" class="screenshot" loading="lazy">
                        <?php endforeach; ?>
                    </td>
                </tr>
                <?php endif; ?>
                <?php if ($desc = $app_info->getDescription()): ?>
                <tr><th>Description</th><td><?php echo wp_kses_post(wpautop(make_clickable(esc_html($desc)))); ?></td></tr>
                <?php endif; ?>
				<?php if ($desc = $app_info->getRecentChanges()): ?>
				<tr><th>Recent Changes</th><td><?php echo wp_kses_post(nl2br($app_info->getRecentChanges())); ?></td></tr>
                <?php endif; ?>

				<?php if ($desc = $app_info->getVideo()): ?>
				<tr><th>Video</th><td><?php echo esc_html($app_info->getVideo()); ?></td></tr>
                <?php endif; ?>
					
            </table>
        <?php endif; ?>
    </div>

    <script>
    document.getElementById('gplay-form').onsubmit = function() {
        const progress = document.getElementById('gplay-progress');
        const fill = document.getElementById('gplay-fill');
        const percent = document.getElementById('gplay-percent');
        const text = document.getElementById('gplay-text');

        progress.style.display = 'block';
        progress.style.opacity = '1';
        fill.style.width = '0%';
        percent.textContent = '0%';

        let p = 0;
        const messages = ["Connecting...", "Fetching details...", "Loading screenshots...", "Almost done..."];
        let i = 0;

        const timer = setInterval(() => {
            if (p < 92) p += Math.random() * 5 + 2;
            fill.style.width = p + '%';
            percent.textContent = Math.round(p) + '%';
            if (p > 30 && i < messages.length) {
                text.textContent = messages[i++];
            }
        }, 300);

        setTimeout(() => clearInterval(timer), 40000);
    }; 
	
    </script>
    <?php
}

// Core function with caching
function gplay_nelexa_get_app($package, $locale = 'en_US', $country = 'us') {
    $key = 'gplay_' . md5("{$package}_{$locale}_{$country}");
    $cached = get_transient($key);
    if ($cached !== false) return $cached;

    if (!gplay_nelexa_autoload()) {
        return 'Nelexa library not installed.';
    }

    try {
        $gplay = (new \Nelexa\GPlay\GPlayApps())
            ->setDefaultLocale($locale)
            ->setDefaultCountry($country);

        $info = $gplay->getAppInfo($package);
        set_transient($key, $info, 6 * HOUR_IN_SECONDS);
        return $info;
    } catch (\Nelexa\GPlay\Exception\GooglePlayException $e) {
        $msg = $e->getCode() === 404 ? 'App not found.' : 'Google Play error: ' . $e->getMessage();
    } catch (Throwable $e) {
        $msg = 'Error: ' . $e->getMessage();
    }
    set_transient($key, $msg, 10 * MINUTE_IN_SECONDS);
    return $msg;
}