<?php
/**
 * Core plugin orchestrator.
 *
 * @package PrimeLink
 */

namespace PrimeLink\Core;

use PrimeLink\Core\Admin\Admin;
use PrimeLink\Core\Rest\ImportRest;
use PrimeLink\Core\Rest\ExportRest;
use PrimeLink\Core\Rest\LiveFeedRest;
use PrimeLink\Core\Updater;

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

final class Plugin {

    /**
     * Boot plugin components.
     *
     * @return void
     */
    public static function init() {
        // Register REST routes globally (front + admin).
        // Register immediately to ensure routes are available
        ImportRest::register();
        ExportRest::register();
        LiveFeedRest::register();
        
        // Force register routes if rest_api_init already fired (for early requests)
        if ( did_action( 'rest_api_init' ) ) {
            ImportRest::routes();
            ExportRest::routes();
            if ( method_exists( 'PrimeLink\Core\Rest\LiveFeedRest', 'register_routes' ) ) {
                LiveFeedRest::register_routes();
            }
        }
        
        // Flush rewrite rules once on first load to ensure REST API routes are recognized
        // This is a one-time operation that sets a flag to prevent repeated flushes
        // Also flush if plugin version changed (new routes might have been added)
        $flushed_version = get_option( 'mt_primelink_rewrite_rules_flushed_version', '' );
        if ( ! get_option( 'mt_primelink_rewrite_rules_flushed', false ) || $flushed_version !== MT_PRIMELINK_VERSION ) {
            flush_rewrite_rules( false );
            update_option( 'mt_primelink_rewrite_rules_flushed', true, false );
            update_option( 'mt_primelink_rewrite_rules_flushed_version', MT_PRIMELINK_VERSION, false );
        }

        // Admin-only components.
        Admin::init();

        // Register Live Feed cron intervals and hooks
        add_action( 'init', array( 'PrimeLink\Modules\LiveFeed\LiveFeedSyncService', 'register_cron_intervals' ) );
        add_action( 'mt_primelink_live_feed_sync', array( 'PrimeLink\Modules\LiveFeed\LiveFeedSyncService', 'sync_feed' ) );

        // Initialize license verification system
        Updater::init();

        do_action( 'mt_primelink_loaded' );
    }
}