<?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
 *
 * @since 4.2.5
 */
class Post_Table {

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

    /**
     * Initialize hooks
     *
     * @since 4.2.5
     */
    public function init_hooks() {
        // Add hooks immediately, but check screen in each method
        add_filter( 'manage_post_posts_columns', [ $this, 'add_ai_review_column' ] );
        add_action( 'manage_post_posts_custom_column', [ $this, 'render_ai_review_column' ], 10, 2 );
        add_filter( 'manage_edit-post_sortable_columns', [ $this, 'make_column_sortable' ] );
        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' ] );
    }


    /**
     * 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 ) {
        // Only add column on post list screen
        $screen = get_current_screen();
        if ( ! $screen || $screen->id !== 'edit-post' ) {
            return $columns;
        }

        // Insert AI Review column before the date column
        $new_columns = [];
        foreach ( $columns as $key => $value ) {
            if ( $key === 'date' ) {
                $new_columns['ai_review'] = __( 'AI Review', 'wpuf-pro' );
            }
            $new_columns[ $key ] = $value;
        }

        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 ) {
        // Only render on post list screen
        $screen = get_current_screen();
        if ( ! $screen || $screen->id !== 'edit-post' ) {
            return;
        }

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

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

        if ( ! $status ) {
            echo '—';
            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

        printf(
            '<span class="wpuf-ai-circle %s" data-tooltip="%s" title="%s">%s</span>',
            esc_attr( $config['class'] ),
            $tooltip_attr,
            $tooltip_attr,
            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 ) {
        // Only add sortable on post list screen
        $screen = get_current_screen();
        if ( ! $screen || $screen->id !== 'edit-post' ) {
            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() {
        // Only add filter on post list screen
        $screen = get_current_screen();
        if ( ! $screen || $screen->id !== 'edit-post' ) {
            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;
        }

        // Only add sorting on post list screen
        $screen = get_current_screen();
        if ( ! $screen || $screen->id !== 'edit-post' ) {
            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() {
        $screen = get_current_screen();

        if ( ! $screen || $screen->id !== 'edit-post' ) {
            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
        );
    }
}
