<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Gerencia o Setup Wizard do Hub
 * VERSÃO 3: Cria TODOS os presets (Publicados ou Rascunhos)
 * e chama a classe de presets correta (WPCM_Hub_Service_Presets)
 */
class WPCM_Hub_Setup_Wizard {

    public function __construct() {
        add_action( 'admin_init', array( $this, 'redirect_to_wizard' ) );
        add_action( 'admin_menu', array( $this, 'register_wizard_page' ) );
        add_action( 'admin_post_wpcm_hub_save_wizard', array( $this, 'save_wizard_settings' ) );
        add_action( 'admin_notices', array( $this, 'setup_incomplete_notice' ) );
    }

    public function redirect_to_wizard() {
        if ( get_transient( 'wpcm_hub_activation_redirect' ) ) {
            delete_transient( 'wpcm_hub_activation_redirect' );
            
            // CORREÇÃO: Verificação de contexto visual, sem risco de segurança.
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if ( ! isset( $_GET['activate-multi'] ) ) {
                // Redireciona para o slug do wizard do HUB
                wp_safe_redirect( admin_url( 'admin.php?page=wpcm_hub_setup_wizard' ) );
                exit;
            }
        }
    }

    public function register_wizard_page() {
        add_submenu_page(
            null, // Oculta do menu
            __( 'Setup Consent Hub', 'wpcm-agency-hub' ),
            __( 'Setup Consent Hub', 'wpcm-agency-hub' ),
            'manage_options',
            'wpcm_hub_setup_wizard', // O slug correto do wizard do HUB
            array( $this, 'render_wizard_page' )
        );
    }

    public function render_wizard_page() {
        // Garante que a classe de presets do Hub exista
        if ( ! class_exists( 'WPCM_Hub_Service_Presets' ) ) {
            require_once WPCM_HUB_PATH . 'includes/class-hub-service-presets.php';
        }
        // Chama a classe correta do HUB
        $presets = WPCM_Hub_Service_Presets::get_all_presets();
        ?>
        <div class="wrap wpcm-wizard-wrap" style="max-width: 600px; margin: 40px auto; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px; padding: 20px 40px 40px;">
            <div style="text-align: center; margin-bottom: 20px;">
                <span class="dashicons dashicons-networking" style="font-size: 48px; width: 48px; height: 48px; color: #4F46E5;"></span>
            </div>
            <h1 style="text-align: center;"><?php esc_html_e( 'Welcome to the Consent Agency Hub', 'wpcm-agency-hub' ); ?></h1>
            <p style="text-align: center; font-size: 16px; color: #555;"><?php esc_html_e( 'Let\'s create your global service presets. These will be synced to new clients.', 'wpcm-agency-hub' ); ?></p>

            <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                <input type="hidden" name="action" value="wpcm_hub_save_wizard">
                <?php wp_nonce_field( 'wpcm_hub_wizard_nonce', 'wpcm_hub_wizard_security' ); ?>

                <div class="wpcm-wizard-options" style="margin-top: 30px; border-top: 1px solid #eee; padding-top: 20px;">
                    <p><strong><?php esc_html_e( 'Select the services you want to activate (publish) by default:', 'wpcm-agency-hub' ); ?></strong></p>
                    <p class="description"><?php esc_html_e( 'Services you don\'t select will be created as "Drafts" and can be published later.', 'wpcm-agency-hub' ); ?></p>
                    
                    <ul style="list-style: none; margin: 15px 0 0 0;">
                        <?php foreach ( $presets as $key => $preset ) : ?>
                            <li style="margin-bottom: 10px;">
                                <label>
                                    <input type="checkbox" name="wpcm_services[]" value="<?php echo esc_attr( $key ); ?>" 
                                        <?php checked( in_array( $key, array('google_analytics', 'meta_pixel', 'youtube_vimeo') ) ); ?> >
                                    <strong><?php echo esc_html( $preset['title'] ); ?></strong> (<?php echo esc_html( $preset['category'] ); ?>)
                                </label>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>

                <div class="wpcm-wizard-footer" style="margin-top: 30px; text-align: center;">
                    <button type="submit" class="button button-primary button-hero"><?php esc_html_e( 'Create Presets', 'wpcm-agency-hub' ); ?></button>
                    <a href="<?php echo esc_url( admin_url( 'edit.php?post_type=wpcm_hub_site&page=wpcm_hub_settings' ) ); ?>" style="display: block; margin-top: 10px;"><?php esc_html_e( 'Skip this step', 'wpcm-agency-hub' ); ?></a>
                </div>
            </form>
        </div>
        <?php
    }

    /**
     * Chama a nova lógica "Publicado/Rascunho".
     */
    public function save_wizard_settings() {
        check_admin_referer( 'wpcm_hub_wizard_nonce', 'wpcm_hub_wizard_security' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html( __( 'Sorry, you are not allowed to manage options for this site.', 'wpcm-agency-hub' ) ) );
        }

        if ( ! class_exists( 'WPCM_Hub_Service_Presets' ) ) {
            require_once WPCM_HUB_PATH . 'includes/class-hub-service-presets.php';
        }

        $selected_services = array();
        if ( ! empty( $_POST['wpcm_services'] ) && is_array( $_POST['wpcm_services'] ) ) {
            $selected_services = array_map( 'sanitize_text_field', wp_unslash( $_POST['wpcm_services'] ) );
        }

        // Chama a nova função que cria TODOS os presets
        WPCM_Hub_Service_Presets::create_all_presets_from_wizard( $selected_services );

        if ( in_array( 'youtube_vimeo', $selected_services ) ) {
            $options = get_option( 'wpcm_hub_global_settings', array() );
            if ( !is_array($options) ) $options = array();
            $options['enable_iframe_blocker'] = '1';
            update_option( 'wpcm_hub_global_settings', $options );
        }

        update_option( 'wpcm_hub_setup_complete', 1 );

        // Redireciona para a lista de Global Services para ver o resultado
        wp_safe_redirect( add_query_arg( 'post_type', 'wpcm_hub_service', admin_url( 'edit.php' ) ) );
        exit;
    }

    public function setup_incomplete_notice() {
        // CORREÇÃO: Verificação de contexto visual.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $current_page = isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '';
        
        if ( $current_page === 'wpcm_hub_setup_wizard' ) {
            return;
        }
        if ( ! get_option( 'wpcm_hub_setup_complete' ) ) {
            ?>
            <div class="notice notice-info is-dismissible">
                <p>
                    <strong><?php esc_html_e( 'Welcome to the Consent Agency Hub!', 'wpcm-agency-hub' ); ?></strong> 
                    <?php esc_html_e( 'Please complete the setup wizard to create your global service presets.', 'wpcm-agency-hub' ); ?>
                </p>
                <p>
                    <a href="<?php echo esc_url( admin_url( 'admin.php?page=wpcm_hub_setup_wizard' ) ); ?>" class="button button-primary"><?php esc_html_e( 'Run Setup Wizard', 'wpcm-agency-hub' ); ?></a>
                </p>
            </div>
            <?php
        }
    }
}