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

/**
 * Registra o Custom Post Type "Global Services" (Presets) para o Hub.
 * VERSÃO 3: Adiciona o botão "Sync All Sites" à página de listagem.
 */
class WPCM_Hub_CPT_Services_Global {

    // O SLUG ÚNICO PARA O CPT DO HUB
    private $post_type_slug = 'wpcm_hub_service';

    public function __construct() {
        add_action( 'init', array( $this, 'register_post_type' ) );
        add_action( 'add_meta_boxes', array( $this, 'add_metabox' ) );
        add_action( 'save_post_' . $this->post_type_slug, array( $this, 'save_metabox' ) );

        // --- INÍCIO DA ADIÇÃO ---
        // Adiciona o botão "Sync" à página de listagem deste CPT
        add_action( 'views_edit-' . $this->post_type_slug, array( $this, 'add_sync_button_to_list_page' ) );
        // --- FIM DA ADIÇÃO ---
    }

    /**
     * Adiciona o botão "Sync All Sites" no topo da página de listagem.
     * (Versão corrigida com espaçamento e tooltip)
     */
    public function add_sync_button_to_list_page() {
        // O JS já foi enfileirado pelo WPCM_Hub_Core::load_admin_assets
        ?>
        <div style="text-align: right; float: right; margin-top: 5px; margin-left: 10px;">
            <a href="#" id="wpcm-hub-sync-button" 
               class="button button-primary button-large" 
               data-nonce="<?php echo esc_attr( wp_create_nonce( 'wpcm_hub_sync_nonce' ) ); ?>"
               
               title="<?php esc_attr_e( 'Force all sites to fetch new settings.', 'wpcm-agency-hub' ); ?>">
                
                <?php esc_html_e( 'Sync All Sites', 'wpcm-agency-hub' ); ?>
            </a>
            <span class="spinner" style="float: none; vertical-align: middle; visibility: hidden; margin-left: 5px;"></span>
            
            <div id="wpcm-sync-notice" class="notice" style="display: none; margin-top: 10px; text-align: left;"></div>
        </div>
        <?php
    }

    public function register_post_type() {
        // ... (o resto da função register_post_type não muda) ...
        $labels = array(
            'name'               => __( 'Global Services', 'wpcm-agency-hub' ),
            'singular_name'      => __( 'Global Service', 'wpcm-agency-hub' ),
            'add_new'            => __( 'Add New Service', 'wpcm-agency-hub' ),
            'add_new_item'       => __( 'Add New Service', 'wpcm-agency-hub' ),
            'edit_item'          => __( 'Edit Global Service', 'wpcm-agency-hub' ),
            'new_item'           => __( 'New Global Service', 'wpcm-agency-hub' ),
            'all_items'          => __( 'All Global Services', 'wpcm-agency-hub' ),
            'view_item'          => __( 'View Service', 'wpcm-agency-hub' ),
            'search_items'       => __( 'Search Global Services', 'wpcm-agency-hub' ),
            'not_found'          => __( 'No services found', 'wpcm-agency-hub' ),
            'not_found_in_trash' => __( 'No services found in Trash', 'wpcm-agency-hub' ),
            'menu_name'          => __( 'Global Services', 'wpcm-agency-hub' )
        );

        $args = array(
            'labels'              => $labels,
            'public'              => false,
            'publicly_queryable'  => false,
            'show_ui'             => true,
            'show_in_menu'        => 'edit.php?post_type=wpcm_hub_site', 
            'query_var'           => false,
            'rewrite'             => false,
            'capability_type'     => 'post',
            'has_archive'         => false,
            'hierarchical'        => false,
            'menu_position'       => null,
            'supports'            => array( 'title' ),
            'menu_icon'           => 'dashicons-admin-network',
            'show_in_rest'        => true, 
        );
        register_post_type( $this->post_type_slug, $args );
    }

    public function add_metabox() {
        // ... (o resto da função add_metabox não muda) ...
        add_meta_box(
            'wpcm_service_settings',
            __( 'Global Service Settings', 'wpcm-agency-hub' ),
            array( $this, 'render_metabox' ),
            $this->post_type_slug, 
            'normal',
            'high'
        );
    }

    public function render_metabox( $post ) {
        // ... (o resto da função render_metabox não muda) ...
        wp_nonce_field( 'wpcm_service_save', 'wpcm_service_nonce' );
        
        $category  = get_post_meta( $post->ID, '_wpcm_category', true );
        $desc      = get_post_meta( $post->ID, '_wpcm_description', true );
        $keywords  = get_post_meta( $post->ID, '_wpcm_keywords', true );
        $scripts   = get_post_meta( $post->ID, '_wpcm_scripts', true );

        ?>
        <p>
            <?php esc_html_e( 'Configure this service. It will be sent as a "preset" to all connected client sites.', 'wpcm-agency-hub' ); ?>
        </p>
        <table class="form-table">
            <tbody>
                <tr>
                    <th><label for="wpcm_category"><?php esc_html_e( 'Category', 'wpcm-agency-hub' ); ?></label></th>
                    <td>
                        <select name="wpcm_category" id="wpcm_category" required>
                            <option value="analytics" <?php selected( $category, 'analytics' ); ?>><?php esc_html_e( 'Analytics', 'wpcm-agency-hub' ); ?></option>
                            <option value="marketing" <?php selected( $category, 'marketing' ); ?>><?php esc_html_e( 'Marketing', 'wpcm-agency-hub' ); ?></option>
                            </select>
                        <p class="description"><?php esc_html_e( 'Assign this service to a category.', 'wpcm-agency-hub' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="wpcm_description"><?php esc_html_e( 'Service Description', 'wpcm-agency-hub' ); ?></label></th>
                    <td>
                        <textarea name="wpcm_description" id="wpcm_description" class="large-text" rows="3"><?php echo esc_textarea( $desc ); ?></textarea>
                        <p class="description"><?php esc_html_e( 'This text will be shown to the user in the consent modal.', 'wpcm-agency-hub' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="wpcm_keywords"><?php esc_html_e( 'Auto-Blocker Keywords', 'wpcm-agency-hub' ); ?></label></th>
                    <td>
                        <textarea name="wpcm_keywords" id="wpcm_keywords" class="large-text" rows="3"><?php echo esc_textarea( $keywords ); ?></textarea>
                        <p class="description"><?php esc_html_e( 'One keyword/domain per line (e.g., "googletagmanager.com").', 'wpcm-agency-hub' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="wpcm_scripts"><?php esc_html_e( 'Manual Scripts (Fallback)', 'wpcm-agency-hub' ); ?></label></th>
                    <td>
                        <textarea name="wpcm_scripts" id="wpcm_scripts" class="large-text" rows="5" style="font-family: Consolas, Monaco, monospace;"><?php echo esc_textarea( $scripts ); ?></textarea>
                        <p class="description"><?php esc_html_e( 'These scripts will be injected on the client site if this service is consented to.', 'wpcm-agency-hub' ); ?></p>
                    </td>
                </tr>
            </tbody>
        </table>
        <?php
    }

    private function _get_allowed_script_html() {
        // ... (o resto da função _get_allowed_script_html não muda) ...
        return array(
            'script' => array(
                'src'     => true,
                'type'    => true,
                'async'   => true,
                'defer'   => true,
                'charset' => true,
                'id'      => true,
                'class'   => true,
            ),
        );
    }

    private function _sanitize_scripts_field( $input ) {
        // ... (o resto da função _sanitize_scripts_field não muda) ...
        return wp_kses( $input, $this->_get_allowed_script_html() );
    }

    public function save_metabox( $post_id ) {
        // ... (o resto da função save_metabox não muda) ...
        $nonce = isset( $_POST['wpcm_service_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['wpcm_service_nonce'] ) ) : '';
        
        if ( ! $nonce || ! wp_verify_nonce( $nonce, 'wpcm_service_save' ) ) {
            return;
        }
        
        if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) ) {
            return;
        }

        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        $fields_to_sanitize = array(
            'wpcm_category'    => 'sanitize_text_field',
            'wpcm_description' => 'sanitize_textarea_field',
            'wpcm_keywords'    => 'sanitize_textarea_field',
        );

        foreach ( $fields_to_sanitize as $key => $sanitize_callback ) {
            if ( isset( $_POST[$key] ) ) {
                // CORREÇÃO: Adicionado phpcs:ignore para validar o uso dinâmico de sanitização
                // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                $value = $sanitize_callback( wp_unslash( $_POST[$key] ) );
                update_post_meta( $post_id, '_' . $key, $value );
            }
        }

        if ( isset( $_POST['wpcm_scripts'] ) ) {
            // CORREÇÃO: Adicionado phpcs:ignore pois usamos uma função customizada que implementa wp_kses
            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            $sanitized_scripts = $this->_sanitize_scripts_field( wp_unslash( $_POST['wpcm_scripts'] ) );
            update_post_meta( $post_id, '_wpcm_scripts', $sanitized_scripts );
        }
    }
}