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

if ( ! class_exists( 'WP_List_Table' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}

/**
 * ATUALIZADO (Sprint 7): Traduz os IDs de serviço em nomes legíveis.
 */
class WPCM_Hub_Log_Table extends WP_List_Table {

    private $service_names = array();

    public function __construct() {
        parent::__construct( array(
            'singular' => __( 'Consent Log', 'wpcm-agency-hub' ),
            'plural'   => __( 'Consent Logs', 'wpcm-agency-hub' ),
            'ajax'     => false
        ) );
    }

    public function get_columns() {
        return array(
            'site_name'          => __( 'Site', 'wpcm-agency-hub' ),
            'user_hash'          => __( 'User (Hashed)', 'wpcm-agency-hub' ),
            'ip_address'         => __( 'IP Address', 'wpcm-agency-hub' ), 
            'consent_categories' => __( 'Consents Given', 'wpcm-agency-hub' ),
            'policy_version'     => __( 'Policy Version', 'wpcm-agency-hub' ),
            'timestamp'          => __( 'Date & Time', 'wpcm-agency-hub' )
        );
    }

    public function get_sortable_columns() {
        return array(
            'timestamp' => array( 'timestamp', true ),
            'site_name' => array( 'site_name', false ),
        );
    }

    protected function extra_tablenav( $which ) {
        if ( $which !== 'top' ) {
            return;
        }
        
        $sites_query = new WP_Query( array(
            'post_type'      => 'wpcm_hub_site',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'orderby'        => 'title',
            'order'          => 'ASC',
            'no_found_rows'  => true,
        ) );

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $current_filter = isset( $_GET['filter_site_id'] ) ? absint( $_GET['filter_site_id'] ) : 0;

        echo '<div class="alignleft actions">';
        
        echo '<select name="filter_site_id" style="margin-right:5px;">';
        echo '<option value="0">' . esc_html__( 'All Connected Sites', 'wpcm-agency-hub' ) . '</option>';
        
        if ( $sites_query->have_posts() ) {
            while ( $sites_query->have_posts() ) {
                $sites_query->the_post();
                $id = get_the_ID();
                $title = get_the_title();
                echo '<option value="' . esc_attr( $id ) . '" ' . selected( $current_filter, $id, false ) . '>' . esc_html( $title ) . '</option>';
            }
            wp_reset_postdata();
        }
        echo '</select>';

        submit_button( __( 'Filter', 'wpcm-agency-hub' ), 'button', 'filter_action', false );
        echo '</div>';


        // --- Botão Exportar CSV ---
        ?>
        <div class="alignright actions">
            <?php
            $export_args = array(
                'page'               => 'wpcm_hub_logs',
                'wpcm_hub_action'    => 'export_csv',
                'filter_site_id'     => $current_filter,
                'wpcm_export_nonce'  => wp_create_nonce( 'wpcm_hub_export_csv_nonce' )
            );
            $export_url = add_query_arg( $export_args, admin_url( 'edit.php?post_type=wpcm_hub_site' ) );
            ?>
            <a href="<?php echo esc_url( $export_url ); ?>" class="button button-secondary" title="<?php esc_attr_e( 'Export current view to CSV', 'wpcm-agency-hub' ); ?>">
                <span class="dashicons dashicons-download" style="margin-top: 4px;"></span> <?php esc_html_e( 'Export CSV', 'wpcm-agency-hub' ); ?>
            </a>
        </div>
        <?php
    }

    public function column_default( $item, $column_name ) {
        switch ( $column_name ) {
            case 'site_name': return '<strong>' . esc_html( $item->site_name ) . '</strong>';
            case 'user_hash': $hash = esc_attr( $item->user_hash ); return '<code title="' . $hash . '">' . esc_html( substr( $hash, 0, 12 ) ) . '...</code>';
            case 'ip_address':
                $ip = ! empty( $item->ip_address ) ? esc_html( $item->ip_address ) : '';
                if ( empty( $ip ) ) { return '<em style="color:#999;">' . esc_html__( 'Not stored', 'wpcm-agency-hub' ) . '</em>'; }
                return '<code>' . $ip . '</code>';
            case 'consent_categories':
                $categories = explode( ',', $item->consent_categories );
                $badges = array();
                
                foreach ( $categories as $cat ) {
                    $cat = trim( $cat );
                    if ( empty($cat) ) continue;

                    if ( strpos( $cat, 'service_hub_' ) === 0 ) {
                        $service_name = $this->service_names[ $cat ] ?? '';
                        if ( $service_name ) {
                            $badges[] = '<span class="wpcm-badge wpcm-badge-service">' . esc_html( $service_name ) . '</span>';
                        }
                    } else {
                        $badges[] = '<span class="wpcm-badge wpcm-badge-' . esc_attr( $cat ) . '">' . esc_html( ucfirst( $cat ) ) . '</span>';
                    }
                }
                return implode( ' ', $badges );

            case 'policy_version': return '<span class="wpcm-version-tag">' . esc_html( $item->policy_version ) . '</span>';
            case 'timestamp':
                $date = strtotime( $item->timestamp );
                return date_i18n( get_option( 'date_format' ), $date ) . ' <span style="color:#999">' . date_i18n( get_option( 'time_format' ), $date ) . '</span>';
            default: return 'N/A';
        }
    }

    private function prepare_service_names() {
        $services_query = new WP_Query( array(
            'post_type'              => 'wpcm_hub_service',
            'post_status'            => 'any',
            'posts_per_page'         => -1,
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        if ( $services_query->have_posts() ) {
            foreach ( $services_query->posts as $post ) {
                $id_num = $post->ID;
                $title = $post->post_title;
                $id_key = 'service_hub_' . $id_num;
                $this->service_names[ $id_key ] = $title;
            }
        }
    }

    public function prepare_items() {
        global $wpdb;

        $this->prepare_service_names();

        $this->_column_headers = $this->get_column_info();
        $per_page = 20;
        $current_page = $this->get_pagenum();
        $offset = ( $current_page - 1 ) * $per_page;

        $log_table = $wpdb->prefix . 'wpcm_hub_logs';
        $posts_table = $wpdb->prefix . 'posts';

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $filter_site_id = isset( $_GET['filter_site_id'] ) ? absint( $_GET['filter_site_id'] ) : 0;
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $orderby = isset( $_GET['orderby'] ) ? sanitize_key( $_GET['orderby'] ) : 'timestamp';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $order = isset( $_GET['order'] ) ? sanitize_key( $_GET['order'] ) : 'DESC';

        $valid_orderby = array( 'timestamp', 'site_name' );
        if ( ! in_array( $orderby, $valid_orderby ) ) { $orderby = 'timestamp'; }
        if ( ! in_array( strtoupper( $order ), array( 'ASC', 'DESC' ) ) ) { $order = 'DESC'; }

        $where_clauses = array( '1=1' );
        $prepare_args = array();

        if ( $filter_site_id > 0 ) {
            $where_clauses[] = 't_log.site_post_id = %d';
            $prepare_args[] = $filter_site_id;
        }

        $where_sql = implode( ' AND ', $where_clauses );

        // Consulta para o Total de Itens
        if ( ! empty( $prepare_args ) ) {
            // CORREÇÃO: Flags completas para cobrir a interpolação e a contagem de argumentos.
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
            $total_items = $wpdb->get_var(
                $wpdb->prepare( "SELECT COUNT(t_log.id) FROM $log_table AS t_log WHERE $where_sql", $prepare_args )
            );
        } else {
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $total_items = $wpdb->get_var( "SELECT COUNT(t_log.id) FROM $log_table AS t_log WHERE $where_sql" );
        }

        // Consulta para os Itens da Página (com JOIN)
        $prepare_args[] = $per_page;
        $prepare_args[] = $offset;

        // CORREÇÃO: Flags completas para cobrir a interpolação, ordenação e contagem de argumentos.
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
        $this->items = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT t_log.*, t_posts.post_title AS site_name 
                 FROM $log_table AS t_log
                 LEFT JOIN $posts_table AS t_posts ON t_log.site_post_id = t_posts.ID
                 WHERE $where_sql
                 ORDER BY $orderby $order
                 LIMIT %d OFFSET %d",
                $prepare_args
            )
        );

        // Configuração da Paginação
        $this->set_pagination_args( array(
            'total_items' => $total_items,
            'per_page'    => $per_page,
        ) );
    }
}