<?php
/**
 * LuxStrat International — Universal Deduplication Guard
 *
 * One class for ALL languages. The $lang parameter namespaces everything:
 *   Meta prefix:  _dba_luxstrat_{lang}_
 *   Transient:    dba_luxstrat_{lang}_used_{date}
 *
 * @package DamalionBlogAI
 * @subpackage LuxStratIntl
 */

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

class DBA_LuxStrat_Intl_Dedupe {

    /**
     * Get the meta prefix for a language.
     */
    public static function meta_prefix( $lang ) {
        return '_dba_luxstrat_' . sanitize_key( $lang ) . '_';
    }

    /**
     * Check if a theme already has a post this week (Mon→Sun).
     */
    public static function theme_posted_this_week( $lang, $theme_slug ) {
        if ( empty( $theme_slug ) ) return false;

        $prefix = self::meta_prefix( $lang );
        $tz     = self::get_timezone();
        $now    = new DateTime( 'now', $tz );

        $day_of_week = (int) $now->format( 'N' );
        $monday      = clone $now;
        $monday->modify( '-' . ( $day_of_week - 1 ) . ' days' );
        $week_start = $monday->format( 'Y-m-d' ) . ' 00:00:00';
        $week_end   = $now->format( 'Y-m-d' ) . ' 23:59:59';

        $existing = new WP_Query( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending', 'private' ),
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'date_query'     => array( array(
                'after'     => $week_start,
                'before'    => $week_end,
                'inclusive' => true,
            ) ),
            'meta_query'     => array(
                'relation' => 'AND',
                array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ),
                array( 'key' => $prefix . 'theme', 'value' => $theme_slug, 'compare' => '=' ),
            ),
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        return $existing->have_posts();
    }

    /**
     * Check if ANY LuxStrat post in this language was already published today.
     */
    public static function posted_today( $lang ) {
        $prefix = self::meta_prefix( $lang );
        $tz     = self::get_timezone();
        $now    = new DateTime( 'now', $tz );

        $existing = new WP_Query( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending', 'private' ),
            'posts_per_page' => 1,
            'fields'         => 'ids',
            'date_query'     => array( array(
                'after'     => $now->format( 'Y-m-d' ) . ' 00:00:00',
                'before'    => $now->format( 'Y-m-d' ) . ' 23:59:59',
                'inclusive' => true,
            ) ),
            'meta_query'     => array(
                array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ),
            ),
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        return $existing->have_posts();
    }

    /**
     * Check if a title is too similar to recent posts in this language (last 90 days).
     */
    public static function title_is_duplicate( $lang, $title ) {
        if ( empty( $title ) ) return false;

        $prefix     = self::meta_prefix( $lang );
        $normalised = mb_strtolower( trim( $title ) );

        $recent = new WP_Query( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending', 'private' ),
            'posts_per_page' => 100,
            'fields'         => 'ids',
            'date_query'     => array( array( 'after' => '90 days ago' ) ),
            'meta_query'     => array(
                array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ),
            ),
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        if ( ! $recent->have_posts() ) return false;

        foreach ( $recent->posts as $post_id ) {
            $existing_title = mb_strtolower( trim( get_the_title( $post_id ) ) );
            if ( $existing_title === $normalised ) return true;
            similar_text( $normalised, $existing_title, $percent );
            if ( $percent > 85 ) return true;
        }

        return false;
    }

    /**
     * Fast in-memory tracker — prevent double-runs on the same day.
     */
    public static function is_marked_today( $lang, $theme_slug ) {
        $key  = 'dba_luxstrat_' . $lang . '_used_' . date( 'Y-m-d' );
        $used = get_transient( $key );
        return is_array( $used ) && in_array( $theme_slug, $used, true );
    }

    /**
     * Mark a theme as used today.
     */
    public static function mark_used_today( $lang, $theme_slug ) {
        $key  = 'dba_luxstrat_' . $lang . '_used_' . date( 'Y-m-d' );
        $used = get_transient( $key );
        if ( ! is_array( $used ) ) $used = array();
        if ( ! in_array( $theme_slug, $used, true ) ) {
            $used[] = $theme_slug;
            set_transient( $key, $used, DAY_IN_SECONDS );
        }
    }

    private static function get_timezone() {
        try {
            return new DateTimeZone( 'Europe/Luxembourg' );
        } catch ( \Exception $e ) {
            return new DateTimeZone( 'UTC' );
        }
    }
}
