<?php
/**
 * DBA_EEurope_Registry
 *
 * Holds all 12 Eastern European country configurations, rotation-order logic,
 * and integrates with the existing GeoBot infrastructure.
 *
 * Rotation schedule: Sat/Sun, 07:00 CET, 1 post/day (configurable).
 *
 * @since 3.0.0
 */

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

class DBA_EEurope_Registry {

    /**
     * Fixed rotation order (priority sequence).
     * Poland leads (largest economy), followed by EU members by GDP,
     * then EU candidate (Serbia).
     */
    const ROTATION_ORDER = array(
        'poland',
        'czech_republic',
        'romania',
        'hungary',
        'slovakia',
        'croatia',
        'bulgaria',
        'lithuania',
        'slovenia',
        'latvia',
        'estonia',
        'serbia',
    );

    /**
     * EU membership status — used in prompts for factual grounding.
     *
     * @return array country_key => { eu_member, eu_year, currency, eurozone }
     */
    public static function get_eu_status() {
        return array(
            'poland'         => array( 'eu_member' => true,  'eu_year' => 2004, 'currency' => 'PLN',  'eurozone' => false ),
            'czech_republic' => array( 'eu_member' => true,  'eu_year' => 2004, 'currency' => 'CZK',  'eurozone' => false ),
            'serbia'         => array( 'eu_member' => false, 'eu_year' => null,  'currency' => 'RSD',  'eurozone' => false, 'eu_candidate' => true ),
            'croatia'        => array( 'eu_member' => true,  'eu_year' => 2013, 'currency' => 'EUR',  'eurozone' => true, 'eurozone_year' => 2023 ),
            'slovenia'       => array( 'eu_member' => true,  'eu_year' => 2004, 'currency' => 'EUR',  'eurozone' => true, 'eurozone_year' => 2007 ),
            'slovakia'       => array( 'eu_member' => true,  'eu_year' => 2004, 'currency' => 'EUR',  'eurozone' => true, 'eurozone_year' => 2009 ),
            'hungary'        => array( 'eu_member' => true,  'eu_year' => 2004, 'currency' => 'HUF',  'eurozone' => false ),
            'romania'        => array( 'eu_member' => true,  'eu_year' => 2007, 'currency' => 'RON',  'eurozone' => false ),
            'bulgaria'       => array( 'eu_member' => true,  'eu_year' => 2007, 'currency' => 'BGN',  'eurozone' => false ),
            'estonia'        => array( 'eu_member' => true,  'eu_year' => 2004, 'currency' => 'EUR',  'eurozone' => true, 'eurozone_year' => 2011 ),
            'latvia'         => array( 'eu_member' => true,  'eu_year' => 2004, 'currency' => 'EUR',  'eurozone' => true, 'eurozone_year' => 2014 ),
            'lithuania'      => array( 'eu_member' => true,  'eu_year' => 2004, 'currency' => 'EUR',  'eurozone' => true, 'eurozone_year' => 2015 ),
        );
    }

    /**
     * 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/';

        $countries = array();

        $labels = array(
            'poland'         => 'Poland',
            'czech_republic' => 'Czech Republic',
            'serbia'         => 'Serbia',
            'croatia'        => 'Croatia',
            'slovenia'       => 'Slovenia',
            'slovakia'       => 'Slovakia',
            'hungary'        => 'Hungary',
            'romania'        => 'Romania',
            'bulgaria'       => 'Bulgaria',
            'estonia'        => 'Estonia',
            'latvia'         => 'Latvia',
            'lithuania'      => 'Lithuania',
        );

        foreach ( $labels as $key => $label ) {
            $countries[ $key ] = array(
                'label'                 => $label,
                'country_key'           => $key,
                'meta_prefix'           => '_dba_geo_' . $key . '_',
                'wpml_code'             => 'en',
                'settings_option'       => 'dba_geo_' . $key . '_settings',
                'communes_option'       => 'dba_geo_' . $key . '_communes',
                'default_posting_days'  => array( 'thursday', 'friday' ),
                'default_posts_per_run' => 1,
                'timezone'              => 'Europe/Luxembourg',
                'word_count_min'        => 1000,
                'word_count_max'        => 1800,
                'cta_text'              => sprintf( $base_cta_text, $label ),
                'cta_link_text'         => $base_cta_link,
                'cta_link_url'          => $base_cta_url,
                'is_eeurope'            => true,
            );
        }

        return $countries;
    }

    /**
     * Get a single country config.
     *
     * @param  string $key Country key (e.g. 'poland').
     * @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_eeurope_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_eeurope_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_eeurope_rotation_state', array( 'index' => 0 ) );
        $index = intval( $state['index'] );

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

        return $enabled[ $index ];
    }

    /**
     * Get next scheduled EEurope run timestamp (site timezone).
     *
     * @return int Unix timestamp
     */
    public static function get_next_scheduled_run_ts() {
        if ( ! class_exists( 'DBA_EEurope_Scheduler' ) ) {
            return current_time( 'timestamp' );
        }

        $settings = get_option( 'dba_eeurope_settings', array() );
        $posting_days = ! empty( $settings['posting_days'] ) ? (array) $settings['posting_days'] : array( 'thursday', 'friday' );

        $candidates = array();
        foreach ( $posting_days as $day ) {
            $ts = wp_next_scheduled( DBA_EEurope_Scheduler::CRON_HOOK, array( $day ) );
            if ( $ts ) $candidates[] = (int) $ts;
        }
        // Also check no-args (Conflict Center reschedules without args)
        $ts_no_args = wp_next_scheduled( DBA_EEurope_Scheduler::CRON_HOOK );
        if ( $ts_no_args ) $candidates[] = (int) $ts_no_args;

        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
     * @param array $recent_countries
     * @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_eeurope_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 ) ) {
            if ( class_exists( 'DBA_EEurope_Scheduler' ) && method_exists( DBA_EEurope_Scheduler::get_instance(), 'get_recent_eeurope_usage_for_admin' ) ) {
                $ref_ts = $ref_ts ?: self::get_next_scheduled_run_ts();
                $recent = DBA_EEurope_Scheduler::get_instance()->get_recent_eeurope_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;
        }

        return $enabled[ $start ];
    }

    /**
     * Reset rotation to the beginning (Poland).
     */
    public static function reset_rotation() {
        update_option( 'dba_eeurope_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_eeurope_rotation_state', array(
            'index'        => 0,
            'last_run'     => '',
            'last_country' => '',
        ) );
    }

    /**
     * Register all EEurope countries into the GeoBot registry.
     * Called on plugins_loaded.
     */
    public static function register_in_geobot() {
        if ( ! class_exists( 'DBA_GeoBot_Registry' ) ) {
            return;
        }
        if ( ! method_exists( 'DBA_GeoBot_Registry', 'register_country' ) ) {
            return;
        }
        foreach ( self::get_countries() as $key => $config ) {
            DBA_GeoBot_Registry::register_country( $key, $config );
        }
    }
}
