<?php
/**
 * Admin banner for plugin promotion and one-click install.
 *
 * @package nxt-event-planner
 */

function nxt_event_planner_is_admin_banner_screen( $hook_suffix = '' ) {
    // Show the banner across the entire admin area.
    return is_admin();
}

function nxt_event_planner_find_plugin_file_by_slug( $slug ) {
    if ( ! function_exists( 'get_plugins' ) ) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $plugins = get_plugins();
    foreach ( $plugins as $nxt_event_planner_plugin_file => $plugin_data ) {
        if ( 0 === strpos( $nxt_event_planner_plugin_file, $slug . '/' ) ) {
            return $nxt_event_planner_plugin_file;
        }
    }

    return '';
}

function nxt_event_planner_admin_banner_dismiss_key() {
    return 'nxt_event_planner_admin_banner_dismissed_' . sanitize_key( get_stylesheet() );
}

function nxt_event_planner_admin_banner_assets( $hook_suffix ) {
    if ( ! nxt_event_planner_is_admin_banner_screen( $hook_suffix ) ) {
        return;
    }

    $nxt_event_planner_theme_version = wp_get_theme()->get( 'Version' );
    $nxt_event_planner_plugin_slug   = 'novex-demo-importer';
    $nxt_event_planner_plugin_file   = nxt_event_planner_find_plugin_file_by_slug( $nxt_event_planner_plugin_slug );
    $nxt_event_planner_is_active     = ! empty( $nxt_event_planner_plugin_file ) && is_plugin_active( $nxt_event_planner_plugin_file );

    wp_enqueue_style(
        'nxt-event-planner-admin-banner',
        get_template_directory_uri() . '/assets/css/nxt-event-planner-admin-banner.css',
        array(),
        filemtime( get_template_directory() . '/assets/css/nxt-event-planner-admin-banner.css' )
    );

    wp_enqueue_script(
        'nxt-event-planner-admin-banner',
        get_template_directory_uri() . '/js/nxt-event-planner-admin-banner.js',
        array(),
        $nxt_event_planner_theme_version,
        true
    );

    wp_localize_script(
        'nxt-event-planner-admin-banner',
        'nxtEventPlannerAdminBanner',
        array(
            'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
            'nonce'          => wp_create_nonce( 'nxt_event_planner_install_novex' ),
            'dismissNonce'   => wp_create_nonce( 'nxt_event_planner_dismiss_admin_banner' ),
            'noticeKey'      => nxt_event_planner_admin_banner_dismiss_key(),
            'installText'    => __( 'Install Plugin', 'nxt-event-planner' ),
            'installingText' => __( 'Installing and activating...', 'nxt-event-planner' ),
            'activatedText'  => __( 'Plugin Activated', 'nxt-event-planner' ),
            'workingText'    => __( 'Please wait...', 'nxt-event-planner' ),
            'successText'    => __( 'Plugin installed and activated successfully.', 'nxt-event-planner' ),
            'errorText'      => __( 'The plugin could not be installed. Please try again.', 'nxt-event-planner' ),
            'isActive'       => $nxt_event_planner_is_active,
        )
    );
}
add_action( 'admin_enqueue_scripts', 'nxt_event_planner_admin_banner_assets' );

function nxt_event_planner_is_admin_banner_dismissed() {
    return (bool) get_transient( nxt_event_planner_admin_banner_dismiss_key() );
}

function nxt_event_planner_render_admin_banner() {
    if ( ! nxt_event_planner_is_admin_banner_screen() || ! current_user_can( 'activate_plugins' ) || nxt_event_planner_is_admin_banner_dismissed() ) {
        return;
    }

    // Hide the banner on the Novex Demo Importer page.
    if ( isset( $_GET['page'] ) && 'novex-demo-importer' === sanitize_key( wp_unslash( $_GET['page'] ) ) ) {
        return;
    }

    $nxt_event_planner_plugin_slug = 'novex-demo-importer';
    $nxt_event_planner_plugin_file = nxt_event_planner_find_plugin_file_by_slug( $nxt_event_planner_plugin_slug );
    $nxt_event_planner_is_active   = ! empty( $nxt_event_planner_plugin_file ) && is_plugin_active( $nxt_event_planner_plugin_file );
    $nxt_event_planner_button_text = $nxt_event_planner_is_active ? __( 'Plugin Activated', 'nxt-event-planner' ) : __( 'Install Plugin', 'nxt-event-planner' );
    ?>
    <div class="notice nxt-event-planner-admin-banner is-dismissible">
        <div class="nxt-event-planner-admin-banner__inner">
            <div class="nxt-event-planner-admin-banner__logo">
                <img src="<?php echo esc_url( get_template_directory_uri() . '/assets/img/novex-logo.svg' ); ?>" alt="<?php esc_attr_e( 'Novex', 'nxt-event-planner' ); ?>">
            </div>
            <div class="nxt-event-planner-admin-banner__content">
                <h2 class="nxt-event-planner-admin-banner__title"><?php esc_html_e( 'Get Started With NXT Event Planner', 'nxt-event-planner' ); ?></h2>
                <p class="nxt-event-planner-admin-banner__desc"><?php esc_html_e( 'Install and activate Novex Demo Importer to unlock one-click demo setup and speed up your site launch.', 'nxt-event-planner' ); ?></p>
                <div class="nxt-event-planner-admin-banner__actions">
                    <button type="button" class="nxt-event-planner-admin-banner__btn nxt-event-planner-admin-banner__btn--install<?php echo $nxt_event_planner_is_active ? ' is-complete' : ''; ?>" <?php disabled( $nxt_event_planner_is_active ); ?>>
                        <?php echo esc_html( $nxt_event_planner_button_text ); ?>
                    </button>
                    <a href="https://novexthemes.com/preview/nxt-event-planner-pro/?utm_source=wordpress&utm_medium=theme&utm_campaign=free_theme_admin_banner" target="_blank" class="nxt-event-planner-admin-banner__btn nxt-event-planner-admin-banner__btn--demo"><?php esc_html_e( 'View Demo', 'nxt-event-planner' ); ?></a>
                    <a href="https://novexthemes.com/product/event-planner-wordpress-theme/?utm_source=wordpress&utm_medium=theme&utm_campaign=free_theme_admin_banner" target="_blank" class="nxt-event-planner-admin-banner__btn nxt-event-planner-admin-banner__btn--buy-now"><?php esc_html_e( 'Buy Now', 'nxt-event-planner' ); ?></a>

                </div>
                <div class="nxt-event-planner-admin-banner__status"></div>
            </div>
        </div>
        <button type="button" class="notice-dismiss nxt-event-planner-admin-banner__dismiss">
            <span class="screen-reader-text"><?php esc_html_e( 'Dismiss this notice.', 'nxt-event-planner' ); ?></span>
        </button>
    </div>
    <?php
}
add_action( 'admin_notices', 'nxt_event_planner_render_admin_banner' );

function nxt_event_planner_ajax_install_activate_novex() {
    check_ajax_referer( 'nxt_event_planner_install_novex', 'nonce' );

    $nxt_event_planner_plugin_slug = 'novex-demo-importer';
    $nxt_event_planner_plugin_file = nxt_event_planner_find_plugin_file_by_slug( $nxt_event_planner_plugin_slug );

    if ( empty( $nxt_event_planner_plugin_file ) ) {
        if ( ! current_user_can( 'install_plugins' ) ) {
            wp_send_json_error(
                array(
                    'message' => __( 'You do not have permission to install plugins.', 'nxt-event-planner' ),
                )
            );
        }

        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/misc.php';
        require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

        $nxt_event_planner_api = plugins_api(
            'plugin_information',
            array(
                'slug'   => $nxt_event_planner_plugin_slug,
                'fields' => array(
                    'sections' => false,
                ),
            )
        );

        if ( is_wp_error( $nxt_event_planner_api ) || empty( $nxt_event_planner_api->download_link ) ) {
            wp_send_json_error(
                array(
                    'message' => __( 'Could not fetch plugin information from WordPress.org.', 'nxt-event-planner' ),
                )
            );
        }

        $nxt_event_planner_upgrader  = new Plugin_Upgrader( new Automatic_Upgrader_Skin() );
        $nxt_event_planner_installed = $nxt_event_planner_upgrader->install( $nxt_event_planner_api->download_link );

        if ( is_wp_error( $nxt_event_planner_installed ) ) {
            wp_send_json_error(
                array(
                    'message' => $nxt_event_planner_installed->get_error_message(),
                )
            );
        }

        if ( ! $nxt_event_planner_installed ) {
            $nxt_event_planner_error = '';
            if ( isset( $nxt_event_planner_upgrader->skin ) && method_exists( $nxt_event_planner_upgrader->skin, 'get_errors' ) ) {
                $nxt_event_planner_errors = $nxt_event_planner_upgrader->skin->get_errors();
                if ( is_wp_error( $nxt_event_planner_errors ) ) {
                    $nxt_event_planner_error = $nxt_event_planner_errors->get_error_message();
                }
            }

            wp_send_json_error(
                array(
                    'message' => ! empty( $nxt_event_planner_error ) ? $nxt_event_planner_error : __( 'Plugin installation failed.', 'nxt-event-planner' ),
                )
            );
        }

        $nxt_event_planner_plugin_file = nxt_event_planner_find_plugin_file_by_slug( $nxt_event_planner_plugin_slug );
    }

    if ( empty( $nxt_event_planner_plugin_file ) ) {
        wp_send_json_error(
            array(
                'message' => __( 'Plugin installed but the main plugin file could not be found.', 'nxt-event-planner' ),
            )
        );
    }

    if ( ! current_user_can( 'activate_plugins' ) ) {
        wp_send_json_error(
            array(
                'message' => __( 'You do not have permission to activate plugins.', 'nxt-event-planner' ),
            )
        );
    }

    $plugin_page_url = admin_url( 'admin.php?page=novex-demo-importer' );

    if ( is_plugin_active( $nxt_event_planner_plugin_file ) ) {
        wp_send_json_success(
            array(
                'message'  => __( 'Novex Demo Importer is already active.', 'nxt-event-planner' ),
                'redirect' => $plugin_page_url,
            )
        );
    }

    $activated = activate_plugin( $nxt_event_planner_plugin_file );
    if ( is_wp_error( $activated ) ) {
        wp_send_json_error(
            array(
                'message' => $activated->get_error_message(),
            )
        );
    }

    wp_send_json_success(
        array(
            'message'  => __( 'Novex Demo Importer has been installed and activated.', 'nxt-event-planner' ),
            'redirect' => $plugin_page_url,
        )
    );
}
add_action( 'wp_ajax_nxt_event_planner_install_activate_novex', 'nxt_event_planner_ajax_install_activate_novex' );

function nxt_event_planner_ajax_dismiss_admin_banner() {
    check_ajax_referer( 'nxt_event_planner_dismiss_admin_banner', 'nonce' );

    if ( ! current_user_can( 'activate_plugins' ) ) {
        wp_send_json_error(
            array(
                'message' => __( 'You do not have permission to dismiss this notice.', 'nxt-event-planner' ),
            )
        );
    }

    $notice = isset( $_POST['notice'] ) ? sanitize_key( wp_unslash( $_POST['notice'] ) ) : '';

    if ( nxt_event_planner_admin_banner_dismiss_key() !== $notice ) {
        wp_send_json_error(
            array(
                'message' => __( 'Invalid notice identifier.', 'nxt-event-planner' ),
            )
        );
    }

    // Hide the banner for 1 hour only, then it reappears.
    set_transient( $notice, '1', HOUR_IN_SECONDS );

    wp_send_json_success();
}
add_action( 'wp_ajax_nxt_event_planner_dismiss_admin_banner', 'nxt_event_planner_ajax_dismiss_admin_banner' );
