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

/**
 * Adds a sortable "SEO" column to the posts/pages list tables showing the
 * combined SEO score (computed in the editor and stored in _seo_fury_seo_score)
 * as a coloured dot + number. Gives an at-a-glance, sortable overview of which
 * content needs attention across the whole site.
 */
class SEO_Fury_Posts_Column {

    const META_KEY = '_seo_fury_seo_score';

    public function __construct() {
        add_action( 'admin_init', array( $this, 'register_columns' ) );
        add_action( 'pre_get_posts', array( $this, 'handle_orderby' ) );
    }

    /**
     * Post types that get the column: public types that support our editor box.
     */
    private function get_post_types() {
        $types = get_post_types( array( 'public' => true ), 'names' );
        unset( $types['attachment'] );
        return apply_filters( 'seo_fury_seo_column_post_types', array_values( $types ) );
    }

    public function register_columns() {
        foreach ( $this->get_post_types() as $type ) {
            add_filter( "manage_{$type}_posts_columns", array( $this, 'add_column' ) );
            add_action( "manage_{$type}_posts_custom_column", array( $this, 'render_column' ), 10, 2 );
            add_filter( "manage_edit-{$type}_sortable_columns", array( $this, 'add_sortable' ) );
        }
    }

    public function add_column( $columns ) {
        // Insert before the date column when present, otherwise append.
        $new = array();
        foreach ( $columns as $key => $label ) {
            if ( 'date' === $key ) {
                $new['seo_fury_score'] = __( 'SEO', 'seo-fury' );
            }
            $new[ $key ] = $label;
        }
        if ( ! isset( $new['seo_fury_score'] ) ) {
            $new['seo_fury_score'] = __( 'SEO', 'seo-fury' );
        }
        return $new;
    }

    public function add_sortable( $columns ) {
        $columns['seo_fury_score'] = 'seo_fury_score';
        return $columns;
    }

    public function render_column( $column, $post_id ) {
        if ( 'seo_fury_score' !== $column ) {
            return;
        }

        $raw = get_post_meta( $post_id, self::META_KEY, true );
        if ( $raw === '' ) {
            echo '<span style="color:var(--sf-gray-400, #a7aaad);" title="' . esc_attr__( 'Open the editor to calculate the SEO score', 'seo-fury' ) . '">&mdash;</span>';
            return;
        }

        $score = max( 0, min( 100, (int) $raw ) );
        if ( $score >= 80 ) {
            $color = '#46b450';
            $label = __( 'Good', 'seo-fury' );
        } elseif ( $score >= 50 ) {
            $color = '#dba617';
            $label = __( 'OK', 'seo-fury' );
        } else {
            $color = '#d63638';
            $label = __( 'Poor', 'seo-fury' );
        }

        printf(
            '<span title="%1$s" style="display:inline-flex;align-items:center;gap:6px;font-weight:600;">'
            . '<span style="width:10px;height:10px;border-radius:50%%;background:%2$s;display:inline-block;"></span>%3$d</span>',
            esc_attr( $label ),
            esc_attr( $color ),
            $score
        );
    }

    /**
     * Sort by the score meta when the SEO column header is clicked. Posts
     * without a score are treated as 0 so they sort to the bottom (ASC).
     */
    public function handle_orderby( $query ) {
        if ( ! is_admin() || ! $query->is_main_query() ) {
            return;
        }
        if ( 'seo_fury_score' !== $query->get( 'orderby' ) ) {
            return;
        }

        // Named-clause pattern (WP 4.2+): include posts that have no score via
        // the NOT EXISTS branch so they don't vanish from the list — they sort
        // to the end (NULL) when ordering by the scored clause.
        $order = strtoupper( (string) $query->get( 'order' ) ) === 'ASC' ? 'ASC' : 'DESC';
        $query->set( 'meta_query', array(
            'relation' => 'OR',
            'sf_score' => array( 'key' => self::META_KEY, 'type' => 'NUMERIC', 'compare' => 'EXISTS' ),
            array( 'key' => self::META_KEY, 'compare' => 'NOT EXISTS' ),
        ) );
        $query->set( 'orderby', array( 'sf_score' => $order ) );
    }
}
