<?php
/**
 * Blog Over Admin Dashboard
 *
 * Handles theme activation redirect, admin menu registration,
 * welcome notice, and AJAX notice dismissal.
 *
 * @package Blog_Over
 * @since   1.4.0
 */

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

require_once __DIR__ . '/class-blog-over-plugin-helper.php';

/**
 * Class Blog_Over_Admin
 */
class Blog_Over_Admin
{

    /**
     * Dashboard page slug.
     *
     * @var string
     */
    const PAGE_SLUG = 'blog-over-dashboard';

    /**
     * Starter Sites page slug.
     *
     * @var string
     */
    const STARTER_SLUG = 'blog-over-starter-sites';

    /**
     * Notice dismissed option name.
     *
     * @var string
     */
    const NOTICE_OPTION = 'blog_over_notice_dismissed';

    /**
     * Activation redirect transient name.
     *
     * @var string
     */
    const REDIRECT_TRANSIENT = 'blog_over_activation_redirect';

    /**
     * Initialize hooks.
     */
    public function __construct()
    {
        add_action('after_switch_theme', array($this, 'set_activation_redirect'));
        add_action('admin_init', array($this, 'do_activation_redirect'));
        add_action('admin_menu', array($this, 'register_menu'));
        add_action('admin_menu', array($this, 'hide_ocdi_menu'), 99);
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('admin_notices', array($this, 'welcome_notice'));
        add_action('wp_ajax_blog_over_dismiss_notice', array($this, 'dismiss_notice'));
        add_action('wp_ajax_blog_over_install_companion', array($this, 'install_companion'));
    }

    /**
     * Set transient on theme activation.
     */
    public function set_activation_redirect()
    {
        set_transient(self::REDIRECT_TRANSIENT, true, 30);
    }

    /**
     * Redirect to themes page after theme activation.
     */
    public function do_activation_redirect()
    {

        if (!get_transient(self::REDIRECT_TRANSIENT)) {
            return;
        }

        delete_transient(self::REDIRECT_TRANSIENT);

        // Bail if activating from network or bulk.
        if (is_network_admin() || isset($_GET['activate-multi'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return;
        }

        wp_safe_redirect(admin_url('themes.php'));
        exit;
    }

    /**
     * Register admin pages under Appearance.
     */
    public function register_menu()
    {
        add_theme_page(
            esc_html__('Blog Over Dashboard', 'blog-over'),
            esc_html__('Blog Over', 'blog-over'),
            'manage_options',
            self::PAGE_SLUG,
            array($this, 'render_dashboard')
        );

        add_theme_page(
            esc_html__('Blog Over Starter Sites', 'blog-over'),
            esc_html__('Starter Sites', 'blog-over'),
            'manage_options',
            self::STARTER_SLUG,
            array($this, 'render_starter_sites')
        );
    }

    /**
     * Hide the default OCDI menu item visually.
     *
     * We use our own Starter Sites page. The OCDI page must remain
     * registered (not removed via remove_submenu_page) so that
     * get_admin_page_title() can resolve $title when the import
     * step URL is visited — otherwise $title stays null, which
     * triggers a strip_tags(null) deprecation on PHP 8.1+.
     */
    public function hide_ocdi_menu()
    {
        add_action('admin_head', function () {
            echo '<style>#adminmenu a[href="themes.php?page=one-click-demo-import"]{display:none !important;}</style>';
        });
    }

    /**
     * Render the dashboard page.
     */
    public function render_dashboard()
    {
        require_once BLOG_OVER_DIR . '/inc/admin/views/dashboard-page.php';
    }

    /**
     * Render the Starter Sites page.
     */
    public function render_starter_sites()
    {
        require_once BLOG_OVER_DIR . '/inc/admin/views/starter-sites-page.php';
    }

    /**
     * Enqueue admin assets on the dashboard page only.
     *
     * @param string $hook_suffix The current admin page hook suffix.
     */
    public function enqueue_assets($hook_suffix)
    {

        $allowed_hooks = array(
            'appearance_page_' . self::PAGE_SLUG,
            'appearance_page_' . self::STARTER_SLUG,
            'themes.php',
        );
        if (!in_array($hook_suffix, $allowed_hooks, true)) {
            return;
        }

        wp_enqueue_style(
            'blog-over-admin-dashboard',
            BLOG_OVER_URI . '/assets/css/admin-dashboard.css',
            array(),
            BLOG_OVER_VERSION
        );

        // Enqueue plugin install scripts on the Starter Sites page (Formula pattern).
        if ('appearance_page_' . self::STARTER_SLUG === $hook_suffix) {
            wp_enqueue_script('plugin-install');
            wp_enqueue_script('updates');
            wp_enqueue_script(
                'blog-over-plugin-install',
                BLOG_OVER_URI . '/inc/admin/js/recommended-plugin-install.js',
                array('jquery'),
                BLOG_OVER_VERSION,
                true
            );
            wp_localize_script(
                'blog-over-plugin-install',
                'blog_over_start_page',
                array('activating' => __('Activating', 'blog-over'))
            );
        }
    }

    /**
     * Show a dismissible welcome notice.
     */
    public function welcome_notice()
    {

        if (get_option(self::NOTICE_OPTION)) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        // Only show on the Appearance → Themes screen.
        $screen = get_current_screen();
        if (!$screen || 'themes' !== $screen->id) {
            return;
        }

        $dashboard_url = admin_url('themes.php?page=' . self::PAGE_SLUG);
        $theme = wp_get_theme();
        $current_user = wp_get_current_user();
        ?>
        <div class="notice notice-info is-dismissible blog-over-welcome-notice-wrapper">
            <div class="blog-over-welcome-notice-inner">
                <div class="blog-over-welcome-notice-content">
                    <p class="blog-over-welcome-greeting">
                        <?php
                        printf(
                            /* translators: %s: user display name */
                            esc_html__('Hello, %s 👋', 'blog-over'),
                            esc_html($current_user->display_name)
                        );
                        ?>
                    </p>
                    <h2 class="blog-over-welcome-title">
                        <?php
                        printf(
                            /* translators: %s: theme name */
                            esc_html__('Welcome to %s', 'blog-over'),
                            esc_html($theme->get('Name'))
                        );
                        ?>
                    </h2>
                    <p class="blog-over-welcome-text">
                        <?php
                        printf(
                            /* translators: %s: theme name */
                            esc_html__('Thank you for choosing %s! Get started by importing a starter site or jump into the customizer to make it yours.', 'blog-over'),
                            esc_html($theme->get('Name'))
                        );
                        ?>
                    </p>
                    <div class="blog-over-welcome-actions">
                        <a href="<?php echo esc_url(admin_url('themes.php?page=blog-over-starter-sites')); ?>"
                            id="blog-over-get-started-btn" class="button button-primary blog-over-btn-get-started">
                            <span class="dashicons dashicons-download"></span>
                            <?php esc_html_e('Import Starter Site', 'blog-over'); ?>
                        </a>
                        <a href="<?php echo esc_url(admin_url('customize.php')); ?>" class="button blog-over-btn-secondary">
                            <span class="dashicons dashicons-admin-customizer"></span>
                            <?php esc_html_e('Customize', 'blog-over'); ?>
                        </a>
                    </div>
                    <div class="blog-over-welcome-links">
                        <a href="https://awplife.com/demo/blog-over/" target="_blank" rel="noopener noreferrer">
                            <span class="dashicons dashicons-desktop"></span>
                            <?php esc_html_e('View Demos', 'blog-over'); ?>
                        </a>
                        <a href="https://wordpress.org/support/theme/blog-over/" target="_blank" rel="noopener noreferrer">
                            <span class="dashicons dashicons-sos"></span>
                            <?php esc_html_e('Support', 'blog-over'); ?>
                        </a>
                    </div>
                </div>
                <div class="blog-over-welcome-notice-image">
                    <div class="blog-over-welcome-screenshot">
                        <img src="<?php echo esc_url(BLOG_OVER_URI . '/screenshot.png'); ?>"
                            alt="<?php esc_attr_e('Blog Over Theme Preview', 'blog-over'); ?>">
                    </div>
                </div>
            </div>
            <div class="blog-over-welcome-notice-footer">
                <button type="button" class="button-link blog-over-notice-dismiss-text">
                    <?php esc_html_e('Dismiss this notice', 'blog-over'); ?>
                </button>
            </div>
        </div>
        <script>
            jQuery(document).ready(function ($) {
                // "Dismiss this notice" — permanently dismiss via AJAX.
                $('.blog-over-welcome-notice-wrapper').on('click', '.blog-over-notice-dismiss-text', function () {
                    $.post(ajaxurl, {
                        action: 'blog_over_dismiss_notice',
                        _wpnonce: '<?php echo esc_js(wp_create_nonce('blog_over_dismiss_notice')); ?>'
                    });
                    $(this).closest('.blog-over-welcome-notice-wrapper').fadeOut(200);
                });

                // Import Starter Site (Install/Activate Plugin)
                $('#blog-over-get-started-btn').on('click', function (e) {
                    e.preventDefault();
                    var $btn = $(this);
                    if ($btn.hasClass('updating-message')) {
                        return;
                    }

                    $btn.addClass('updating-message').text('<?php esc_html_e('Processing...', '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.text('<?php esc_html_e('Redirecting...', 'blog-over'); ?>');
                            window.location.href = response.data.redirect_url;
                        } else {
                            $btn.removeClass('updating-message').text('<?php esc_html_e('Error! Try Again', 'blog-over'); ?>');
                            alert(response.data.message || '<?php esc_html_e('An error occurred.', 'blog-over'); ?>');
                        }
                    }).fail(function () {
                        $btn.removeClass('updating-message').text('<?php esc_html_e('Error! Try Again', 'blog-over'); ?>');
                        alert('<?php esc_html_e('An error occurred. Please try again.', 'blog-over'); ?>');
                    });
                });
            });
        </script>
        <?php
    }

    /**
     * AJAX handler — dismiss the welcome notice permanently.
     */
    public function dismiss_notice()
    {

        check_ajax_referer('blog_over_dismiss_notice');

        if (!current_user_can('manage_options')) {
            wp_send_json_error();
        }

        update_option(self::NOTICE_OPTION, 1);
        wp_send_json_success();
    }

    /**
     * AJAX handler — install and activate companion plugin.
     *
     * Installs and activates both AWP Companion and One Click Demo Import
     * so the Starter Sites page works immediately for fresh users.
     */
    public function install_companion()
    {

        check_ajax_referer('blog_over_install_companion');

        if (!current_user_can('install_plugins')) {
            wp_send_json_error(array('message' => __('You do not have permission to install plugins.', 'blog-over')));
        }

        $demo_importer_url = admin_url('themes.php?page=' . self::STARTER_SLUG);

        include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        include_once ABSPATH . 'wp-admin/includes/plugin.php';

        // Plugins to install and activate.
        $plugins = array(
            array(
                'slug' => 'awp-companion',
                'file' => 'awp-companion/awp-companion.php',
            ),
            array(
                'slug' => 'one-click-demo-import',
                'file' => 'one-click-demo-import/one-click-demo-import.php',
            ),
        );

        foreach ($plugins as $plugin) {
            $plugin_file = $plugin['file'];
            $plugin_slug = $plugin['slug'];

            if (is_plugin_active($plugin_file)) {
                continue;
            }

            // Install from WordPress.org if not already on disk.
            if (!file_exists(WP_PLUGIN_DIR . '/' . $plugin_file)) {
                $api = plugins_api('plugin_information', array(
                    'slug' => $plugin_slug,
                    'fields' => array('sections' => false),
                ));

                if (is_wp_error($api)) {
                    wp_send_json_error(array(
                        'message' => sprintf(
                            /* translators: %s: plugin slug */
                            __('Could not retrieve plugin info for %s.', 'blog-over'),
                            $plugin_slug
                        ),
                    ));
                }

                $upgrader = new Plugin_Upgrader(new Automatic_Upgrader_Skin());
                $install = $upgrader->install($api->download_link);

                if (is_wp_error($install)) {
                    wp_send_json_error(array('message' => $install->get_error_message()));
                } elseif (true !== $install) {
                    wp_send_json_error(array(
                        'message' => sprintf(
                            /* translators: %s: plugin slug */
                            __('Failed to install %s.', 'blog-over'),
                            $plugin_slug
                        ),
                    ));
                }
            }

            // Activate.
            $activate = activate_plugin($plugin_file);
            if (is_wp_error($activate)) {
                wp_send_json_error(array('message' => $activate->get_error_message()));
            }
        }

        wp_send_json_success(array('redirect_url' => $demo_importer_url));
    }
}

// Boot.
new Blog_Over_Admin();
