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

/**
 * ATUALIZADO (Sprint 8): Adiciona o botão "Testar Conexão"
 */
class WPCM_Hub_CPT_Sites {

    public function __construct() {
        add_action( 'init', array( $this, 'register_post_type' ) );
        add_action( 'add_meta_boxes', array( $this, 'add_metabox' ) );
        add_action( 'save_post_wpcm_hub_site', array( $this, 'save_metabox' ) );
        add_action( 'redirect_post_location', array( $this, 'redirect_after_publish' ), 10, 2 );
    }

    public function register_post_type() {
        $labels = array(
            'name'               => __( 'Connected Sites', 'wpcm-agency-hub' ),
            'singular_name'      => __( 'Site', 'wpcm-agency-hub' ),
            'add_new'            => __( 'Add New Site', 'wpcm-agency-hub' ),
            'add_new_item'       => __( 'Add New Site', 'wpcm-agency-hub' ),
            'edit_item'          => __( 'Edit Site', 'wpcm-agency-hub' ),
            'all_items'          => __( 'All Connected Sites', 'wpcm-agency-hub' ),
            'menu_name'          => __( 'Consent Agency Hub', 'wpcm-agency-hub' )
        );
        $args = array(
            'labels'              => $labels,
            'public'              => false,
            'show_ui'             => true,
            'show_in_menu'        => true,
            'menu_position'       => 30,
            'menu_icon'           => 'dashicons-networking',
            'supports'            => array( 'title' ),
            'hierarchical'        => false,
            'has_archive'         => false,
            'rewrite'             => false,
        );
        register_post_type( 'wpcm_hub_site', $args );
    }

    public function add_metabox() {
        add_meta_box(
            'wpcm_hub_site_settings',
            __( 'Site Connection Details', 'wpcm-agency-hub' ),
            array( $this, 'render_metabox' ),
            'wpcm_hub_site',
            'normal',
            'high'
        );
    }

    /**
     * ATUALIZADO: Adiciona o botão e a área de status do teste
     */
    public function render_metabox( $post ) {
        wp_nonce_field( 'wpcm_hub_site_save', 'wpcm_hub_site_nonce' );
        
        $site_url  = get_post_meta( $post->ID, '_site_url', true );
        $api_key   = get_post_meta( $post->ID, '_api_key', true );
        $status    = get_post_meta( $post->ID, '_status', true ) ?: 'disconnected';
        
        $assigned_profile = get_post_meta( $post->ID, '_wpcm_assigned_profile', true );
        $disable_ssl = get_post_meta( $post->ID, '_disable_sslverify', true );

        $profiles = new WP_Query( array(
            'post_type' => 'wpcm_hub_profile',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC'
        ));

        if ( empty( $api_key ) ) {
            $api_key = 'sk_' . wp_generate_password( 40, false );
        }

        ?>
        <table class="form-table">
            <tbody>
                <tr>
                    <th><label for="wpcm_site_url"><?php esc_html_e( 'Site URL', 'wpcm-agency-hub' ); ?></label></th>
                    <td>
                        <input type="url" name="wpcm_site_url" id="wpcm_site_url" class="large-text" 
                               value="<?php echo esc_url( $site_url ); ?>" 
                               placeholder="https://client-site.com">
                        <p class="description"><?php esc_html_e( 'The full URL of the client WordPress site.', 'wpcm-agency-hub' ); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><label for="wpcm_api_key"><?php esc_html_e( 'Site API Key', 'wpcm-agency-hub' ); ?></label></th>
                    <td>
                        <input type="text" name="wpcm_api_key" id="wpcm_api_key" class="large-text" 
                               value="<?php echo esc_attr( $api_key ); ?>" readonly>
                        <p class="description"><?php esc_html_e( 'Copy this key and paste it into the "Agency Hub" tab on the client site.', 'wpcm-agency-hub' ); ?></p>
                    </td>
                </tr>
                 <tr>
                    <th><?php esc_html_e( 'Status', 'wpcm-agency-hub' ); ?></th>
                    <td>
                        <?php if ( $status === 'connected' ) : ?>
                            <strong style="color: #10b981;"><?php esc_html_e( 'Connected', 'wpcm-agency-hub' ); ?></strong>
                        <?php else : ?>
                            <strong style="color: #ef4444;"><?php esc_html_e( 'Disconnected', 'wpcm-agency-hub' ); ?></strong>
                        <?php endif; ?>
                    </td>
                </tr>

                <tr>
                    <th><?php esc_html_e( 'Test Connection', 'wpcm-agency-hub' ); ?></th>
                    <td>
                        <button type="button" class="button" id="wpcm-hub-test-connection" data-postid="<?php echo esc_attr( $post->ID ); ?>">
                            <?php esc_html_e( 'Run Test', 'wpcm-agency-hub' ); ?>
                        </button>
                        <span class="spinner" style="float: none; vertical-align: middle;"></span>
                        <em id="wpcm-hub-test-status" style="margin-left: 10px;"></em>
                    </td>
                </tr>
                <tr style="border-top: 1px solid #ddd;">
                    <th><label for="wpcm_assigned_profile"><?php esc_html_e( 'Assign Config. Profile', 'wpcm-agency-hub' ); ?></label></th>
                    <td>
                        <select name="wpcm_assigned_profile" id="wpcm_assigned_profile" class="large-text">
                            <option value="0" <?php selected( $assigned_profile, 0 ); ?>>
                                <?php esc_html_e( '— Use Global Settings —', 'wpcm-agency-hub' ); ?>
                            </option>
                            
                            <?php
                            if ( $profiles->have_posts() ) {
                                while ( $profiles->have_posts() ) {
                                    $profiles->the_post();
                                    $profile_id = get_the_ID();
                                    $profile_title = get_the_title();
                                    ?>
                                    <option value="<?php echo esc_attr( $profile_id ); ?>" <?php selected( $assigned_profile, $profile_id ); ?>>
                                        <?php echo esc_html( $profile_title ); ?>
                                    </option>
                                    <?php
                                }
                                wp_reset_postdata();
                            }
                            ?>
                        </select>
                        <p class="description"><?php esc_html_e( 'Select a specific profile to override the "Global Settings" for this site.', 'wpcm-agency-hub' ); ?></p>
                    </td>
                </tr>
                
                <tr style="border-top: 1px solid #ddd;">
                    <th><label for="wpcm_disable_sslverify"><?php esc_html_e( 'Connection Security', 'wpcm-agency-hub' ); ?></label></th>
                    <td>
                        <fieldset>
                            <input type="checkbox" name="wpcm_disable_sslverify" id="wpcm_disable_sslverify" value="1" <?php checked( $disable_ssl, '1' ); ?>>
                            <label for="wpcm_disable_sslverify"><?php esc_html_e( 'Disable SSL Verification', 'wpcm-agency-hub' ); ?></label>
                            <p class="description" style="color:#c93535;">
                                <?php esc_html_e( 'Warning: Only check this if sync is failing due to a self-signed SSL certificate. This is insecure and disables security checks for this site.', 'wpcm-agency-hub' ); ?>
                            </p>
                        </fieldset>
                    </td>
                </tr>
                </tbody>
        </table>
        <?php
    }

    public function save_metabox( $post_id ) {
        $nonce = isset( $_POST['wpcm_hub_site_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['wpcm_hub_site_nonce'] ) ) : '';
        if ( ! $nonce || ! wp_verify_nonce( $nonce, 'wpcm_hub_site_save' ) ) return;
        if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || wp_is_post_revision( $post_id ) ) return;
        if ( ! current_user_can( 'edit_post', $post_id ) ) return;
        if ( isset( $_POST['wpcm_site_url'] ) ) {
            update_post_meta( $post_id, '_site_url', esc_url_raw( wp_unslash( $_POST['wpcm_site_url'] ) ) );
        }
        if ( isset( $_POST['wpcm_api_key'] ) ) {
            $existing_key = get_post_meta( $post_id, '_api_key', true );
            if ( empty( $existing_key ) ) {
                update_post_meta( $post_id, '_api_key', sanitize_text_field( wp_unslash( $_POST['wpcm_api_key'] ) ) );
                update_post_meta( $post_id, '_status', 'disconnected' );
            }
        }
        if ( isset( $_POST['wpcm_assigned_profile'] ) ) {
            $profile_id = absint( $_POST['wpcm_assigned_profile'] );
            update_post_meta( $post_id, '_wpcm_assigned_profile', $profile_id );
        }
        $disable_ssl = isset( $_POST['wpcm_disable_sslverify'] ) ? '1' : '0';
        update_post_meta( $post_id, '_disable_sslverify', $disable_ssl );
    }
    
    public function redirect_after_publish( $location, $post_id ) {
        // CORREÇÃO: Adicionado phpcs:ignore pois a verificação de nonce já ocorreu no save_post.
        // Aqui apenas decidimos o redirect visual.
        
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if ( ! isset( $_POST['save'] ) && ! isset( $_POST['publish'] ) ) return $location;
        
        $post = get_post( $post_id );
        if ( ! $post || $post->post_type !== 'wpcm_hub_site' ) return $location;
        
        // phpcs:ignore WordPress.Security.NonceVerification.Missing
        if ( isset( $_POST['publish'] ) || isset( $_POST['save'] ) ) {
            $location = remove_query_arg( 'message', $location ); 
            $location = add_query_arg( array( 'post_type' => 'wpcm_hub_site' ), admin_url( 'edit.php' ) );
        }
        return $location;
    }
}