<?php
/**
 * DBA_EEurope_Dedupe
 *
 * Deduplication guard: prevents duplicate titles, same-day double-posts,
 * and same-theme-per-week repeats across EEurope countries.
 *
 * All state is namespaced to 'eeurope' to avoid collisions with LATAM/LuxStrat.
 *
 * @since 3.0.0
 */

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

class DBA_EEurope_Dedupe {

    /**
     * Meta prefix for all EEurope post meta.
     */
    public static function meta_prefix() {
        return '_dba_eeurope_';
    }

    /**
     * Check if ANY EEurope post was already published today.
     *
     * @return bool
     */
    public static function posted_today() {
        $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' => '_dba_eeurope_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 (last 90 days).
     *
     * Uses both exact match and similarity scoring (>85% = duplicate).
     *
     * @param string $title
     * @return bool
     */
    public static function title_is_duplicate( $title ) {
        if ( empty( $title ) ) return false;

        $normalised = mb_strtolower( trim( $title ) );

        $recent = new WP_Query( array(
            'post_type'      => 'post',
            'post_status'    => array( 'publish', 'draft', 'pending', 'private' ),
            'posts_per_page' => 150,
            'fields'         => 'ids',
            'date_query'     => array( array( 'after' => '90 days ago' ) ),
            'meta_query'     => array(
                array( 'key' => '_dba_eeurope_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;
    }

    /**
     * Check if a theme was already used for a specific country this week.
     *
     * @param string $country_key
     * @param string $theme_key
     * @return bool
     */
    public static function theme_used_this_week( $country_key, $theme_key ) {
        if ( empty( $theme_key ) ) return false;

        $tz  = self::get_timezone();
        $now = new DateTime( 'now', $tz );
        $dow = (int) $now->format( 'N' );
        $monday = clone $now;
        $monday->modify( '-' . ( $dow - 1 ) . ' days' );

        $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'     => $monday->format( 'Y-m-d' ) . ' 00:00:00',
                'before'    => $now->format( 'Y-m-d' ) . ' 23:59:59',
                'inclusive' => true,
            ) ),
            'meta_query'     => array(
                'relation' => 'AND',
                array( 'key' => '_dba_eeurope_auto_created', 'compare' => 'EXISTS' ),
                array( 'key' => '_dba_eeurope_country', 'value' => $country_key ),
                array( 'key' => '_dba_eeurope_theme', 'value' => $theme_key ),
            ),
            'no_found_rows'          => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ) );

        return $existing->have_posts();
    }

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

    /**
     * Mark a country as generated today.
     */
    public static function mark_used_today( $country_key ) {
        $key  = 'dba_eeurope_used_' . date( 'Y-m-d' );
        $used = get_transient( $key );
        if ( ! is_array( $used ) ) $used = array();
        if ( ! in_array( $country_key, $used, true ) ) {
            $used[] = $country_key;
            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' );
        }
    }
}
