<?php

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

class AIEO_MOI_Poller {

    const HOOK = 'aieo_moi_poll_vendors';

    public static function init() {
        add_filter('cron_schedules', array(__CLASS__, 'add_schedule'));
        add_action(self::HOOK,        array(__CLASS__, 'tick'));
        
        
        
        
        
        add_action('admin_init', array(__CLASS__, 'maybe_schedule'));
    }

    
    public static function maybe_schedule() {
        $scheduled = wp_next_scheduled(self::HOOK);
        if (self::has_enabled_vendors()) {
            if (!$scheduled) {
                wp_schedule_event(time() + 60, 'aieo_moi_5min', self::HOOK);
            }
        } elseif ($scheduled) {
            wp_unschedule_event($scheduled, self::HOOK);
        }
    }

    
    private static function has_enabled_vendors() {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['vendors'];
        
        return (int) $wpdb->get_var("SELECT 1 FROM {$tbl} WHERE enabled = 1 LIMIT 1") === 1;
    }

    public static function add_schedule($s) {
        if (!isset($s['aieo_moi_5min'])) {
            $s['aieo_moi_5min'] = array(
                'interval' => 5 * MINUTE_IN_SECONDS,
                'display'  => __('Every 5 minutes (Marketplace Order Importer)', 'ai-eshop-optimizer'),
            );
        }
        return $s;
    }

    
    public static function tick() {
        foreach (AIEO_MOI_Vendor_Manager::list_all() as $vendor) {
            if (empty($vendor['enabled'])) { continue; }
            $provider = AIEO_MOI_Provider_Registry::get((string) $vendor['provider']);
            if (!$provider) { continue; }
            
            
            
            if (method_exists($provider, 'is_polling') && ! $provider->is_polling()) { continue; }

            $state    = isset($vendor['credentials']['poller_state']) && is_array($vendor['credentials']['poller_state'])
                ? $vendor['credentials']['poller_state'] : array();
            $since_ts = isset($state['last_polled_at']) ? (int) $state['last_polled_at'] : (time() - DAY_IN_SECONDS);

            try {
                $orders = $provider->poll_orders($vendor, $since_ts);
            } catch (\Throwable $e) {
                AIEO_MOI_Inbound_Log::record(array(
                    'vendor_id'  => (int) $vendor['id'],
                    'event_type' => 'poll',
                    'status'     => 'failed',
                    'error_text' => $e->getMessage(),
                ));
                continue;
            }
            if (!is_array($orders)) { $orders = array(); }

            $processed = 0;
            foreach ($orders as $canonical) {
                if (!is_array($canonical) || empty($canonical['remote_order_id'])) { continue; }
                $result = AIEO_MOI_Order_Mapper::upsert_from_canonical($vendor, $canonical, 'poll');
                AIEO_MOI_Inbound_Log::record(array(
                    'vendor_id'       => (int) $vendor['id'],
                    'event_type'      => 'poll_' . (isset($canonical['event_type']) ? (string) $canonical['event_type'] : 'order'),
                    'remote_order_id' => (string) $canonical['remote_order_id'],
                    'status'          => isset($result['error']) ? 'failed' : 'processed',
                    'error_text'      => isset($result['error']) && is_wp_error($result['error']) ? $result['error']->get_error_message() : null,
                    'wc_order_id'     => isset($result['wc_order_id']) ? (int) $result['wc_order_id'] : null,
                ));
                $processed++;
            }

            
            $creds = AIEO_MOI_Vendor_Manager::credentials($vendor);
            $creds['poller_state'] = array(
                'last_polled_at' => time(),
                'processed'      => $processed,
            );
            AIEO_MOI_Vendor_Manager::save(array(
                'id'                   => (int) $vendor['id'],
                'slug'                 => $vendor['slug'],
                'provider'             => $vendor['provider'],
                'label'                => $vendor['label'],
                'credentials'          => $creds,
                'default_order_status' => $vendor['default_order_status'],
                'sku_strategy'         => $vendor['sku_strategy'],
                'sku_meta_key'         => $vendor['sku_meta_key'],
                'enabled'              => $vendor['enabled'],
            ));
        }
    }
}

AIEO_MOI_Poller::init();
