<?php
/**
 * Blog Over — Starter Sites Page Template
 *
 * Custom 3-column responsive grid for demo import cards.
 * Reads demo data from the OCDI filter and renders our own UI.
 * The actual import is handled by OCDI's built-in step URL.
 *
 * @package Blog_Over
 * @since   1.4.0
 * @version 1.4.1
 */

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

// Read the registered demos from the same filter OCDI uses.
$demos = apply_filters('pt-ocdi/import_files', array());
$has_pro = class_exists('Blog_Over_Pro');

// Check if required plugins are active.
$ocdi_active = is_plugin_active('one-click-demo-import/one-click-demo-import.php');
$awp_active = is_plugin_active('awp-companion/awp-companion.php');
$plugins_ready = $ocdi_active && $awp_active;
?>
<div class="blog-over-starter-sites">

    <!-- Page Header -->
    <div class="blog-over-starter-header">
        <div class="blog-over-starter-header-inner">
            <h1>
                <?php esc_html_e('Starter Sites', 'blog-over'); ?>
            </h1>
            <p>
                <?php esc_html_e('Import a starter site to quickly set up your website. Choose from our professionally designed templates.', 'blog-over'); ?>
            </p>
        </div>
    </div>

    <?php if (empty($demos)): ?>

        <div class="blog-over-starter-empty">
            <span class="dashicons dashicons-layout"></span>
            <p>
                <?php esc_html_e('The following plugins are required to display starter sites. Please install and activate them.', 'blog-over'); ?>
            </p>

            <?php if (current_user_can('install_plugins')):
                $redirect_url = admin_url('themes.php?page=blog-over-starter-sites');
                $required_plugins = array(
                    array(
                        'name' => 'AWP Companion',
                        'slug' => 'awp-companion',
                        'desc' => __('Provides front page customization and demo content settings.', 'blog-over'),
                    ),
                    array(
                        'name' => 'One Click Demo Import',
                        'slug' => 'one-click-demo-import',
                        'desc' => __('Enables one-click demo content import.', 'blog-over'),
                    ),
                );
                $helper = Blog_Over_Plugin_Helper::instance();
                ?>
                <div class="blog-over-plugin-cards">
                    <?php foreach ($required_plugins as $plugin): ?>
                        <div class="blog-over-plugin-card">
                            <h4><?php echo esc_html($plugin['name']); ?></h4>
                            <p><?php echo esc_html($plugin['desc']); ?></p>
                            <?php
                            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is escaped inside helper.
                            echo $helper->get_button_html($plugin['slug'], $redirect_url);
                            ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>


    <?php else: ?>

        <div class="blog-over-starter-grid">
            <?php foreach ($demos as $index => $demo):
                // Determine demo type from categories.
                $categories = isset($demo['categories']) ? (array) $demo['categories'] : array();
                $is_pro = in_array('Pro Demos', $categories, true);

                // Screenshot.
                $img_src = '';
                if (!empty($demo['import_preview_image_url'])) {
                    $img_src = $demo['import_preview_image_url'];
                } else {
                    $theme = wp_get_theme();
                    $img_src = $theme->get_screenshot();
                }

                // Demo title.
                $title = !empty($demo['import_file_name']) ? $demo['import_file_name'] : esc_html__('Demo', 'blog-over');

                // Preview URL.
                $preview_url = !empty($demo['preview_url']) ? $demo['preview_url'] : '';

                // OCDI import step URL.
                $import_url = admin_url('themes.php?page=one-click-demo-import&step=import&import=' . absint($index));
                ?>

                <div class="blog-over-starter-card">
                    <div class="blog-over-starter-card-image">
                        <?php if ($is_pro): ?>
                            <span class="blog-over-starter-badge blog-over-starter-badge-pro">
                                <?php esc_html_e('Pro', 'blog-over'); ?>
                            </span>
                        <?php else: ?>
                            <span class="blog-over-starter-badge blog-over-starter-badge-free">
                                <?php esc_html_e('Free', 'blog-over'); ?>
                            </span>
                        <?php endif; ?>

                        <?php if ($img_src): ?>
                            <img src="<?php echo esc_url($img_src); ?>" alt="<?php echo esc_attr($title); ?>" loading="lazy" />
                        <?php endif; ?>
                    </div>

                    <div class="blog-over-starter-card-body">
                        <h3 class="blog-over-starter-card-title">
                            <?php echo esc_html($title); ?>
                        </h3>

                        <div class="blog-over-starter-card-actions">
                            <?php if ($preview_url): ?>
                                <a href="<?php echo esc_url($preview_url); ?>" class="blog-over-starter-btn" target="_blank"
                                    rel="noopener noreferrer">
                                    <span class="dashicons dashicons-visibility"></span>
                                    <?php esc_html_e('Live Demo', 'blog-over'); ?>
                                </a>
                            <?php endif; ?>

                            <?php if ($is_pro && !$has_pro): ?>
                                <!-- Pro demo but Pro plugin not active — show upgrade link -->
                                <a href="https://awplife.com/wordpress-themes/blog-over/"
                                    class="blog-over-starter-btn blog-over-starter-btn-pro" target="_blank"
                                    rel="noopener noreferrer">
                                    <span class="dashicons dashicons-star-filled"></span>
                                    <?php esc_html_e('Upgrade to Pro', 'blog-over'); ?>
                                </a>
                            <?php elseif ($plugins_ready): ?>
                                <!-- Both plugins active — direct import link -->
                                <a href="<?php echo esc_url($import_url); ?>"
                                    class="blog-over-starter-btn blog-over-starter-btn-primary">
                                    <span class="dashicons dashicons-download"></span>
                                    <?php esc_html_e('Import', 'blog-over'); ?>
                                </a>
                            <?php elseif (current_user_can('install_plugins')): ?>
                                <!-- Plugins missing — install/activate first, then redirect to import -->
                                <a href="#"
                                    class="blog-over-starter-btn blog-over-starter-btn-primary blog-over-import-ensure-plugins"
                                    data-import-url="<?php echo esc_url($import_url); ?>">
                                    <span class="dashicons dashicons-download"></span>
                                    <?php esc_html_e('Import', 'blog-over'); ?>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

            <?php endforeach; ?>
        </div>

    <?php endif; ?>

</div>

<?php if (!empty($demos) && !$plugins_ready && current_user_can('install_plugins')): ?>
    <script>
        jQuery(function ($) {
            /**
             * Import buttons that need plugins installed/activated first.
             *
             * Triggers the same AJAX handler used by the welcome notice
             * (blog_over_install_companion) to install + activate both
             * AWP Companion and OCDI, then redirects to the OCDI import step.
             */
            $('.blog-over-import-ensure-plugins').on('click', function (e) {
                e.preventDefault();
                var $btn = $(this);
                if ($btn.hasClass('updating-message')) {
                    return;
                }

                var importUrl = $btn.data('import-url');

                $btn.addClass('updating-message')
                    .find('.dashicons').removeClass('dashicons-download').addClass('dashicons-update');
                $btn.contents().last()[0].textContent = ' <?php echo esc_js(__('Installing plugins...', 'blog-over')); ?>';

                $.post(ajaxurl, {
                    action: 'blog_over_install_companion',
                    _wpnonce: '<?php echo esc_js(wp_create_nonce('blog_over_install_companion')); ?>'
                }, function (response) {
                    if (response.success) {
                        $btn.contents().last()[0].textContent = ' <?php echo esc_js(__('Redirecting...', 'blog-over')); ?>';
                        window.location.href = importUrl;
                    } else {
                        $btn.removeClass('updating-message')
                            .find('.dashicons').removeClass('dashicons-update').addClass('dashicons-download');
                        $btn.contents().last()[0].textContent = ' <?php echo esc_js(__('Import', 'blog-over')); ?>';
                        /* translators: fallback error */
                        alert(response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('Plugin installation failed. Please try again.', 'blog-over')); ?>');
                    }
                }).fail(function () {
                    $btn.removeClass('updating-message')
                        .find('.dashicons').removeClass('dashicons-update').addClass('dashicons-download');
                    $btn.contents().last()[0].textContent = ' <?php echo esc_js(__('Import', 'blog-over')); ?>';
                    alert('<?php echo esc_js(__('An error occurred. Please try again.', 'blog-over')); ?>');
                });
            });
        });
    </script>
<?php endif; ?>