<?php

namespace WPSN\Core;

use WPSN\Admin\SettingsRepository;

defined('ABSPATH') || exit;

final class Lifecycle
{
    /**
     * Central registry of WP-Cron hooks owned by the plugin.
     *
     * Keep this list in sync with new scheduled features so deactivate()
     * leaves no orphaned events behind in the cron option.
     *
     * @var string[]
     */
    private const CRON_HOOKS = [
        'wpsn_activity_log_purge',
        'wpsn_ai_botblock_stats_purge',
        'wpsn_audit_tick',
        'wpsn_billing_center_sync',
        'wpsn_drift_daily',
        'wpsn_gsc_daily_fetch',
        'wpsn_gsc_daily_rank',
        'wpsn_gsc_weekly_digest',
        'wpsn_license_verify',
        'wpsn_notifications_digest_tick',
        'wpsn_platform_ops_tick',
        'wpsn_privacy_purge_external_log',
        'wpsn_quality_gate_tick',
        'wpsn_queue_tick',
        'wpsn_redirects_cleanup_404',
        'wpsn_saas_dashboard_tick',
        'wpsn_saas_sync_tick',
        'wpsn_site_crawl_tick',
    ];

    public static function activate(): void
    {
        // Basic versioning + defaults.
        if (!get_option('wpsn_version')) {
            add_option('wpsn_version', WPSN_VERSION);
        } else {
            update_option('wpsn_version', WPSN_VERSION);
        }

        // Use repository defaults so activation stays in sync with SettingsRepository::defaults().
        if (!get_option(SettingsRepository::OPTION_NAME)) {
            $repo = new SettingsRepository();
            add_option(SettingsRepository::OPTION_NAME, $repo->defaults());
        }

        // Capabilities/roles.
        Capabilities::install();

        // Stage 6: register sitemap rewrite rules and flush so endpoints work immediately.
        add_rewrite_rule('^sitemap\.xml$', 'index.php?wpsn_sitemap=index', 'top');
        add_rewrite_rule('^sitemap_index\.xml$', 'index.php?wpsn_sitemap=index', 'top');
        add_rewrite_rule('^([a-z0-9_-]+)-sitemap\.xml$', 'index.php?wpsn_sitemap=$matches[1]&wpsn_sitemap_page=1', 'top');
        add_rewrite_rule('^([a-z0-9_-]+)-sitemap([0-9]+)\.xml$', 'index.php?wpsn_sitemap=$matches[1]&wpsn_sitemap_page=$matches[2]', 'top');

        // AI Search Readiness: /llms.txt
        add_rewrite_rule('^llms\.txt$', 'index.php?wpsn_llms_txt=1', 'top');

        // WooCommerce Merchant feed: /merchant-feed.xml
        add_rewrite_rule('^merchant-feed\.xml$', 'index.php?wpsn_merchant_feed=1', 'top');

        // Local SEO: /locations.kml
        add_rewrite_rule('^locations\.kml$', 'index.php?wpsn_locations_kml=1', 'top');

        flush_rewrite_rules(false);
    }

    public static function deactivate(): void
    {
        if (function_exists('wp_clear_scheduled_hook')) {
            foreach (self::CRON_HOOKS as $hook) {
                wp_clear_scheduled_hook($hook);
            }
        }

        // Remove our rewrite rules.
        flush_rewrite_rules(false);
    }
}
