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

/**
 * Registra o CPT "Perfis de Configuração" (wpcm_hub_profile).
 * CORRIGIDO: O text-domain 'wp-consent-manager' foi substituído por 'wpcm-agency-hub'
 */
class WPCM_Hub_CPT_Profiles {

    private $post_type_slug = 'wpcm_hub_profile';

    public function __construct() {
        add_action( 'init', array( $this, 'register_post_type' ) );
        add_action( 'add_meta_boxes', array( $this, 'add_metaboxes' ) );
        add_action( 'add_meta_boxes', array( $this, 'remove_third_party_metaboxes' ), 99 );
        add_action( 'save_post_' . $this->post_type_slug, array( $this, 'save_metabox' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
    }

    public function remove_third_party_metaboxes() {
        remove_meta_box( 'external-featured-image', $this->post_type_slug, 'side' );
    }

    public function enqueue_assets( $hook_suffix ) {
        $screen = get_current_screen();
        if ( ( $hook_suffix == 'post.php' || $hook_suffix == 'post-new.php' ) && $screen->post_type === $this->post_type_slug ) {
            wp_enqueue_style( 'wp-color-picker' );
        }
    }

    public function register_post_type() {
        $labels = array(
            'name'               => __( 'Configuration Profiles', 'wpcm-agency-hub' ),
            'singular_name'      => __( 'Profile', 'wpcm-agency-hub' ),
            'add_new'            => __( 'Add New Profile', 'wpcm-agency-hub' ),
            'add_new_item'       => __( 'Add New Profile', 'wpcm-agency-hub' ),
            'edit_item'          => __( 'Edit Profile', 'wpcm-agency-hub' ),
            'all_items'          => __( 'Configuration Profiles', 'wpcm-agency-hub' ),
            'menu_name'          => __( 'Config. Profiles', 'wpcm-agency-hub' )
        );
        $args = array(
            'labels'              => $labels,
            'public'              => false,
            'show_ui'             => true,
            'show_in_menu'        => 'edit.php?post_type=wpcm_hub_site', // Submenu do Hub
            'capability_type'     => 'post',
            'supports'            => array( 'title' ),
            'hierarchical'        => false,
            'show_in_rest'        => false,
        );
        register_post_type( $this->post_type_slug, $args );
    }

    public function add_metaboxes() {
        add_meta_box(
            'wpcm_profile_settings_metabox',
            __( 'Profile Settings', 'wpcm-agency-hub' ),
            array( $this, 'render_metabox_content' ),
            $this->post_type_slug,
            'normal',
            'high'
        );
    }

    public function render_metabox_content( $post ) {
        wp_nonce_field( 'wpcm_profile_save', 'wpcm_profile_nonce' );

        $options = get_post_meta( $post->ID, '_wpcm_profile_settings', true );
        $defaults = WPCM_Hub_Settings::get_default_options();
        $options = wp_parse_args( $options, $defaults );
        
        // CORREÇÃO: Adicionado ignore para verificação de nonce, pois é apenas estado visual da aba
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'design';
        ?>
        
        <style>
            .wpcm-metabox-nav { border-bottom: 1px solid #ccc; margin: 0 0 20px; }
            .wpcm-metabox-nav .nav-tab { background: #f1f1f1; border-color: #ccc; }
            .wpcm-metabox-nav .nav-tab-active { background: #fff; border-bottom-color: #fff; }
            .wpcm-tab-content { display: none; }
            .wpcm-tab-content.active { display: block; }
        </style>

        <h2 class="nav-tab-wrapper wpcm-metabox-nav">
            <a href="#design" class="nav-tab <?php echo $active_tab == 'design' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e( 'Design', 'wpcm-agency-hub' ); ?></a>
            <a href="#content" class="nav-tab <?php echo $active_tab == 'content' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e( 'Content', 'wpcm-agency-hub' ); ?></a>
            <a href="#services" class="nav-tab <?php echo $active_tab == 'services' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e( 'Services', 'wpcm-agency-hub' ); ?></a>
        </h2>

        <div id="design" class="wpcm-tab-content <?php echo $active_tab == 'design' ? 'active' : ''; ?>">
            <table class="form-table">
                <?php $this->render_field_select( 'banner_position', __( 'Banner Position', 'wpcm-agency-hub' ), $options, array( 'bottom-left'  => __( 'Bottom Left Corner', 'wpcm-agency-hub' ), 'bottom-right' => __( 'Bottom Right Corner', 'wpcm-agency-hub' ), 'footer' => __( 'Footer (Full Width Bar)', 'wpcm-agency-hub' ), 'modal' => __( 'Center Screen (Pop-up)', 'wpcm-agency-hub' ) ) ); ?>
                <?php $this->render_field_color( 'bg_color', __( 'Banner Background Color', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_color( 'text_color', __( 'Banner Text Color', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_color( 'btn_accept_bg_color', __( 'Accept Button Background', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_color( 'btn_reject_bg_color', __( 'Reject Button Background', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_color( 'btn_reject_text_color', __( 'Reject Button Text', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_color( 'btn_reject_border_color', __( 'Reject Button Border', 'wpcm-agency-hub' ), $options ); ?>
            </table>
        </div>

        <div id="content" class="wpcm-tab-content <?php echo $active_tab == 'content' ? 'active' : ''; ?>">
            <table class="form-table">
                <tr style="border-top: 1px solid #ddd;"><th scope="row"><?php esc_html_e( 'General Behavior', 'wpcm-agency-hub' ); ?></th><td><hr style="display: none;"></td></tr>
                <?php 
                $this->render_field_checkbox( 
                    'enable_gcm_advanced', 
                    __( 'Google Consent Mode v2 (Advanced)', 'wpcm-agency-hub' ), 
                    $options, 
                    __( 'Override global setting: Enable Advanced Mode for sites using this profile.', 'wpcm-agency-hub' ) 
                );
                
                // ADICIONADO: Checkbox de IP Logging no Perfil
                $this->render_field_checkbox( 
                    'enable_ip_logging', 
                    __( 'IP Address Logging', 'wpcm-agency-hub' ), 
                    $options, 
                    __( 'Override global setting: Enable IP logging for sites using this profile.', 'wpcm-agency-hub' ) 
                ); 
                ?>

                <tr style="border-top: 1px solid #ddd;"><th scope="row"><?php esc_html_e( 'Banner Texts', 'wpcm-agency-hub' ); ?></th><td><hr style="display: none;"></td></tr>
                <?php $this->render_field_text( 'policy_page_url', __( 'Privacy Policy URL', 'wpcm-agency-hub' ), $options, __( 'Use {site_url} to automatically insert the client\'s site URL.', 'wpcm-agency-hub' ) ); ?>
                <?php $this->render_field_textarea( 'banner_text', __( 'Banner Main Text', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_text( 'btn_accept_text', __( 'Accept Button Text', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_text( 'btn_reject_text', __( 'Reject Button Text', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_text( 'btn_settings_text', __( 'Customize Button Text', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_text( 'modal_title', __( 'Modal Title Text', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_text( 'btn_save_text', __( 'Modal Save Button Text', 'wpcm-agency-hub' ), $options ); ?>
                
                <tr style="border-top: 1px solid #ddd;"><th scope="row"><?php esc_html_e( 'iFrame Blocker Content', 'wpcm-agency-hub' ); ?></th><td><hr style="display: none;"></td></tr>
                <?php $this->render_field_checkbox( 'enable_iframe_blocker', __( 'Enable iFrame Blocker', 'wpcm-agency-hub' ), $options, __( 'Enable iFrame Blocker (YouTube, Vimeo, Google Maps).', 'wpcm-agency-hub' ) ); ?>
                <?php $this->render_field_textarea( 'iframe_blocker_text', __( 'iFrame Blocker Text', 'wpcm-agency-hub' ), $options ); ?>
                <?php $this->render_field_text( 'iframe_blocker_button_text', __( 'iFrame Blocker Button', 'wpcm-agency-hub' ), $options ); ?>
                
                <tr style="border-top: 1px solid #ddd;"><th scope="row"><?php esc_html_e( 'Necessary Content', 'wpcm-agency-hub' ); ?></th><td><hr style="display: none;"></td></tr>
                <?php $this->render_field_textarea( 'necessary_desc', __( 'Necessary Description', 'wpcm-agency-hub' ), $options ); ?>
            </table>
        </div>

        <div id="services" class="wpcm-tab-content <?php echo $active_tab == 'services' ? 'active' : ''; ?>">
            <p><?php esc_html_e( 'Select which "Global Services" should be active for this profile. Only the services you check here will be sent to the client.', 'wpcm-agency-hub' ); ?></p>
            <table class="form-table">
                <tbody>
                    <tr>
                        <th><label><?php esc_html_e( 'Apply Global Services', 'wpcm-agency-hub' ); ?></label></th>
                        <td>
                            <?php
                            $global_services = new WP_Query( array(
                                'post_type' => 'wpcm_hub_service',
                                'post_status' => 'publish',
                                'posts_per_page' => -1,
                                'orderby' => 'title',
                                'order' => 'ASC'
                            ) );

                            $selected_services = $options['services'] ?? array();
                            
                            if ( $global_services->have_posts() ) :
                                while ( $global_services->have_posts() ) : $global_services->the_post();
                                    $service_id = get_the_ID();
                                    $checked = in_array( $service_id, $selected_services );
                                    ?>
                                    <fieldset style="margin-bottom: 5px;">
                                        <label>
                                            <input type="checkbox" 
                                                   name="wpcm_profile_settings[services][]" 
                                                   value="<?php echo esc_attr( $service_id ); ?>"
                                                   <?php checked( $checked ); ?>
                                            >
                                            <?php echo esc_html( get_the_title() ); ?>
                                        </label>
                                    </fieldset>
                                <?php
                                endwhile;
                                wp_reset_postdata();
                            else :
                                echo '<p><em>' . esc_html__( 'No Global Services found. Please add services under "Consent Agency Hub > Global Services" first.', 'wpcm-agency-hub' ) . '</em></p>';
                            endif;
                            ?>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <script>
            jQuery(document).ready(function($) {
                // Navegação das abas
                $('.wpcm-metabox-nav .nav-tab').on('click', function(e) {
                    e.preventDefault();
                    var $tab = $(this);
                    var $wrapper = $tab.closest('.postbox');
                    var targetId = $tab.attr('href');
                    
                    $wrapper.find('.wpcm-metabox-nav .nav-tab').removeClass('nav-tab-active');
                    $tab.addClass('nav-tab-active');
                    $wrapper.find('.wpcm-tab-content').removeClass('active');
                    $wrapper.find(targetId).addClass('active');

                    var currentUrl = window.location.href;
                    var newUrl = currentUrl.replace(/&tab=[^&]*/, '') + '&tab=' + targetId.replace('#', '');
                    window.history.replaceState(null, null, newUrl);
                });
            });
        </script>
        <?php
    }

    /**
     * Salva todos os dados do metabox em um único array no post_meta.
     */
    public function save_metabox( $post_id ) {
        // CORREÇÃO: Uso correto de wp_unslash e sanitização do Nonce e Input
        $nonce = isset( $_POST['wpcm_profile_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['wpcm_profile_nonce'] ) ) : '';
        
        if ( ! wp_verify_nonce( $nonce, 'wpcm_profile_save' ) ) { return; }
        if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) ) { return; }
        if ( ! current_user_can( 'edit_post', $post_id ) ) { return; }
        
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- O array é sanitizado chave por chave abaixo.
        $input = isset( $_POST['wpcm_profile_settings'] ) ? wp_unslash( $_POST['wpcm_profile_settings'] ) : array();
        
        if ( ! is_array( $input ) ) { $input = array(); }
        $clean_input = array();
        $defaults = WPCM_Hub_Settings::get_default_options();
        $allowed_positions = array( 'footer', 'modal', 'bottom-left', 'bottom-right' );
        $clean_input['banner_position'] = ( isset( $input['banner_position'] ) && in_array( $input['banner_position'], $allowed_positions ) ) ? $input['banner_position'] : $defaults['banner_position'];
        $clean_input['bg_color']        = isset( $input['bg_color'] ) ? sanitize_hex_color( $input['bg_color'] ) : $defaults['bg_color'];
        $clean_input['text_color']      = isset( $input['text_color'] ) ? sanitize_hex_color( $input['text_color'] ) : $defaults['text_color'];
        $clean_input['btn_accept_bg_color']     = isset( $input['btn_accept_bg_color'] ) ? sanitize_hex_color( $input['btn_accept_bg_color'] ) : $defaults['btn_accept_bg_color'];
        $clean_input['btn_reject_bg_color']     = isset( $input['btn_reject_bg_color'] ) ? sanitize_hex_color( $input['btn_reject_bg_color'] ) : $defaults['btn_reject_bg_color'];
        $clean_input['btn_reject_text_color']   = isset( $input['btn_reject_text_color'] ) ? sanitize_hex_color( $input['btn_reject_text_color'] ) : $defaults['btn_reject_text_color'];
        $clean_input['btn_reject_border_color'] = isset( $input['btn_reject_border_color'] ) ? sanitize_hex_color( $input['btn_reject_border_color'] ) : $defaults['btn_reject_border_color'];
        $clean_input['policy_page_url'] = isset( $input['policy_page_url'] ) ? esc_url_raw( $input['policy_page_url'] ) : $defaults['policy_page_url'];
        $clean_input['banner_text']     = isset( $input['banner_text'] ) ? sanitize_textarea_field( $input['banner_text'] ) : $defaults['banner_text'];
        $clean_input['btn_accept_text'] = isset( $input['btn_accept_text'] ) ? sanitize_text_field( $input['btn_accept_text'] ) : $defaults['btn_accept_text'];
        $clean_input['btn_reject_text'] = isset( $input['btn_reject_text'] ) ? sanitize_text_field( $input['btn_reject_text'] ) : $defaults['btn_reject_text'];
        $clean_input['btn_settings_text'] = isset( $input['btn_settings_text'] ) ? sanitize_text_field( $input['btn_settings_text'] ) : $defaults['btn_settings_text'];
        $clean_input['modal_title']       = isset( $input['modal_title'] ) ? sanitize_text_field( $input['modal_title'] ) : $defaults['modal_title'];
        $clean_input['btn_save_text']     = isset( $input['btn_save_text'] ) ? sanitize_text_field( $input['btn_save_text'] ) : $defaults['btn_save_text'];
        $clean_input['enable_iframe_blocker'] = isset( $input['enable_iframe_blocker'] ) ? '1' : '0';
        $clean_input['enable_gcm_advanced'] = isset( $input['enable_gcm_advanced'] ) ? '1' : '0';

        // ADICIONADO: Salvando IP Logging
        $clean_input['enable_ip_logging'] = isset( $input['enable_ip_logging'] ) ? '1' : '0';

        $clean_input['iframe_blocker_text'] = isset( $input['iframe_blocker_text'] ) ? sanitize_textarea_field( $input['iframe_blocker_text'] ) : $defaults['iframe_blocker_text'];
        $clean_input['iframe_blocker_button_text'] = isset( $input['iframe_blocker_button_text'] ) ? sanitize_text_field( $input['iframe_blocker_button_text'] ) : $defaults['iframe_blocker_button_text'];
        $clean_input['necessary_desc']    = isset( $input['necessary_desc'] ) ? sanitize_textarea_field( $input['necessary_desc'] ) : $defaults['necessary_desc'];
        $clean_input['services'] = array();
        if ( isset( $input['services'] ) && is_array( $input['services'] ) ) {
            $clean_input['services'] = array_map( 'absint', $input['services'] );
        }
        update_post_meta( $post_id, '_wpcm_profile_settings', $clean_input );
    }

    
    /* --- Funções de Renderização de Campo --- */
    
    private function render_field_text( $id, $label, $options, $desc = '' ) {
        $value = $options[$id] ?? ''; ?>
        <tr valign="top">
            <th scope="row"><label for="<?php echo esc_attr($id); ?>"><?php echo esc_html($label); ?></label></th>
            <td>
                <input type="text" id="<?php echo esc_attr($id); ?>" name="wpcm_profile_settings[<?php echo esc_attr($id); ?>]" value="<?php echo esc_attr($value); ?>" class="large-text" />
                <?php if ($desc): ?><p class="description"><?php echo esc_html($desc); ?></p><?php endif; ?>
            </td>
        </tr>
    <?php }

    private function render_field_textarea( $id, $label, $options, $desc = '' ) {
        $value = $options[$id] ?? ''; ?>
        <tr valign="top">
            <th scope="row"><label for="<?php echo esc_attr($id); ?>"><?php echo esc_html($label); ?></label></th>
            <td>
                <textarea id="<?php echo esc_attr($id); ?>" name="wpcm_profile_settings[<?php echo esc_attr($id); ?>]" rows="5" class="large-text"><?php echo esc_textarea($value); ?></textarea>
                <?php if ($desc): ?><p class="description"><?php echo esc_html($desc); ?></p><?php endif; ?>
            </td>
        </tr>
    <?php }

    private function render_field_checkbox( $id, $label, $options, $desc = '' ) {
        $value = $options[$id] ?? '0'; ?>
        <tr valign="top">
            <th scope="row"><label for="<?php echo esc_attr($id); ?>"><?php echo esc_html($label); ?></label></th>
            <td>
                <fieldset>
                    <input type="hidden" name="wpcm_profile_settings[<?php echo esc_attr($id); ?>]" value="0">
                    <input type="checkbox" id="<?php echo esc_attr($id); ?>" name="wpcm_profile_settings[<?php echo esc_attr($id); ?>]" value="1" <?php checked( $value, '1' ); ?> />
                    <label for="<?php echo esc_attr($id); ?>"><?php echo esc_html($desc); ?></label>
                </fieldset>
            </td>
        </tr>
    <?php }

    private function render_field_select( $id, $label, $options, $choices, $desc = '' ) {
        $value = $options[$id] ?? ''; ?>
        <tr valign="top">
            <th scope="row"><label for="<?php echo esc_attr($id); ?>"><?php echo esc_html($label); ?></label></th>
            <td>
                <select id="<?php echo esc_attr($id); ?>" name="wpcm_profile_settings[<?php echo esc_attr($id); ?>]">
                    <?php foreach ($choices as $val => $name): ?>
                        <option value="<?php echo esc_attr($val); ?>" <?php selected($value, $val); ?>><?php echo esc_html($name); ?></option>
                    <?php endforeach; ?>
                </select>
                <?php if ($desc): ?><p class="description"><?php echo esc_html($desc); ?></p><?php endif; ?>
            </td>
        </tr>
    <?php }

    private function render_field_color( $id, $label, $options, $desc = '' ) {
        $value = $options[$id] ?? '';
        $default = WPCM_Hub_Settings::get_default_options()[$id] ?? '#000000'; ?>
        <tr valign="top">
            <th scope="row"><label for="<?php echo esc_attr($id); ?>"><?php echo esc_html($label); ?></label></th>
            <td>
                <input type="text" id="<?php echo esc_attr($id); ?>" name="wpcm_profile_settings[<?php echo esc_attr($id); ?>]" value="<?php echo esc_attr($value); ?>" class="wpcm-color-picker" data-default-color="<?php echo esc_attr($default); ?>" />
                <?php if ($desc): ?><p class="description"><?php echo esc_html($desc); ?></p><?php endif; ?>
            </td>
        </tr>
    <?php }
}