<?php

namespace WeDevs\Wpuf\Pro\AI_Review;

/**
 * AI Review Column for Posts Table
 *
 * Adds AI review status column to WordPress Posts table with sorting and filtering
 * for all public post types.
 *
 * @since 4.2.5
 */
class Post_Table {

    /**
     * Cached list of allowed screen IDs for supported post types
     *
     * @since 4.2.13
     *
     * @var array|null
     */
    private $allowed_screens = null;

    /**
     * Constructor
     */
    public function __construct() {
        $this->init_hooks();
    }

    /**
     * Initialize hooks
     *
     * @since 4.2.5
     */
    public function init_hooks() {
        // Defer CPT-specific hook registration to admin_init so all post types are registered
        add_action( 'admin_init', [ $this, 'register_column_hooks' ] );

        // These hooks work globally and check screen context internally
        add_action( 'restrict_manage_posts', [ $this, 'add_filter_dropdown' ] );
        add_action( 'pre_get_posts', [ $this, 'handle_filtering' ] );
        add_action( 'pre_get_posts', [ $this, 'handle_sorting' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
    }

    /**
     * Register column hooks for all public post types
     *
     * Deferred to admin_init to ensure all CPTs are registered.
     *
     * @since 4.2.13
     *
     * @return void
     */
    public function register_column_hooks() {
        $post_types = get_post_types( [ 'public' => true ] );

        foreach ( $post_types as $post_type ) {
            // Priority 20 ensures we run after plugins like WooCommerce that rebuild
            // the columns array at priority 10, so our "before date" insertion works
            add_filter( "manage_{$post_type}_posts_columns", [ $this, 'add_ai_review_column' ], 20 );
            add_action( "manage_{$post_type}_posts_custom_column", [ $this, 'render_ai_review_column' ], 10, 2 );
            add_filter( "manage_edit-{$post_type}_sortable_columns", [ $this, 'make_column_sortable' ] );

            // Some plugins (e.g. Easy Digital Downloads) use the screen-level
            // column filter which runs after the post-type-level filter and
            // replaces the entire columns array. Hook into it at a late priority
            // so our column survives.
            add_filter( "manage_edit-{$post_type}_columns", [ $this, 'add_ai_review_column' ], 20 );
        }
    }

    /**
     * Check if the current screen is a supported post type list screen
     *
     * @since 4.2.13
     *
     * @return bool
     */
    private function is_supported_screen() {
        $screen = get_current_screen();

        if ( ! $screen ) {
            return false;
        }

        if ( $this->allowed_screens === null ) {
            $post_types            = get_post_types( [ 'public' => true ] );
            $this->allowed_screens = array_map(
                function ( $pt ) {
                    return 'edit-' . $pt;
                },
                $post_types
            );
        }

        return in_array( $screen->id, $this->allowed_screens, true );
    }

    /**
     * Add AI Review column to posts table
     *
     * @since 4.2.5
     *
     * @param array $columns Existing columns
     * @return array Modified columns
     */
    public function add_ai_review_column( $columns ) {
        if ( ! $this->is_supported_screen() || isset( $columns['ai_review'] ) ) {
            return $columns;
        }

        // Insert AI Review column before the date column
        $new_columns = [];
        $inserted    = false;

        foreach ( $columns as $key => $value ) {
            if ( $key === 'date' ) {
                $new_columns['ai_review'] = __( 'AI Review', 'wpuf-pro' );
                $inserted = true;
            }
            $new_columns[ $key ] = $value;
        }

        // If no 'date' column exists (e.g. The Events Calendar replaces it),
        // append the AI Review column at the end.
        if ( ! $inserted ) {
            $new_columns['ai_review'] = __( 'AI Review', 'wpuf-pro' );
        }

        return $new_columns;
    }

    /**
     * Render AI Review column content
     *
     * @since 4.2.5
     *
     * @param string $column_name Column name
     * @param int    $post_id     Post ID
     */
    public function render_ai_review_column( $column_name, $post_id ) {
        if ( ! $this->is_supported_screen() ) {
            return;
        }

        if ( $column_name !== 'ai_review' ) {
            return;
        }

        $status = get_post_meta( $post_id, 'wpuf_ai_review_status', true );

        if ( ! $status ) {
            $can_retry = current_user_can( 'manage_options' );
            $clickable_class = $can_retry ? ' clickable' : '';
            $data_attrs = $can_retry ? sprintf(
            ' data-post-id="%d" data-status="no_review"',
            esc_attr( $post_id )
            ) : '';

            printf(
            '<span class="wpuf-ai-circle wpuf-ai-circle-gray%s" title="%s"%s>%s</span>',
            $clickable_class,
            esc_attr( __( 'No Review - Click to retry', 'wpuf-pro' ) ),
            $data_attrs,
            esc_html( '—' )
            );
            return;
        }

        // Get summary from the full review data if available
        $review = get_post_meta( $post_id, 'wpuf_ai_post_review', true );
        $summary = ( $review && isset( $review['summary'] ) ) ? $review['summary'] : '';

        // Define status icons and colors
        $status_config = [
            'full'         => [
                'icon'  => '●',
                'class' => 'wpuf-ai-circle-green',
                'title' => $summary ?: __( 'Full Match - Meets all criteria', 'wpuf-pro' ),
            ],
            'medium'       => [
                'icon'  => '●',
                'class' => 'wpuf-ai-circle-yellow',
                'title' => $summary ?: __( 'Medium Match - Partially meets criteria', 'wpuf-pro' ),
            ],
            'none'         => [
                'icon'  => '●',
                'class' => 'wpuf-ai-circle-red',
                'title' => $summary ?: __( 'No Match - Does not meet criteria', 'wpuf-pro' ),
            ],
            'failed'       => [
                'icon'  => '●',
                'class' => 'wpuf-ai-circle-gray',
                'title' => $summary ?: __( 'Review Failed', 'wpuf-pro' ),
            ],
            'pending'      => [
                'icon'  => '○',
                'class' => 'wpuf-ai-circle-blue',
                'title' => __( 'Review Pending - Scheduled for processing', 'wpuf-pro' ),
            ],
            'in_progress'  => [
                'icon'  => '⟳',
                'class' => 'wpuf-ai-circle-orange',
                'title' => __( 'Review In Progress - Currently being processed', 'wpuf-pro' ),
            ],
        ];

        if ( ! isset( $status_config[ $status ] ) ) {
            echo '—';
            return;
        }

        $config = $status_config[ $status ];
        $tooltip_text = wp_kses_post( $config['title'] ); // Allow basic HTML but sanitize properly
        $tooltip_attr = esc_attr( strip_tags( $config['title'] ) ); // Plain text for attribute

        // Check if user can retry (has manage_options capability)
        $can_retry = current_user_can( 'manage_options' );
        $clickable_class = $can_retry ? ' clickable' : '';
        $data_attrs = $can_retry ? sprintf(
            ' data-post-id="%d" data-status="%s" data-summary="%s"',
            esc_attr( $post_id ),
            esc_attr( $status ),
            esc_attr( strip_tags( $summary ) )
        ) : '';

        printf(
            '<span class="wpuf-ai-circle %s%s" data-tooltip="%s" title="%s"%s>%s</span>',
            esc_attr( $config['class'] ),
            $clickable_class,
            $tooltip_attr,
            $tooltip_attr,
            $data_attrs,
            esc_html( $config['icon'] )
        );
    }

    /**
     * Make AI Review column sortable
     *
     * @since 4.2.5
     *
     * @param array $sortable_columns Existing sortable columns
     * @return array Modified sortable columns
     */
    public function make_column_sortable( $sortable_columns ) {
        if ( ! $this->is_supported_screen() ) {
            return $sortable_columns;
        }

        $sortable_columns['ai_review'] = 'ai_review_status';
        return $sortable_columns;
    }

    /**
     * Add filter dropdown for AI review status
     *
     * @since 4.2.5
     */
    public function add_filter_dropdown() {
        if ( ! $this->is_supported_screen() ) {
            return;
        }

        $current_filter = isset( $_GET['ai_review_filter'] ) ? sanitize_key( wp_unslash( $_GET['ai_review_filter'] ) ) : '';

        $filter_options = [
            ''           => __( 'All Reviews', 'wpuf-pro' ),
            'full'       => __( 'Full Match', 'wpuf-pro' ),
            'medium'     => __( 'Medium Match', 'wpuf-pro' ),
            'none'       => __( 'No Match', 'wpuf-pro' ),
            'failed'     => __( 'Failed', 'wpuf-pro' ),
            'pending'    => __( 'Pending', 'wpuf-pro' ),
            'in_progress' => __( 'In Progress', 'wpuf-pro' ),
            'no_review'  => __( 'No Review', 'wpuf-pro' ),
        ];

        echo '<select name="ai_review_filter" id="ai_review_filter">';
        foreach ( $filter_options as $value => $label ) {
            printf(
                '<option value="%s"%s>%s</option>',
                esc_attr( $value ),
                selected( $current_filter, $value, false ),
                esc_html( $label )
            );
        }
        echo '</select>';

        // Add nonce field for security
        wp_nonce_field( 'ai_review_filter', 'ai_review_filter_nonce' );
    }

    /**
     * Handle filtering by AI review status
     *
     * @since 4.2.5
     *
     * @param \WP_Query $query Query object
     */
    public function handle_filtering( $query ) {
        if ( ! is_admin() || ! $query->is_main_query() ) {
            return;
        }

        // Verify nonce for security
        $nonce = isset( $_REQUEST['ai_review_filter_nonce'] ) ? wp_unslash( $_REQUEST['ai_review_filter_nonce'] ) : '';
        if ( ! wp_verify_nonce( $nonce, 'ai_review_filter' ) ) {
            return;
        }

        $filter = isset( $_GET['ai_review_filter'] ) ? sanitize_key( wp_unslash( $_GET['ai_review_filter'] ) ) : '';
        $allowed_filters = [ 'full', 'medium', 'none', 'failed', 'pending', 'in_progress', 'no_review' ];

        if ( empty( $filter ) || ! in_array( $filter, $allowed_filters, true ) ) {
            return;
        }

        $meta_query = $query->get( 'meta_query' );
        if ( ! is_array( $meta_query ) ) {
            $meta_query = [];
        }

        if ( $filter === 'no_review' ) {
            // Posts without AI review status
            $meta_query[] = [
                'relation' => 'OR',
                [
                    'key'     => 'wpuf_ai_review_status',
                    'compare' => 'NOT EXISTS',
                ],
                [
                    'key'     => 'wpuf_ai_review_status',
                    'value'   => '',
                    'compare' => '=',
                ],
            ];
        } else {
            // Posts with specific review status
            $meta_query[] = [
                'key'     => 'wpuf_ai_review_status',
                'value'   => $filter,
                'compare' => '=',
            ];
        }

        $query->set( 'meta_query', $meta_query );
    }

    /**
     * Handle sorting by AI review status
     *
     * @since 4.2.5
     *
     * @param \WP_Query $query Query object
     */
    public function handle_sorting( $query ) {
        if ( ! is_admin() || ! $query->is_main_query() ) {
            return;
        }

        if ( ! $this->is_supported_screen() ) {
            return;
        }

        $orderby = $query->get( 'orderby' );

        if ( $orderby !== 'ai_review_status' ) {
            return;
        }

        // Set meta query for AI review data
        $query->set( 'meta_key', 'wpuf_ai_review_status' );
        $query->set( 'orderby', 'meta_value' );

        // Add custom sorting logic via filter
        add_filter( 'posts_orderby', [ $this, 'custom_ai_review_orderby' ], 10, 2 );
    }

    /**
     * Custom orderby for AI review status
     *
     * @since 4.2.5
     *
     * @param string   $orderby Current ORDER BY clause
     * @param WP_Query $query  Query object
     * @return string Modified ORDER BY clause
     */
    public function custom_ai_review_orderby( $orderby, $query ) {
        global $wpdb;

        // Remove the filter to avoid infinite recursion
        remove_filter( 'posts_orderby', [ $this, 'custom_ai_review_orderby' ], 10 );

        // Escape table names for security
        $meta_table = esc_sql( $wpdb->postmeta );
        $posts_table = esc_sql( $wpdb->posts );

        // Escape status values for security
        $status_full = esc_sql( 'full' );
        $status_medium = esc_sql( 'medium' );
        $status_none = esc_sql( 'none' );
        $status_failed = esc_sql( 'failed' );
        $status_pending = esc_sql( 'pending' );
        $status_in_progress = esc_sql( 'in_progress' );

        // Custom SQL for sorting AI review status
        // Note: Table names and status values are already escaped with esc_sql()
        $orderby = sprintf(
            "CASE
                WHEN %s.meta_value = '%s' THEN 1
                WHEN %s.meta_value = '%s' THEN 2
                WHEN %s.meta_value = '%s' THEN 3
                WHEN %s.meta_value = '%s' THEN 4
                WHEN %s.meta_value = '%s' THEN 5
                WHEN %s.meta_value = '%s' THEN 6
                ELSE 7
            END ASC, %s.post_date DESC",
            $meta_table, $status_full,
            $meta_table, $status_medium,
            $meta_table, $status_none,
            $meta_table, $status_failed,
            $meta_table, $status_pending,
            $meta_table, $status_in_progress,
            $posts_table
        );

        return $orderby;
    }

    /**
     * Enqueue assets for AI review column
     *
     * @since 4.2.5
     */
    public function enqueue_assets() {
        if ( ! $this->is_supported_screen() ) {
            return;
        }

        // Enqueue CSS for AI review circles
        wp_enqueue_style(
            'wpuf-ai-review-column',
            WPUF_PRO_ASSET_URI . '/css/wpuf-ai-review.css',
            [],
            WPUF_PRO_VERSION
        );

        // Enqueue JavaScript for tooltips
        wp_enqueue_script(
            'wpuf-ai-review-column',
            WPUF_PRO_ASSET_URI . '/js/wpuf-ai-review-column.js',
            [ 'jquery' ],
            WPUF_PRO_VERSION,
            true
        );

        // Localize script with i18n strings
        wp_localize_script(
            'wpuf-ai-review-column',
            'wpufAIReview',
            [
                'rest_url'   => esc_url_raw( rest_url() ),
                'rest_nonce' => wp_create_nonce( 'wp_rest' ),
                'i18n' => [
                    'full'       => __( 'Full Match', 'wpuf-pro' ),
                    'medium'     => __( 'Medium Match', 'wpuf-pro' ),
                    'none'       => __( 'No Match', 'wpuf-pro' ),
                    'failed'     => __( 'Failed', 'wpuf-pro' ),
                    'pending'    => __( 'Pending', 'wpuf-pro' ),
                    'inProgress' => __( 'In Progress', 'wpuf-pro' ),
                    'confirmRetry'   => __( 'Retry AI review for this post?', 'wpuf-pro' ),
                    'currentStatus'  => __( 'Current status', 'wpuf-pro' ),
                    'summary'        => __( 'Summary', 'wpuf-pro' ),
                    'retryFailed'    => __( 'Retry failed', 'wpuf-pro' ),
                    'requestFailed'  => __( 'Request failed. Please try again.', 'wpuf-pro' ),
                ],
            ]
        );
    }
}
