<?php

declare(strict_types=1);

namespace Instinctor\Core;


if (!defined('ABSPATH')) exit;
use Instinctor\Core\Config;
use Instinctor\Core\Migration;

/**
 * Handles plugin activation
 */
class Activator
{
    public static function activate(): void
    {
        // Run all pending schema migrations (idempotent — safe on re-activation)
        Migration::run();

        self::setDefaultOptions();
        self::scheduleCronJobs();

        // Register roles and capabilities
        \Instinctor\Core\RoleManager::install();

        // NOTE: we deliberately do NOT change the site's permalink_structure here.
        // Silently overwriting a global WordPress setting on activation is disallowed;
        // an opt-in admin notice (instinctor.php) recommends pretty permalinks instead.
        // Flush rewrite rules so the plugin's own routes register.
        flush_rewrite_rules();
    }

    private static function scheduleCronJobs(): void
    {
        // Low stock notifications - runs daily
        if (!wp_next_scheduled('instinctor_check_low_stock')) {
            wp_schedule_event(time(), 'daily', 'instinctor_check_low_stock');
        }

        // v1.3.0 Cron jobs
        \Instinctor\Services\CronService::schedule();
    }

    private static function setDefaultOptions(): void
    {
        $defaults = [
            'instinctor_store_type'             => 'mixed',
            'instinctor_currency'               => 'USD',
            'instinctor_currency_position'      => 'left',
            'instinctor_thousand_separator'     => ',',
            'instinctor_decimal_separator'      => '.',
            'instinctor_decimals'               => 2,
            'instinctor_tax_enabled'            => false,
            'instinctor_prices_include_tax'     => false,
            'instinctor_multi_currency_enabled' => false,
            'instinctor_auto_detect_currency'   => false,
            'instinctor_exchange_rate_api'      => '',
        ];

        foreach ($defaults as $key => $value) {
            if (get_option($key) === false) {
                add_option($key, $value);
            }
        }

        // Track first install date (never overwrite)
        if (Config::get('instinctor_installed_at') === false) {
            add_option('instinctor_installed_at', current_time('timestamp'));
        }

        // Flag that we need to prompt for free registration (if not already registered)
        if (!Config::get('instinctor_registered')) {
            Config::set('instinctor_show_registration_prompt', true);
        }
    }
}
