<?php
/**
 * SEO helpers: short slug generation and meta output
 *
 * @package Trendly_AI_Post
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Determine if a major SEO plugin is active to avoid duplicate tags.
 */
function trendly_ai_post_has_seo_plugin() {
    return (
        class_exists( 'WPSEO_Frontend' ) || // Yoast
        class_exists( 'RankMath' ) || // Rank Math
        defined( 'AIOSEO_VERSION' ) || // All in One SEO
        class_exists( 'SEOPRESS' ) // SEOPress
    );
}

/**
 * Build a short, SEO-friendly slug from a title.
 * - strips common stopwords
 * - keeps up to 6 words and max 45 characters
 */
function trendly_ai_post_build_short_slug( $title ) {
    $title = wp_strip_all_tags( $title );
    $title = remove_accents( $title );

    // Lowercase and split to words
    $words = preg_split( '/[^a-zA-Z0-9]+/', strtolower( $title ), -1, PREG_SPLIT_NO_EMPTY );
    if ( empty( $words ) ) {
        return sanitize_title( $title );
    }

    // Basic English stopwords + newsy terms
    $stop = array( 'the','a','an','and','or','but','if','then','else','when','at','by','for','in','of','on','to','up','via','from','with','over','under','after','before','about','into','between','across','through','as','is','are','was','were','be','been','being','this','that','these','those','it','its','their','his','her','you','your','yours','we','our','ours','i','me','my','mine','they','them','he','she','will','just','can','could','should','would','may','might','must','have','has','had','do','does','did','not','no','yes','new','breaking','update' );

    $filtered = array();
    foreach ( $words as $w ) {
        if ( in_array( $w, $stop, true ) ) { continue; }
        $filtered[] = $w;
    }

    if ( empty( $filtered ) ) {
        $filtered = $words; // fallback
    }

    // Keep up to 6 words
    $filtered = array_slice( $filtered, 0, 6 );

    $slug = implode( '-', $filtered );

    // Enforce max length ~45 chars; trim at hyphen boundary when possible
    if ( strlen( $slug ) > 45 ) {
        $parts = explode( '-', $slug );
        $trimmed = '';
        foreach ( $parts as $p ) {
            $candidate = $trimmed === '' ? $p : $trimmed . '-' . $p;
            if ( strlen( $candidate ) > 45 ) { break; }
            $trimmed = $candidate;
        }
        if ( $trimmed !== '' ) {
            $slug = $trimmed;
        } else {
            $slug = substr( $slug, 0, 45 );
        }
    }

    return sanitize_title( $slug );
}

/**
 * Shorten auto-generated slugs on post insert/update.
 */
function trendly_ai_post_filter_insert_post_data( $data, $postarr ) {
    // Only for posts and pages; extend for CPTs if needed
    $ptype = isset( $data['post_type'] ) ? $data['post_type'] : ( isset( $postarr['post_type'] ) ? $postarr['post_type'] : 'post' );
    if ( ! in_array( $ptype, array( 'post', 'page' ), true ) ) {
        return $data;
    }

    // Skip if explicitly set slug and it's short
    $current_slug = isset( $data['post_name'] ) ? $data['post_name'] : '';
    $title        = isset( $data['post_title'] ) ? $data['post_title'] : ( isset( $postarr['post_title'] ) ? $postarr['post_title'] : '' );

    // Conditions to (re)build slug:
    // - no slug yet
    // - slug equals full sanitized title (likely auto)
    // - slug longer than 45 chars or more than 6 hyphenated tokens
    $auto_title_slug = sanitize_title( $title );
    $too_long        = ( strlen( $current_slug ) > 45 || ( substr_count( $current_slug, '-' ) + 1 ) > 6 );

    $should_update = ( $current_slug === '' || $current_slug === $auto_title_slug || $too_long );

    if ( $should_update && ! empty( $title ) ) {
        $short = trendly_ai_post_build_short_slug( $title );
        // Let core ensure uniqueness; we set a better base.
        $data['post_name'] = $short;
    }

    return $data;
}
add_filter( 'wp_insert_post_data', 'trendly_ai_post_filter_insert_post_data', 12, 2 );

/**
 * Generate a concise meta description from content/excerpt.
 */
function trendly_ai_post_meta_description( $post ) {
    if ( ! $post ) { return ''; }
    $text = $post->post_excerpt ? $post->post_excerpt : $post->post_content;
    $text = wp_strip_all_tags( $text );
    $text = preg_replace( '/\s+/', ' ', $text );
    $text = trim( $text );
    if ( strlen( $text ) > 160 ) {
        $text = substr( $text, 0, 157 ) . '...';
    }
    return esc_attr( $text );
}

// Intentionally not filtering the document title to avoid any duplication with themes/SEO plugins.

/**
 * Output meta tags (description, canonical, OG/Twitter) if no SEO plugin.
 */
function trendly_ai_post_wp_head_meta() {
    if ( trendly_ai_post_has_seo_plugin() ) {
        return; // avoid duplication
    }

    if ( is_singular() ) {
        global $post;
        if ( ! $post ) { return; }

        $permalink   = get_permalink( $post );
        $title       = wp_strip_all_tags( get_the_title( $post ) );
        $description = trendly_ai_post_meta_description( $post );

        // Meta description
        echo '<meta name="description" content="' . esc_attr( $description ) . '" />' . "\n";

        // Canonical
        echo '<link rel="canonical" href="' . esc_url( $permalink ) . '" />' . "\n";

        // Open Graph basic
        echo '<meta property="og:type" content="article" />' . "\n";
        echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n";
        echo '<meta property="og:description" content="' . esc_attr( $description ) . '" />' . "\n";
        echo '<meta property="og:url" content="' . esc_url( $permalink ) . '" />' . "\n";

        // Featured image if present
        if ( has_post_thumbnail( $post ) ) {
            $img = wp_get_attachment_image_src( get_post_thumbnail_id( $post ), 'full' );
            if ( $img && ! empty( $img[0] ) ) {
                echo '<meta property="og:image" content="' . esc_url( $img[0] ) . '" />' . "\n";
                echo '<meta name="twitter:card" content="summary_large_image" />' . "\n";
                echo '<meta name="twitter:image" content="' . esc_url( $img[0] ) . '" />' . "\n";
            }
        } else {
            echo '<meta name="twitter:card" content="summary" />' . "\n";
        }

        // Twitter title/description
        echo '<meta name="twitter:title" content="' . esc_attr( $title ) . '" />' . "\n";
        echo '<meta name="twitter:description" content="' . esc_attr( $description ) . '" />' . "\n";
    }
}
add_action( 'wp_head', 'trendly_ai_post_wp_head_meta', 1 );
