<?php
/**
 * Ajoute deux colonnes dans le listing WP des post types où Falcify est
 * activé : « FALC publié » (statut visuel) et « Score FALC » (note 0-100
 * calculée en PHP à partir du contenu FALC stocké en meta).
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

class Falcify_List_Columns {
    public static function init() {
        // On s'enregistre tard pour laisser Falcify_Settings se charger et
        // pour que get_post_types() renvoie tous les CPT déclarés.
        add_action( 'admin_init', array( __CLASS__, 'register' ) );
        add_action( 'admin_head', array( __CLASS__, 'styles' ) );
    }

    public static function register() {
        $enabled = (array) Falcify_Settings::get_value( 'enabled_post_types' );
        if ( empty( $enabled ) ) return;
        foreach ( $enabled as $pt ) {
            $pt = sanitize_key( $pt );
            if ( $pt === '' ) continue;
            add_filter( "manage_{$pt}_posts_columns", array( __CLASS__, 'columns' ) );
            add_action( "manage_{$pt}_posts_custom_column", array( __CLASS__, 'render' ), 10, 2 );
        }
    }

    public static function columns( $cols ) {
        // Insère nos colonnes juste avant la date pour rester lisible.
        $new = array();
        foreach ( $cols as $key => $label ) {
            if ( $key === 'date' ) {
                $new['falcify_status'] = esc_html__( 'FALC publié', 'falcify-connector' );
                $new['falcify_score']  = esc_html__( 'Score FALC', 'falcify-connector' );
            }
            $new[ $key ] = $label;
        }
        if ( ! isset( $new['falcify_status'] ) ) {
            $new['falcify_status'] = esc_html__( 'FALC publié', 'falcify-connector' );
            $new['falcify_score']  = esc_html__( 'Score FALC', 'falcify-connector' );
        }
        return $new;
    }

    public static function render( $col, $post_id ) {
        if ( $col === 'falcify_status' ) {
            $status = (string) get_post_meta( $post_id, '_falcify_status', true );
            $has    = (string) get_post_meta( $post_id, '_falcify_content', true ) !== '';
            if ( $status === 'published' ) {
                echo '<span class="falcify-pill ok">' . esc_html__( 'Publié', 'falcify-connector' ) . '</span>';
            } elseif ( $status === 'validated' ) {
                echo '<span class="falcify-pill validated">' . esc_html__( 'Validé', 'falcify-connector' ) . '</span>';
            } elseif ( $status === 'draft' || $has ) {
                echo '<span class="falcify-pill draft">' . esc_html__( 'Brouillon', 'falcify-connector' ) . '</span>';
            } else {
                echo '<span class="falcify-pill none">' . esc_html__( '—', 'falcify-connector' ) . '</span>';
            }
            return;
        }
        if ( $col === 'falcify_score' ) {
            $falc = (string) get_post_meta( $post_id, '_falcify_content', true );
            if ( $falc === '' ) { echo '<span class="falcify-score none">—</span>'; return; }
            $score = self::compute_score( $falc );
            $cls   = $score >= 80 ? 'is-good' : ( $score >= 60 ? 'is-mid' : 'is-bad' );
            printf( '<span class="falcify-score %s">%d/100</span>', esc_attr( $cls ), (int) $score );
            return;
        }
    }

    /**
     * Heuristique simple alignée sur la lecture FALC :
     *  - moyenne mots/phrase (cible 8, plafond 20)
     *  - % de mots > 8 lettres (cible < 10 %)
     *  - bonus structure (titres + paragraphes courts).
     */
    public static function compute_score( $html ) {
        $text = trim( wp_strip_all_tags( (string) $html ) );
        if ( $text === '' ) return 0;
        $sentences = preg_split( '/(?<=[.!?])\s+/u', $text );
        $sentences = array_values( array_filter( array_map( 'trim', (array) $sentences ) ) );
        if ( empty( $sentences ) ) return 0;
        $word_counts = array_map( function( $s ) {
            return count( preg_split( '/\s+/u', $s, -1, PREG_SPLIT_NO_EMPTY ) );
        }, $sentences );
        $total = array_sum( $word_counts );
        $avg   = $total / max( 1, count( $sentences ) );
        $words = preg_split( '/\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY );
        $long  = 0;
        foreach ( $words as $w ) {
            if ( mb_strlen( preg_replace( '/[^\p{L}]/u', '', $w ) ) > 8 ) $long++;
        }
        $pct_long = $total > 0 ? ( $long / $total ) * 100 : 0;

        $score = 100;
        if ( $avg > 8 )  $score -= min( 40, ( $avg - 8 ) * 4 );
        if ( $pct_long > 10 ) $score -= min( 40, ( $pct_long - 10 ) * 1.5 );
        // Bonus structure
        if ( preg_match( '#<h[23]\b#i', (string) $html ) ) $score += 5;
        $score = max( 0, min( 100, (int) round( $score ) ) );
        return $score;
    }

    public static function styles() {
        $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
        if ( ! $screen || $screen->base !== 'edit' ) return;
        echo '<style>
            .column-falcify_status, .column-falcify_score { width: 110px; }
            .falcify-pill { display:inline-block; padding:2px 8px; border-radius:999px; font-size:12px; font-weight:600; line-height:1.6; }
            .falcify-pill.ok { background:#d1fae5; color:#065f46; }
            .falcify-pill.validated { background:#dbeafe; color:#1e40af; }
            .falcify-pill.draft { background:#fef3c7; color:#92400e; }
            .falcify-pill.none { background:#f3f4f6; color:#6b7280; }
            .falcify-score { font-weight:600; }
            .falcify-score.is-good { color:#059669; }
            .falcify-score.is-mid  { color:#d97706; }
            .falcify-score.is-bad  { color:#dc2626; }
            .falcify-score.none    { color:#9ca3af; font-weight:400; }
        </style>';
    }
}