<?php
/**
 * DBA_LATAM_Registry
 *
 * Holds all 15 Latin America country configurations, city data,
 * and rotation-order logic. This module registers LATAM countries
 * into the existing GeoBot infrastructure but manages its own
 * rotation scheduler (Sat/Sun, 07:00 CET, 1 post/day).
 *
 * @since 2.11.0
 */

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

class DBA_LATAM_Registry {

    /**
     * Fixed rotation order (priority sequence).
     * Brazil leads, followed by largest economies, then the rest alphabetically.
     */
    const ROTATION_ORDER = array(
        'brazil',
        'mexico',
        'argentina',
        'chile',
        'peru',
        'colombia',
        'ecuador',
        'guatemala',
        'honduras',
        'el_salvador',
        'nicaragua',
        'costa_rica',
        'bolivia',
        'paraguay',
        'uruguay',
    );

    /**
     * Full country configurations.
     *
     * Each entry mirrors the GeoBot registry schema so it can be
     * injected into DBA_GeoBot_Registry::get_countries() seamlessly.
     *
     * @return array
     */
    public static function get_countries() {
        $base_cta_text     = 'Damalion supports international investors, entrepreneurs, and family offices establishing and structuring their business in %s.';
        $base_cta_link     = 'Contact your Damalion experts now.';
        $base_cta_url      = 'https://www.damalion.com/lets-connect/';

        return array(

            // ── TIER 1: Priority markets ────────────────────────────

            'brazil' => array(
                'label'               => 'Brazil',
                'country_key'         => 'brazil',
                'meta_prefix'         => '_dba_geo_brazil_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_brazil_settings',
                'communes_option'     => 'dba_geo_brazil_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Brazil' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'mexico' => array(
                'label'               => 'Mexico',
                'country_key'         => 'mexico',
                'meta_prefix'         => '_dba_geo_mexico_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_mexico_settings',
                'communes_option'     => 'dba_geo_mexico_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Mexico' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'argentina' => array(
                'label'               => 'Argentina',
                'country_key'         => 'argentina',
                'meta_prefix'         => '_dba_geo_argentina_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_argentina_settings',
                'communes_option'     => 'dba_geo_argentina_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Argentina' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'chile' => array(
                'label'               => 'Chile',
                'country_key'         => 'chile',
                'meta_prefix'         => '_dba_geo_chile_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_chile_settings',
                'communes_option'     => 'dba_geo_chile_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Chile' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'peru' => array(
                'label'               => 'Peru',
                'country_key'         => 'peru',
                'meta_prefix'         => '_dba_geo_peru_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_peru_settings',
                'communes_option'     => 'dba_geo_peru_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Peru' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            // ── TIER 2 ─────────────────────────────────────────────

            'colombia' => array(
                'label'               => 'Colombia',
                'country_key'         => 'colombia',
                'meta_prefix'         => '_dba_geo_colombia_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_colombia_settings',
                'communes_option'     => 'dba_geo_colombia_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Colombia' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'ecuador' => array(
                'label'               => 'Ecuador',
                'country_key'         => 'ecuador',
                'meta_prefix'         => '_dba_geo_ecuador_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_ecuador_settings',
                'communes_option'     => 'dba_geo_ecuador_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Ecuador' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'guatemala' => array(
                'label'               => 'Guatemala',
                'country_key'         => 'guatemala',
                'meta_prefix'         => '_dba_geo_guatemala_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_guatemala_settings',
                'communes_option'     => 'dba_geo_guatemala_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Guatemala' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'honduras' => array(
                'label'               => 'Honduras',
                'country_key'         => 'honduras',
                'meta_prefix'         => '_dba_geo_honduras_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_honduras_settings',
                'communes_option'     => 'dba_geo_honduras_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Honduras' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'el_salvador' => array(
                'label'               => 'El Salvador',
                'country_key'         => 'el_salvador',
                'meta_prefix'         => '_dba_geo_el_salvador_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_el_salvador_settings',
                'communes_option'     => 'dba_geo_el_salvador_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'El Salvador' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'nicaragua' => array(
                'label'               => 'Nicaragua',
                'country_key'         => 'nicaragua',
                'meta_prefix'         => '_dba_geo_nicaragua_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_nicaragua_settings',
                'communes_option'     => 'dba_geo_nicaragua_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Nicaragua' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'costa_rica' => array(
                'label'               => 'Costa Rica',
                'country_key'         => 'costa_rica',
                'meta_prefix'         => '_dba_geo_costa_rica_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_costa_rica_settings',
                'communes_option'     => 'dba_geo_costa_rica_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Costa Rica' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            // ── TIER 3 ─────────────────────────────────────────────

            'bolivia' => array(
                'label'               => 'Bolivia',
                'country_key'         => 'bolivia',
                'meta_prefix'         => '_dba_geo_bolivia_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_bolivia_settings',
                'communes_option'     => 'dba_geo_bolivia_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Bolivia' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'paraguay' => array(
                'label'               => 'Paraguay',
                'country_key'         => 'paraguay',
                'meta_prefix'         => '_dba_geo_paraguay_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_paraguay_settings',
                'communes_option'     => 'dba_geo_paraguay_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Paraguay' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),

            'uruguay' => array(
                'label'               => 'Uruguay',
                'country_key'         => 'uruguay',
                'meta_prefix'         => '_dba_geo_uruguay_',
                'wpml_code'           => 'en',
                'settings_option'     => 'dba_geo_uruguay_settings',
                'communes_option'     => 'dba_geo_uruguay_communes',
                'default_posting_days'=> array( 'saturday', 'sunday' ),
                'default_posts_per_run' => 1,
                'timezone'            => 'Europe/Luxembourg',
                'word_count_min'      => 500,
                'word_count_max'      => 800,
                'cta_text'            => sprintf( $base_cta_text, 'Uruguay' ),
                'cta_link_text'       => $base_cta_link,
                'cta_link_url'        => $base_cta_url,
                'is_latam'            => true,
            ),
        );
    }

    /**
     * Get a single country config.
     *
     * @param  string $key Country key (e.g. 'brazil').
     * @return array|null
     */
    public static function get_country( $key ) {
        $countries = self::get_countries();
        return isset( $countries[ $key ] ) ? $countries[ $key ] : null;
    }

    /**
     * Get the rotation order as an indexed array.
     *
     * @return array
     */
    public static function get_rotation_order() {
        return self::ROTATION_ORDER;
    }

    /**
     * Get only the countries that are enabled in settings.
     *
     * @return array  Array of country keys in rotation order.
     */
    public static function get_enabled_countries() {
        $enabled = array();
        foreach ( self::ROTATION_ORDER as $key ) {
            $config   = self::get_country( $key );
            if ( ! $config ) continue;
            $settings = get_option( $config['settings_option'], array() );
            if ( ! empty( $settings['enabled'] ) ) {
                $enabled[] = $key;
            }
        }
        return $enabled;
    }

    /**
     * Get the next country in rotation.
     *
     * Reads the current rotation index from wp_options, advances it,
     * and returns the country key. Wraps around at the end.
     *
     * @return string|false  Country key or false if none enabled.
     */
    public static function get_next_country() {
        $enabled = self::get_enabled_countries();
        if ( empty( $enabled ) ) {
            return false;
        }

        $state = get_option( 'dba_latam_rotation_state', array(
            'index' => 0,
            'last_run' => '',
        ) );

        $index = intval( $state['index'] );

        // Wrap around
        if ( $index >= count( $enabled ) ) {
            $index = 0;
        }

        $country_key = $enabled[ $index ];

        // Advance index for next run
        $state['index']    = $index + 1;
        $state['last_run'] = current_time( 'mysql' );
        $state['last_country'] = $country_key;
        update_option( 'dba_latam_rotation_state', $state, false );

        return $country_key;
    }

    /**
     * Peek at what country is next without advancing.
     *
     * @return string|false
     */
    public static function peek_next_country() {
        $enabled = self::get_enabled_countries();
        if ( empty( $enabled ) ) {
            return false;
        }

        $state = get_option( 'dba_latam_rotation_state', array( 'index' => 0 ) );
        $index = intval( $state['index'] );

        if ( $index >= count( $enabled ) ) {
            $index = 0;
        }

        return $enabled[ $index ];
    }

    /**
     * Get next scheduled LATAM run timestamp (site timezone).
     * Uses the earliest of the next Saturday/Sunday events.
     *
     * @return int Unix timestamp
     */
    public static function get_next_scheduled_run_ts() {
        if ( ! class_exists( 'DBA_LATAM_Scheduler' ) ) {
            return current_time( 'timestamp' );
        }

        $sat = wp_next_scheduled( DBA_LATAM_Scheduler::CRON_HOOK, array( 'saturday' ) );
        $sun = wp_next_scheduled( DBA_LATAM_Scheduler::CRON_HOOK, array( 'sunday' ) );

        $candidates = array();
        if ( $sat ) $candidates[] = (int) $sat;
        if ( $sun ) $candidates[] = (int) $sun;

        if ( empty( $candidates ) ) {
            return current_time( 'timestamp' );
        }
        sort( $candidates );
        return (int) $candidates[0];
    }

    /**
     * Peek next eligible country (cooldown-aware) without advancing rotation.
     *
     * @param int $cooldown_days
     * @param int|null $ref_ts Timestamp for the upcoming run (defaults to next scheduled run).
     * @param array $recent_countries Optional map country_key=>true, precomputed.
     * @return string|false
     */
    public static function peek_next_eligible_country( $cooldown_days = 0, $ref_ts = null, $recent_countries = array() ) {
        $enabled = self::get_enabled_countries();
        if ( empty( $enabled ) ) return false;

        $state = get_option( 'dba_latam_rotation_state', array( 'index' => 0 ) );
        $start = intval( $state['index'] );
        if ( $start >= count( $enabled ) ) $start = 0;

        $cooldown_days = absint( $cooldown_days );
        if ( $cooldown_days > 0 && empty( $recent_countries ) ) {
            // Use scheduler helper if present, else fallback to lightweight query.
            if ( class_exists( 'DBA_LATAM_Scheduler' ) && method_exists( DBA_LATAM_Scheduler::get_instance(), 'get_recent_latam_usage_for_admin' ) ) {
                $ref_ts = $ref_ts ?: self::get_next_scheduled_run_ts();
                $recent = DBA_LATAM_Scheduler::get_instance()->get_recent_latam_usage_for_admin( $cooldown_days, $ref_ts );
                $recent_countries = $recent['countries'] ?? array();
            }
        }

        for ( $i = 0; $i < count( $enabled ); $i++ ) {
            $idx = ( $start + $i ) % count( $enabled );
            $key = $enabled[ $idx ];
            if ( $cooldown_days > 0 && ! empty( $recent_countries ) && isset( $recent_countries[ $key ] ) ) {
                continue;
            }
            return $key;
        }

        // If everything is blocked, show the raw next country.
        return $enabled[ $start ];
    }


    /**
     * Reset rotation to the beginning (Brazil).
     */
    public static function reset_rotation() {
        update_option( 'dba_latam_rotation_state', array(
            'index'    => 0,
            'last_run' => '',
        ), false );
    }

    /**
     * Get rotation state for admin display.
     *
     * @return array
     */
    public static function get_rotation_state() {
        return get_option( 'dba_latam_rotation_state', array(
            'index'        => 0,
            'last_run'     => '',
            'last_country' => '',
        ) );
    }

    /**
     * Register all LATAM countries into the GeoBot registry.
     *
     * This hooks into the GeoBot registry so that:
     * - [damalion_geo_blog country="brazil"] works
     * - GeoBot admin shows LATAM countries
     * - GeoBot generator can handle LATAM requests
     *
     * Called on plugins_loaded.
     */
    public static function register_in_geobot() {
        if ( ! class_exists( 'DBA_GeoBot_Registry' ) ) {
            return;
        }

        // Only register if the GeoBot registry supports dynamic registration
        if ( ! method_exists( 'DBA_GeoBot_Registry', 'register_country' ) ) {
            return;
        }

        foreach ( self::get_countries() as $key => $config ) {
            DBA_GeoBot_Registry::register_country( $key, $config );
        }
    }
}
