<?php

// Core block custom styles

add_action( 'init', function () {
    wp_enqueue_block_style(
        'core/navigation',
        array(
            'handle' => 'multiplex-navigation',
            'src'    => get_theme_file_uri( 'styles/blocks/navigation.css' ),
            'path'   => get_theme_file_path( 'styles/blocks/navigation.css' ),
        )
    );
});

// Theme's style.css

add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_style(
        'multiplex',
        get_theme_file_uri( 'style.css' ),
        [],
        wp_get_theme()->get( 'Version' )
    );
} );

// Patterns category

add_action( 'init', function() {
    register_block_pattern_category(
        'multiplex',
        array(
            'label' => __( 'Multiplex', 'multiplex' ),
        )
    );
} );

// Custom blocks custom styles

// HotBlocks Contact

function multiplex_hotblocks_contact_styles() {
    $handle = 'multiplex-hotblocks-contact';
    $src    = get_theme_file_uri( 'assets/css/hotblocks-contact.css' );
    $ver    = wp_get_theme()->get( 'Version' );

    // Frontend
    wp_enqueue_style( $handle, $src, [], $ver );
}
add_action( 'wp_enqueue_scripts', 'multiplex_hotblocks_contact_styles' );

function multiplex_hotblocks_contact_editor_styles() {
    $src = get_theme_file_uri( 'assets/css/hotblocks-contact.css' );
    $ver = wp_get_theme()->get( 'Version' );

    // Editor (block editor iframe)
    wp_enqueue_style( 'multiplex-hotblocks-contact-editor', $src, [], $ver );
}
add_action( 'enqueue_block_editor_assets', 'multiplex_hotblocks_contact_editor_styles' );

// HotBlocks Carousel

function multiplex_hotblocks_carousel_styles() {
    $handle = 'multiplex-hotblocks-carousel';
    $src    = get_theme_file_uri( 'assets/css/hotblocks-carousel.css' );
    $ver    = wp_get_theme()->get( 'Version' );

    // Frontend
    wp_enqueue_style( $handle, $src, [], $ver );
}
add_action( 'wp_enqueue_scripts', 'multiplex_hotblocks_carousel_styles' );

function multiplex_hotblocks_carousel_editor_styles() {
    $src = get_theme_file_uri( 'assets/css/hotblocks-carousel.css' );
    $ver = wp_get_theme()->get( 'Version' );

    // Editor (block editor iframe)
    wp_enqueue_style( 'multiplex-hotblocks-carousel-editor', $src, [], $ver );
}
add_action( 'enqueue_block_editor_assets', 'multiplex_hotblocks_carousel_editor_styles' );

// HotBlocks Counters

function multiplex_hotblocks_counters_styles() {
    $handle = 'multiplex-hotblocks-counters';
    $src    = get_theme_file_uri( 'assets/css/hotblocks-counters.css' );
    $ver    = wp_get_theme()->get( 'Version' );

    // Frontend
    wp_enqueue_style( $handle, $src, [], $ver );
}
add_action( 'wp_enqueue_scripts', 'multiplex_hotblocks_counters_styles' );

function multiplex_hotblocks_counters_editor_styles() {
    $src = get_theme_file_uri( 'assets/css/hotblocks-counters.css' );
    $ver = wp_get_theme()->get( 'Version' );

    // Editor (block editor iframe)
    wp_enqueue_style( 'multiplex-hotblocks-counters-editor', $src, [], $ver );
}
add_action( 'enqueue_block_editor_assets', 'multiplex_hotblocks_counters_editor_styles' );

// Custom logo.
add_action( 'after_setup_theme', function() {
    add_theme_support(
        'custom-logo',
        array(
            'height'      => 38,
            'width'       => 158,
            'flex-height' => true,
            'flex-width'  => true,
        )
    );
} );

/**
 * Demo content import and setup functionality has been moved to a companion plugin.
 * The theme now remains presentation-only for WordPress.org theme guidelines compliance.
 */

/**
 * Multiplex theme setup page and companion plugins.
 */

/**
 * Show a one-time setup notice after theme activation.
 */
add_action( 'after_switch_theme', function() {
    update_option( 'multiplex_show_setup_notice', 1 );
} );

/**
 * Register the theme setup page under Appearance.
 */
add_action( 'admin_menu', 'multiplex_register_theme_setup_page' );

function multiplex_register_theme_setup_page() {
    add_theme_page(
        __( 'Multiplex Setup', 'multiplex' ),
        __( 'Multiplex Setup', 'multiplex' ),
        'manage_options',
        'multiplex-setup',
        'multiplex_render_theme_setup_page'
    );
}

/**
 * Admin notice after activation.
 */
add_action( 'admin_notices', 'multiplex_theme_setup_notice' );

function multiplex_theme_setup_notice() {
    if ( ! get_option( 'multiplex_show_setup_notice' ) ) {
        return;
    }

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

    $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;

    if ( $screen && 'themes' !== $screen->base && 'dashboard' !== $screen->base ) {
        return;
    }

    $setup_url   = admin_url( 'themes.php?page=multiplex-setup' );
    $dismiss_url = wp_nonce_url(
        add_query_arg( 'multiplex_dismiss_setup_notice', '1', admin_url() ),
        'multiplex_dismiss_setup_notice'
    );

    echo '<div class="notice notice-success is-dismissible">';
    echo '<p><strong>' . esc_html__( 'Multiplex theme is ready.', 'multiplex' ) . '</strong></p>';
    echo '<p>' . esc_html__( 'Install the recommended companion plugins to unlock all theme demos and blocks.', 'multiplex' ) . '</p>';
    echo '<p>';
    echo '<a class="button button-primary" href="' . esc_url( $setup_url ) . '">' . esc_html__( 'Open Theme Setup', 'multiplex' ) . '</a> ';
    echo '<a class="button button-secondary" href="' . esc_url( $dismiss_url ) . '">' . esc_html__( 'Dismiss', 'multiplex' ) . '</a>';
    echo '</p>';
    echo '</div>';
}

/**
 * Dismiss the setup notice.
 */
add_action( 'admin_init', 'multiplex_handle_setup_notice_dismiss' );

function multiplex_handle_setup_notice_dismiss() {
    if (
        isset( $_GET['multiplex_dismiss_setup_notice'] ) &&
        '1' === $_GET['multiplex_dismiss_setup_notice'] &&
        isset( $_GET['_wpnonce'] ) &&
        wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'multiplex_dismiss_setup_notice' )
    ) {
        delete_option( 'multiplex_show_setup_notice' );
        wp_safe_redirect( remove_query_arg( array( 'multiplex_dismiss_setup_notice', '_wpnonce' ) ) );
        exit;
    }
}

/**
 * Return companion plugins config.
 *
 * @return array
 */
function multiplex_get_companion_plugins() {
    return array(
        array(
            'name'        => __( 'HotBlocks Carousel', 'multiplex' ),
            'slug'        => 'hotblocks-carousel',
            'plugin_file' => 'hotblocks-carousel/hotblocks-carousel.php',
            'description' => __( 'Adds the Carousel block used in Multiplex demos.', 'multiplex' ),
        ),
        array(
            'name'        => __( 'HotBlocks Contact Form', 'multiplex' ),
            'slug'        => 'hotblocks-contact-form',
            'plugin_file' => 'hotblocks-contact-form/hotblocks-contact-form.php',
            'description' => __( 'Adds the Contact Form block used in Multiplex demos.', 'multiplex' ),
        ),
        array(
            'name'        => __( 'HotBlocks Counters', 'multiplex' ),
            'slug'        => 'hotblocks-counters',
            'plugin_file' => 'hotblocks-counters/hotblocks-counters.php',
            'description' => __( 'Adds the Counters block used in Multiplex demos.', 'multiplex' ),
        ),
        array(
            'name'        => __( 'HotBlocks Maps', 'multiplex' ),
            'slug'        => 'hotblocks-maps',
            'plugin_file' => 'hotblocks-maps/hotblocks-maps.php',
            'description' => __( 'Adds the Maps block used in Multiplex demos.', 'multiplex' ),
        ),
    );
}

/**
 * Render the setup page.
 *
 * @return void
 */
function multiplex_render_theme_setup_page() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

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

    $success_message = get_transient( 'multiplex_setup_success' );
    $error_message   = get_transient( 'multiplex_setup_error' );

    if ( $success_message ) {
        echo '<div class="notice notice-success inline"><p>' . esc_html( $success_message ) . '</p></div>';
        delete_transient( 'multiplex_setup_success' );
    }

    if ( $error_message ) {
        echo '<div class="notice notice-error inline"><p>' . esc_html( $error_message ) . '</p></div>';
        delete_transient( 'multiplex_setup_error' );
    }

    $plugins       = multiplex_get_companion_plugins();
    $needs_action  = false;

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

        if ( ! file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ) || ! is_plugin_active( $plugin_file ) ) {
            $needs_action = true;
            break;
        }
    }

    echo '<div class="multiplex-setup-grid">';

    foreach ( $plugins as $plugin ) {
        $plugin_file = $plugin['plugin_file'];
        $plugin_path = WP_PLUGIN_DIR . '/' . $plugin_file;

        $is_installed = file_exists( $plugin_path );
        $is_active    = $is_installed && is_plugin_active( $plugin_file );

        echo '<div class="multiplex-setup-card">';
        echo '<h2>' . esc_html( $plugin['name'] ) . '</h2>';
        echo '<p>' . esc_html( $plugin['description'] ) . '</p>';

        echo '<div class="multiplex-plugin-status">';

        if ( $is_active ) {
            echo '<span class="multiplex-status multiplex-status-active">' . esc_html__( 'Active', 'multiplex' ) . '</span>';
        } elseif ( $is_installed ) {
            echo '<span class="multiplex-status multiplex-status-installed">' . esc_html__( 'Installed', 'multiplex' ) . '</span>';
        } else {
            echo '<span class="multiplex-status multiplex-status-missing">' . esc_html__( 'Not installed', 'multiplex' ) . '</span>';
        }

        echo '</div>';

        echo '<div class="multiplex-plugin-actions">';

        if ( $is_active ) {
            echo '<button class="button" disabled="disabled">' . esc_html__( 'Already Active', 'multiplex' ) . '</button>';
        } elseif ( $is_installed ) {
            $activate_url = wp_nonce_url(
                admin_url( 'plugins.php?action=activate&plugin=' . rawurlencode( $plugin_file ) ),
                'activate-plugin_' . $plugin_file
            );

            echo '<a class="button button-primary" href="' . esc_url( $activate_url ) . '">' . esc_html__( 'Activate', 'multiplex' ) . '</a>';
        } else {
            $install_url = wp_nonce_url(
                admin_url( 'update.php?action=install-plugin&plugin=' . rawurlencode( $plugin['slug'] ) ),
                'install-plugin_' . $plugin['slug']
            );

            echo '<a class="button button-primary" href="' . esc_url( $install_url ) . '">' . esc_html__( 'Install', 'multiplex' ) . '</a>';
        }

        echo '</div>';
        echo '</div>';
    }

    if ( $needs_action ) {
        $bulk_install_url = wp_nonce_url(
            admin_url( 'admin-post.php?action=multiplex_install_all_plugins' ),
            'multiplex_install_all_plugins'
        );

        echo '<p style="margin: 20px auto 24px;">';
        echo '<a class="button button-primary button-hero" href="' . esc_url( $bulk_install_url ) . '">' . esc_html__( 'Install All Recommended Plugins', 'multiplex' ) . '</a>';
        echo '</p>';
    }

    echo '</div></div>';
}

/**
 * Enqueue admin styles for the setup page.
 */
add_action( 'admin_enqueue_scripts', 'multiplex_setup_page_assets' );

function multiplex_setup_page_assets( $hook_suffix ) {
    if ( 'appearance_page_multiplex-setup' !== $hook_suffix ) {
        return;
    }

    $css = '
        .multiplex-setup-page {
            max-width: 1200px;
        }
        .multiplex-setup-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
            gap: 20px;
            margin-top: 24px;
        }
        .multiplex-setup-card {
            background: #fff;
            border: 1px solid #dcdcde;
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.04);
        }
        .multiplex-setup-card h2 {
            margin-top: 0;
            margin-bottom: 12px;
            font-size: 18px;
        }
        .multiplex-setup-card p {
            margin-bottom: 18px;
            color: #50575e;
        }
        .multiplex-plugin-status {
            margin-bottom: 18px;
        }
        .multiplex-status {
            display: inline-block;
            padding: 6px 10px;
            border-radius: 999px;
            font-size: 12px;
            font-weight: 600;
            line-height: 1;
        }
        .multiplex-status-active {
            background: #edf7ed;
            color: #0a7a20;
        }
        .multiplex-status-installed {
            background: #fff8e5;
            color: #8a6500;
        }
        .multiplex-status-missing {
            background: #f6f7f7;
            color: #50575e;
        }
        .multiplex-plugin-actions .button {
            min-width: 120px;
            text-align: center;
        }
    ';

    wp_register_style( 'multiplex-setup-inline', false, array(), wp_get_theme()->get( 'Version' ) );
    wp_enqueue_style( 'multiplex-setup-inline' );
    wp_add_inline_style( 'multiplex-setup-inline', $css );
}

/**
 * Install and activate all recommended plugins after explicit user action.
 */
add_action( 'admin_post_multiplex_install_all_plugins', 'multiplex_install_all_plugins_handler' );
function multiplex_install_all_plugins_handler() {
    if ( ! current_user_can( 'install_plugins' ) || ! current_user_can( 'activate_plugins' ) ) {
        wp_die( esc_html__( 'You do not have permission to install plugins.', 'multiplex' ) );
    }

    check_admin_referer( 'multiplex_install_all_plugins' );

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

    $plugins = multiplex_get_companion_plugins();

    $installed_or_activated = array();
    $failed                 = array();

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

        // Already active.
        if ( is_plugin_active( $plugin_file ) ) {
            $installed_or_activated[] = $plugin_name;
            continue;
        }

        // Installed but inactive.
        if ( file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ) ) {
            $result = activate_plugin( $plugin_file );

            if ( is_wp_error( $result ) ) {
                $failed[] = $plugin_name . ': ' . $result->get_error_message();
            } else {
                $installed_or_activated[] = $plugin_name;
            }

            continue;
        }

        // Not installed yet: install from WordPress.org and then activate.
        $api = plugins_api(
            'plugin_information',
            array(
                'slug'   => $plugin_slug,
                'fields' => array(
                    'sections' => false,
                ),
            )
        );

        if ( is_wp_error( $api ) || empty( $api->download_link ) ) {
            $failed[] = $plugin_name . ': ' . esc_html__( 'Could not fetch plugin information.', 'multiplex' );
            continue;
        }

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

        if ( is_wp_error( $install ) || ! $install ) {
            $message = is_wp_error( $install )
                ? $install->get_error_message()
                : esc_html__( 'Installation failed.', 'multiplex' );

            $failed[] = $plugin_name . ': ' . $message;
            continue;
        }

        // Figure out installed plugin file if needed.
        $installed_plugin_file = $plugin_file;

        if ( ! file_exists( WP_PLUGIN_DIR . '/' . $installed_plugin_file ) ) {
            $installed_plugin_file = $upgrader->plugin_info();
        }

        if ( empty( $installed_plugin_file ) || ! file_exists( WP_PLUGIN_DIR . '/' . $installed_plugin_file ) ) {
            $failed[] = $plugin_name . ': ' . esc_html__( 'Installed, but main plugin file could not be detected.', 'multiplex' );
            continue;
        }

        $result = activate_plugin( $installed_plugin_file );

        if ( is_wp_error( $result ) ) {
            $failed[] = $plugin_name . ': ' . $result->get_error_message();
            continue;
        }

        $installed_or_activated[] = $plugin_name;
    }

    if ( ! empty( $installed_or_activated ) ) {
        set_transient(
            'multiplex_setup_success',
            sprintf(
                /* translators: %s: plugin names */
                __( 'Installed & Activated: %s', 'multiplex' ),
                implode( ', ', $installed_or_activated )
            ),
            60
        );
    }

    if ( ! empty( $failed ) ) {
        set_transient(
            'multiplex_setup_error',
            implode( ' | ', $failed ),
            60
        );
    }

    wp_safe_redirect( admin_url( 'themes.php?page=multiplex-setup' ) );
    exit;
}

?>