<?php
if (!defined('ABSPATH')) {
    exit;
}

class VMO_Plan_Policy {
    public static function get_default_affiliate_rate() {
        return defined('VMO_DEFAULT_AFFILIATE_COMMISSION') ? (float) VMO_DEFAULT_AFFILIATE_COMMISSION : 5.0;
    }

    public static function get_overhead_rate() {
        return defined('VMO_OPERATING_OVERHEAD_RATE') ? (float) VMO_OPERATING_OVERHEAD_RATE : 0.40;
    }

    public static function get_min_net_profit_rate() {
        return defined('VMO_MIN_NET_PROFIT_RATE') ? (float) VMO_MIN_NET_PROFIT_RATE : 0.25;
    }

    public static function get_provider_cost_budget_rate() {
        return defined('VMO_PROVIDER_COST_BUDGET_RATE') ? (float) VMO_PROVIDER_COST_BUDGET_RATE : 0.30;
    }

    public static function normalize_plan($plan) {
        $plan = strtolower(trim((string) $plan));

        $aliases = [
            'tester' => 'tester',
            'tester_pack' => 'tester',
            'starter' => 'starter',
            'starter_pack' => 'starter',
            'pro' => 'pro',
            'pro_pack' => 'pro',
            'professional' => 'pro',
            'premium' => 'pro',
            'elite' => 'elite',
            'business' => 'elite',
            'business_pack' => 'elite',
            'enterprise' => 'enterprise',
            'enterprise_pack' => 'enterprise',
            'free' => 'free',
            '' => 'free',
        ];

        return $aliases[$plan] ?? 'free';
    }

    public static function is_paid_plan($plan) {
        return in_array(self::normalize_plan($plan), ['tester', 'starter', 'pro', 'elite', 'enterprise'], true);
    }

    public static function plan_has_priority_compute($plan) {
        return self::normalize_plan($plan) === 'enterprise';
    }

    public static function get_plan($plan) {
        $plans = self::get_all();
        $normalized_plan = self::normalize_plan($plan);

        return $plans[$normalized_plan] ?? $plans['free'];
    }

    public static function get_all() {
        return [
            'free' => self::build_plan([
                'name' => 'Free',
                'price' => 0,
                'recurring_tokens' => 0,
                'signup_bonus_tokens' => 0,
                'background_ops_enabled' => false,
                'background_ops_frequency' => 'none',
                'cron_interval' => null,
                'monthly_ops' => 0,
            ]),
            'tester' => self::build_plan([
                'name' => 'Tester',
                'price' => 49.99,
                'recurring_tokens' => self::resolve_token_constant('VMO_TOKENS_TESTER_PACKAGE', 36034),
                'signup_bonus_tokens' => 185000,
                'background_ops_enabled' => false,
                'background_ops_frequency' => 'none',
                'cron_interval' => null,
                'monthly_ops' => 0,
            ]),
            'starter' => self::build_plan([
                'name' => 'Starter',
                'price' => 99.99,
                'recurring_tokens' => self::resolve_token_constant('VMO_TOKENS_STARTER_PLAN', 72326),
                'signup_bonus_tokens' => 165000,
                'background_ops_enabled' => true,
                'background_ops_frequency' => 'monthly',
                'cron_interval' => 'monthly',
                'monthly_ops' => 1,
            ]),
            'pro' => self::build_plan([
                'name' => 'Pro',
                'price' => 199.99,
                'recurring_tokens' => self::resolve_token_constant('VMO_TOKENS_PRO_PLAN', 144909),
                'signup_bonus_tokens' => 175000,
                'background_ops_enabled' => true,
                'background_ops_frequency' => 'twice monthly',
                'cron_interval' => 'twicemonthly',
                'monthly_ops' => 2,
            ]),
            'elite' => self::build_plan([
                'name' => 'Elite',
                'price' => 499.99,
                'recurring_tokens' => self::resolve_token_constant('VMO_TOKENS_ELITE_PLAN', 362659),
                'signup_bonus_tokens' => 60000,
                'background_ops_enabled' => true,
                'background_ops_frequency' => 'weekly',
                'cron_interval' => 'weekly',
                'monthly_ops' => 4,
            ]),
            'enterprise' => self::build_plan([
                'name' => 'Enterprise',
                'price' => 999.99,
                'recurring_tokens' => self::resolve_token_constant('VMO_TOKENS_ENTERPRISE_PLAN', 500000),
                'signup_bonus_tokens' => 80000,
                'background_ops_enabled' => true,
                'background_ops_frequency' => 'weekly',
                'cron_interval' => 'weekly',
                'monthly_ops' => 4,
                'priority_compute' => true,
            ]),
        ];
    }

    public static function get_checkout_token_grant($plan, $fallback_tokens = 0) {
        $plan_policy = self::get_plan($plan);
        if (!empty($plan_policy['recurring_tokens'])) {
            return (int) $plan_policy['recurring_tokens'];
        }

        return (int) $fallback_tokens;
    }

    public static function get_background_ops_config($plan) {
        $plan_policy = self::get_plan($plan);
        $normalized_plan = self::normalize_plan($plan);

        $reason = null;
        if (!$plan_policy['background_ops_enabled']) {
            if ($normalized_plan === 'tester') {
                $reason = 'The Tester Plan includes the same high-quality onboarding, but no automated background operations. Upgrade to Starter for monthly scans.';
            } else {
                $reason = 'Background operations are not available on free accounts. Subscribe to unlock automated business intelligence.';
            }
        }

        return [
            'enabled' => (bool) $plan_policy['background_ops_enabled'],
            'frequency' => $plan_policy['background_ops_frequency'],
            'cron_interval' => $plan_policy['cron_interval'],
            'reason' => $reason,
            'monthly_ops' => (int) $plan_policy['monthly_ops'],
            'plan' => $normalized_plan,
        ];
    }

    public static function queue_signup_bonus($user_id, $plan) {
        $user_id = (int) $user_id;
        if ($user_id <= 0) {
            return false;
        }

        $plan_policy = self::get_plan($plan);
        $bonus_tokens = (int) ($plan_policy['signup_bonus_tokens'] ?? 0);
        if ($bonus_tokens <= 0) {
            return false;
        }

        $base_plan = self::normalize_plan($plan);
        $bonus_key = 'vmo_' . $base_plan . '_welcome_bonus_claimed';
        if (get_user_meta($user_id, $bonus_key, true)) {
            return false;
        }

        update_user_meta($user_id, 'vmo_unclaimed_signup_bonus', $bonus_tokens);
        update_user_meta($user_id, 'vmo_unclaimed_signup_bonus_value', $plan_policy['signup_bonus_value']);
        update_user_meta($user_id, 'vmo_unclaimed_signup_bonus_plan', $plan_policy['name']);
        update_user_meta($user_id, $bonus_key, true);
        update_user_meta($user_id, $bonus_key . '_date', current_time('mysql'));

        return true;
    }

    private static function build_plan(array $plan) {
        $price = (float) ($plan['price'] ?? 0);
        $recurring_tokens = (int) ($plan['recurring_tokens'] ?? 0);
        $signup_bonus_tokens = (int) ($plan['signup_bonus_tokens'] ?? 0);

        return [
            'name' => (string) ($plan['name'] ?? 'Plan'),
            'price' => $price,
            'recurring_tokens' => $recurring_tokens,
            'signup_bonus_tokens' => $signup_bonus_tokens,
            'signup_bonus_value' => self::format_money($signup_bonus_tokens * self::get_token_rate()),
            'month_one_total_tokens' => $recurring_tokens + $signup_bonus_tokens,
            'background_ops_enabled' => !empty($plan['background_ops_enabled']),
            'background_ops_frequency' => (string) ($plan['background_ops_frequency'] ?? 'none'),
            'cron_interval' => $plan['cron_interval'] ?? null,
            'monthly_ops' => (int) ($plan['monthly_ops'] ?? 0),
            'priority_compute' => !empty($plan['priority_compute']),
            'provider_cost_budget' => round($price * self::get_provider_cost_budget_rate(), 2),
            'min_net_profit_floor' => round($price * self::get_min_net_profit_rate(), 2),
        ];
    }

    /**
     * QuickLaunch-only launch credit tokens (one-time, added to the wallet at provisioning
     * to absorb the extra setup work QL performs vs Direct: server spin-up, domain
     * registration, email infra, DNS, SSL automation). Funded by the +$50/mo QL uplift,
     * NOT recovered in month two. Set per-plan so larger plans get a slightly larger pad.
     */
    public static function get_quicklaunch_launch_credit_tokens($plan) {
        $map = [
            'tester'     => 35000,
            'starter'    => 35000,
            'pro'        => 40000,
            'elite'      => 45000,
            'enterprise' => 50000,
        ];
        $key = self::normalize_plan($plan);
        return (int) ($map[$key] ?? 0);
    }

    private static function get_token_rate() {
        return defined('VMO_TOKEN_RATE') ? (float) VMO_TOKEN_RATE : 0.000667;
    }

    private static function resolve_token_constant($constant_name, $fallback_value) {
        return defined($constant_name) ? constant($constant_name) : $fallback_value;
    }

    private static function format_money($amount) {
        if (function_exists('number_format_i18n')) {
            return '$' . number_format_i18n((float) $amount, 2);
        }

        return '$' . number_format((float) $amount, 2, '.', ',');
    }
}

if (!function_exists('vmo_get_default_affiliate_rate')) {
    function vmo_get_default_affiliate_rate() {
        return VMO_Plan_Policy::get_default_affiliate_rate();
    }
}

if (!function_exists('vmo_normalize_plan_key')) {
    function vmo_normalize_plan_key($plan) {
        return VMO_Plan_Policy::normalize_plan($plan);
    }
}

if (!function_exists('vmo_get_plan_policy')) {
    function vmo_get_plan_policy($plan) {
        return VMO_Plan_Policy::get_plan($plan);
    }
}

if (!function_exists('vmo_get_plan_background_ops_config')) {
    function vmo_get_plan_background_ops_config($plan) {
        return VMO_Plan_Policy::get_background_ops_config($plan);
    }
}

if (!function_exists('vmo_get_plan_checkout_token_grant')) {
    function vmo_get_plan_checkout_token_grant($plan, $fallback_tokens = 0) {
        return VMO_Plan_Policy::get_checkout_token_grant($plan, $fallback_tokens);
    }
}

if (!function_exists('vmo_queue_plan_signup_bonus')) {
    function vmo_queue_plan_signup_bonus($user_id, $plan) {
        return VMO_Plan_Policy::queue_signup_bonus($user_id, $plan);
    }
}