<?php

defined('ABSPATH') || exit;

class BundlePress_Other_Plugins
{
    public static function init()
    {
        add_action('admin_menu', [__CLASS__, 'register_menu'], 99);
        add_action('rest_api_init', [__CLASS__, 'register_rest_routes']);
    }

    public static function register_menu()
    {
        add_submenu_page(
            'bundlepress',
            __('Other Plugins', 'bundlepress'),
            __('Other Plugins', 'bundlepress'),
            'manage_woocommerce',
            'bundlepress-other-plugins',
            [__CLASS__, 'render_page']
        );
    }

    public static function register_rest_routes()
    {
        register_rest_route('bundlepress/v1', '/other-plugins', [
            'methods'  => 'GET',
            'callback' => [__CLASS__, 'get_other_plugins_proxy'],
            'permission_callback' => function () {
                return current_user_can('manage_woocommerce');
            }
        ]);
    }

    public static function get_other_plugins_proxy()
    {
        $transient_key = 'bundlepress_other_plugins_cache';
        $cached_data   = get_transient($transient_key);

        if (false !== $cached_data) {
            return rest_ensure_response($cached_data);
        }

        $response = wp_remote_get('https://dominopress.com/api/wp-plugins', [
            'timeout'   => 15,
            'sslverify' => false,
        ]);

        if (is_wp_error($response)) {
            return new WP_Error('fetch_failed', 'Failed to fetch plugins from DominoPress', ['status' => 500]);
        }

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (empty($data) || !isset($data['success'])) {
            return new WP_Error('invalid_data', 'Invalid response from DominoPress API', ['status' => 500]);
        }

        set_transient($transient_key, $data, 12 * HOUR_IN_SECONDS);
        return rest_ensure_response($data);
    }

    public static function render_page()
    {
        $nonce   = wp_create_nonce('wp_rest');
        $api_url = esc_url(rest_url('bundlepress/v1/other-plugins'));
        ?>
        <div class="wrap" id="bundlepress-other-plugins-root" style="margin-left: -20px; padding: 20px;">
            <div style="max-width: 1200px; margin: 0 auto; padding: 40px 20px; font-family: 'Inter', system-ui, sans-serif;">
                <div style="margin-bottom: 60px; text-align: center;">
                    <h1 style="margin: 0 0 16px 0; font-size: 40px; font-weight: 800; color: #1e293b; letter-spacing: -0.03em; line-height: 1.1;">More from DominoPress</h1>
                    <p style="margin: 0; font-size: 18px; color: #64748b; max-width: 650px; margin-inline: auto; line-height: 1.6; font-weight: 500;">
                        Supercharge your WooCommerce store with our suite of premium tools. Designed for maximum revenue, efficiency, and customer satisfaction.
                    </p>
                </div>

                <style>
                    /* Styles extracted from MaxLimits implementation */
                    .ml-plugin-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 30px; }
                    .ml-plugin-card, .ml-skeleton-card { background: #fff; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -2px rgba(0,0,0,0.05); border: 1px solid rgba(0,0,0,0.05); transition: all 0.3s ease; display: flex; flex-direction: column; height: 100%; box-sizing: border-box;}
                    .ml-plugin-card:hover { transform: translateY(-4px); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.1); }
                    .ml-plugin-img, .ml-skeleton-img { width: 100%; height: 180px; object-fit: cover; border-bottom: 1px solid rgba(0,0,0,0.05); }
                    .ml-plugin-body, .ml-skeleton-body { padding: 24px; display: flex; flex-direction: column; flex: 1; box-sizing: border-box; }
                    .ml-plugin-title { font-size: 20px !important; font-weight: 700 !important; color: #0f172a !important; margin: 0 0 12px 0 !important; line-height: 1.3 !important; padding: 0 !important; border: none !important;}
                    .ml-plugin-desc { font-size: 15px !important; color: #64748b !important; margin: 0 0 24px 0 !important; line-height: 1.6 !important; flex: 1; font-weight: normal !important;}
                    .ml-plugin-actions { display: flex; gap: 12px; margin-top: auto; }
                    .ml-btn-primary { flex: 1; display: inline-flex; justify-content: center; align-items: center; gap: 8px; background: #2563EB; color: #fff !important; padding: 12px 16px; border-radius: 10px; text-decoration: none; font-weight: 600; font-size: 14px; transition: all 0.2s; border: none; cursor: pointer; }
                    .ml-btn-primary:hover { background: #1D4ED8; color: #fff !important; transform: translateY(-1px); box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2); }
                    .ml-btn-secondary { flex: 1; display: inline-flex; justify-content: center; align-items: center; gap: 8px; background: #F1F5F9; color: #334155 !important; padding: 12px 16px; border-radius: 10px; text-decoration: none; font-weight: 600; font-size: 14px; transition: all 0.2s; border: 1px solid #E2E8F0; cursor: pointer; }
                    .ml-btn-secondary:hover { background: #E2E8F0; color: #0F172A !important; }
                    
                    /* Skeleton Animation */
                    @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: .5; } }
                    .ml-skeleton-pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; background-color: #e2e8f0; border-radius: 4px; }
                    .ml-skeleton-title { height: 24px; width: 70%; margin-bottom: 16px; }
                    .ml-skeleton-desc { height: 16px; margin-bottom: 8px; border-radius: 3px; }
                    .ml-skeleton-action { height: 44px; border-radius: 10px; }
                    .anim-fade-in { animation: fadeIn 0.5s ease-out forwards; opacity: 0; }
                    @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
                </style>

                <div id="ml-plugin-grid" class="ml-plugin-grid">
                    <?php for ($i = 0; $i < 6; $i++): ?>
                        <div class="ml-skeleton-card">
                            <div class="ml-skeleton-pulse ml-skeleton-img"></div>
                            <div class="ml-skeleton-body">
                                <div class="ml-skeleton-pulse ml-skeleton-title"></div>
                                <div class="ml-skeleton-pulse ml-skeleton-desc" style="width: 100%"></div>
                                <div class="ml-skeleton-pulse ml-skeleton-desc" style="width: 85%"></div>
                                <div class="ml-skeleton-pulse ml-skeleton-desc" style="width: 40%; margin-bottom: 32px;"></div>
                                <div style="display: flex; gap: 12px; margin-top: auto;">
                                    <div class="ml-skeleton-pulse ml-skeleton-action" style="flex: 1"></div>
                                    <div class="ml-skeleton-pulse ml-skeleton-action" style="flex: 1"></div>
                                </div>
                            </div>
                        </div>
                    <?php endfor; ?>
                </div>
            </div>

            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    const grid = document.getElementById('ml-plugin-grid');
                    const apiUrl = '<?php echo $api_url; ?>';
                    const nonce = '<?php echo $nonce; ?>';

                    fetch(apiUrl, {
                            headers: {
                                'X-WP-Nonce': nonce
                            }
                        })
                        .then(res => res.json())
                        .then(res => {
                            if (res.success && res.data) {
                                renderPlugins(res.data);
                            } else {
                                grid.innerHTML = '<p style="grid-column: 1/-1; text-align: center; padding: 40px; color: #ef4444; background: #fee2e2; border-radius: 12px; font-weight: 600;">Failed to load plugins.</p>';
                            }
                        })
                        .catch(err => {
                            grid.innerHTML = '<p style="grid-column: 1/-1; text-align: center; padding: 40px; color: #ef4444; background: #fee2e2; border-radius: 12px; font-weight: 600;">Network error occurred while fetching plugins.</p>';
                        });

                    function renderPlugins(plugins) {
                        grid.innerHTML = plugins.map(plugin => `
                        <div class="ml-plugin-card anim-fade-in">
                            <img src="${plugin.image}" alt="${plugin.title}" class="ml-plugin-img">
                            <div class="ml-plugin-body">
                                <h2 class="ml-plugin-title">${plugin.title}</h2>
                                <p class="ml-plugin-desc">${plugin.description}</p>
                                <div class="ml-plugin-actions">
                                    ${plugin.button1 ? `
                                        <a href="${plugin.button1.url}" target="_blank" rel="noopener noreferrer" class="ml-btn-primary">
                                            ${plugin.button1.text} <span class="dashicons dashicons-external" style="font-size: 16px; width: 16px; height: 16px;"></span>
                                        </a>
                                    ` : ''}
                                    ${plugin.button2 ? `
                                        <a href="${plugin.button2.url}" target="_blank" rel="noopener noreferrer" class="ml-btn-secondary">
                                            ${plugin.button2.text} <span class="dashicons dashicons-download" style="font-size: 16px; width: 16px; height: 16px;"></span>
                                        </a>
                                    ` : ''}
                                </div>
                            </div>
                        </div>
                    `).join('');
                    }
                });
            </script>
        </div>
        <?php
    }
}
