<?php
// includes/token-manager.php
if (!defined('ABSPATH')) exit;

/**
 * VMO Token Economics v8.2.0 - Next-Generation Pricing Model
 * 
 * New Token Structure:
 * - Complete Webpage: 2,500 VMO tokens (hero + 4 sections + menu + form)
 * - Full Website Generation: 26,250 VMO tokens (25x markup)
 * - Single Section: 400-600 VMO tokens (average 500)
 * - AI Refinements: 150-300 VMO tokens (average 225)
 * - Image Generation: 200-400 VMO tokens (average 300)
 * - Advanced Effects: 100-250 VMO tokens (average 175)
 * 
 * Publishing Costs:
 * - Free Users: 625 VMO tokens per page
 * - Subscribers: 500 VMO tokens per page  
 * - Top-Up Users: 550 VMO tokens per page
 * 
 * Token Rollover Policy:
 * - Subscriber Credits: 6 months rollover
 * - Top-Up Credits: 3 months rollover
 * - Free Trial: 7 days expiration
 * 
 * Rate: 1 VMO token = $0.000667
 * Markup: 7-9x standard, 25x for full website generation
 */

/**
 * Update user token balance.
 *
 * @param int $user_id
 * @param int $amount
 * @param string $op 'add' or 'deduct'
 */
function vmo_update_token_balance($user_id, $amount, $op = 'add') {
    $current = (int) get_user_meta($user_id, 'vmo_token_balance', true);
    $new_balance = ($op === 'add') ? $current + $amount : max(0, $current - $amount);
    update_user_meta($user_id, 'vmo_token_balance', $new_balance);
}

/**
 * Get current token balance.
 *
 * @param int $user_id
 * @return int
 */
function vmo_get_token_balance($user_id) {
    return (int) get_user_meta($user_id, 'vmo_token_balance', true);
}

/**
 * Check if user has sufficient tokens for an operation.
 *
 * @param int $user_id
 * @param string $operation 'content', 'image', or 'refinement'
 * @return bool
 */
function vmo_check_token_balance($user_id, $operation) {
    $current = vmo_get_token_balance($user_id);
    $required = vmo_get_token_cost($operation);
    
    return $current >= $required;
}

/**
 * Get token cost for an operation (v8.1.0 updated - all operations now tracked).
 *
 * @param string $operation Operation type
 * @return int Token cost for the operation
 */
function vmo_get_token_cost($operation) {
    switch ($operation) {
        // Content Generation
        case 'full_page':
        case 'content':
            // 20.8x markup: OpenAI cost ~$0.08 → $1.67 → 2,500 VMO tokens
            return defined('VMO_TOKENS_FULL_PAGE') ? VMO_TOKENS_FULL_PAGE : 2500;
        case 'section':
            return defined('VMO_TOKENS_SECTION') ? VMO_TOKENS_SECTION : 500;
        case 'refinement':
            return defined('VMO_TOKENS_REFINEMENT') ? VMO_TOKENS_REFINEMENT : 225;
        
        // Image Generation
        case 'image':
            return defined('VMO_TOKENS_IMAGE_GENERATION') ? VMO_TOKENS_IMAGE_GENERATION : 1080;
        case 'dalle':
        case 'dalle_image':
            return defined('VMO_TOKENS_DALLE_IMAGE') ? VMO_TOKENS_DALLE_IMAGE : 1080;
        
        // Video Generation (Sora 2 Pro)
        case 'sora_video_4s':
        case 'video_4s':
            return defined('VMO_TOKENS_SORA_VIDEO_4S') ? VMO_TOKENS_SORA_VIDEO_4S : 25200;
        case 'sora_video_8s':
        case 'video_8s':
            return defined('VMO_TOKENS_SORA_VIDEO_8S') ? VMO_TOKENS_SORA_VIDEO_8S : 50400;
        case 'sora_video_12s':
        case 'video_12s':
            return defined('VMO_TOKENS_SORA_VIDEO_12S') ? VMO_TOKENS_SORA_VIDEO_12S : 75600;
        // Sora 2 Standard (lower cost option)
        case 'sora_std_4s':
            return defined('VMO_TOKENS_SORA_STD_4S') ? VMO_TOKENS_SORA_STD_4S : 12600;
        case 'sora_std_8s':
            return defined('VMO_TOKENS_SORA_STD_8S') ? VMO_TOKENS_SORA_STD_8S : 25200;
        case 'sora_std_12s':
            return defined('VMO_TOKENS_SORA_STD_12S') ? VMO_TOKENS_SORA_STD_12S : 37800;
        
        // Effects & Animation
        case 'effects':
        case 'animation':
            return defined('VMO_TOKENS_ADVANCED_EFFECTS') ? VMO_TOKENS_ADVANCED_EFFECTS : 175;
        
        // Chat & Conversation
        case 'chat':
            return defined('VMO_TOKENS_AI_CONVERSATION') ? VMO_TOKENS_AI_CONVERSATION : 50;
        case 'consultation':
        case 'consultation_message':
            return defined('VMO_TOKENS_CONSULTATION_MESSAGE') ? VMO_TOKENS_CONSULTATION_MESSAGE : 405;
        
        // Business Wizard
        case 'business_wizard':
            // 16.7x markup: OpenAI cost ~$0.10 → $1.67 → 2,500 VMO tokens
            return defined('VMO_TOKENS_BUSINESS_WIZARD') ? VMO_TOKENS_BUSINESS_WIZARD : 2500;
        case 'generate_website':
        case 'website_generation':
            // 9x markup: OpenAI cost ~$0.70 → $6.30 → 9,450 VMO tokens
            return defined('VMO_TOKENS_GENERATE_WEBSITE') ? VMO_TOKENS_GENERATE_WEBSITE : 9450;
        
        // TTS (Text-to-Speech)
        case 'tts':
        case 'tts_response':
            return defined('VMO_TOKENS_TTS_RESPONSE') ? VMO_TOKENS_TTS_RESPONSE : 81;
        case 'tts_long':
        case 'tts_per_1k':
            return defined('VMO_TOKENS_TTS_PER_1K_CHARS') ? VMO_TOKENS_TTS_PER_1K_CHARS : 405;
        
        // Transcription (Whisper)
        case 'transcription':
        case 'whisper':
            return defined('VMO_TOKENS_TRANSCRIPTION_PER_MIN') ? VMO_TOKENS_TRANSCRIPTION_PER_MIN : 81;
        
        // Vision Analysis
        case 'vision':
        case 'image_analysis':
            return defined('VMO_TOKENS_VISION_ANALYSIS') ? VMO_TOKENS_VISION_ANALYSIS : 270;
        
        // Deep Research
        case 'deep_research':
        case 'research':
            // 9x markup: OpenAI cost ~$1.00 → $9.00 → 13,500 VMO tokens
            return defined('VMO_TOKENS_DEEP_RESEARCH') ? VMO_TOKENS_DEEP_RESEARCH : 13500;
        
        // Document Analysis
        case 'document':
        case 'document_analysis':
            return defined('VMO_TOKENS_DOCUMENT_ANALYSIS') ? VMO_TOKENS_DOCUMENT_ANALYSIS : 405;
        
        // Email Operations
        case 'email':
            return defined('VMO_TOKENS_EMAIL') ? VMO_TOKENS_EMAIL : 50;
        case 'email_campaign':
        case 'email_campaign_generation':
            return defined('VMO_TOKENS_EMAIL_CAMPAIGN_GENERATION') ? VMO_TOKENS_EMAIL_CAMPAIGN_GENERATION : 945;
        
        // Contact & CRM
        case 'contact_insights':
        case 'contact_recommendations':
            return defined('VMO_TOKENS_CONTACT_INSIGHTS') ? VMO_TOKENS_CONTACT_INSIGHTS : 405;
        
        // Quarterly Business Insights (AI-generated performance report)
        case 'quarterly_insights':
        case 'quarterly_report':
            // 12x markup: OpenAI cost ~$0.06 → $0.72 → 1,080 VMO tokens
            return defined('VMO_TOKENS_QUARTERLY_INSIGHTS') ? VMO_TOKENS_QUARTERLY_INSIGHTS : 1080;
        
        // Tax Calculation (AI-powered tax law interpretation)
        case 'tax_calculation':
        case 'tax_estimate':
            // 12x markup: OpenAI cost ~$0.08 → $0.96 → 1,440 VMO tokens
            return defined('VMO_TOKENS_TAX_CALCULATION') ? VMO_TOKENS_TAX_CALCULATION : 1440;
        
        // Business Planning
        case 'roadmap':
        case 'roadmap_generation':
            return defined('VMO_TOKENS_ROADMAP_GENERATION') ? VMO_TOKENS_ROADMAP_GENERATION : 2025;
        
        // Media Integration - AI-powered creative placement (9x markup on ~$0.06 API cost)
        case 'media_integration':
            return defined('VMO_TOKENS_MEDIA_INTEGRATION') ? VMO_TOKENS_MEDIA_INTEGRATION : 900;
        
        // ═══════════════════════════════════════════════════════════════════
        // ✅ RECURRING OPERATIONS v8.1.0 - Weekly/Monthly/Daily automated AI
        // These justify ongoing subscription value
        // ═══════════════════════════════════════════════════════════════════
        
        // Weekly Deep Research - Business intelligence scan
        case 'weekly_deep_research':
        case 'weekly_research':
            // 20x markup: OpenAI cost ~$0.05 → $1.00 → 1,500 VMO tokens
            return defined('VMO_TOKENS_WEEKLY_DEEP_RESEARCH') ? VMO_TOKENS_WEEKLY_DEEP_RESEARCH : 1500;
        
        // Weekly Email Research - Full email marketing automation
        case 'weekly_email_research':
        case 'email_research':
            // 20x markup: OpenAI cost ~$0.10 → $2.00 → 3,000 VMO tokens
            return defined('VMO_TOKENS_WEEKLY_EMAIL_RESEARCH') ? VMO_TOKENS_WEEKLY_EMAIL_RESEARCH : 3000;
        
        // Weekly SEO Audit - Comprehensive SEO analysis
        case 'weekly_seo_audit':
        case 'seo_audit':
            // 20x markup: OpenAI cost ~$0.08 → $1.60 → 2,400 VMO tokens
            return defined('VMO_TOKENS_WEEKLY_SEO_AUDIT') ? VMO_TOKENS_WEEKLY_SEO_AUDIT : 2400;
        
        // Monthly Blog Generation - AI-written SEO blog post
        case 'monthly_blog':
        case 'automated_blog':
            // 20x markup: OpenAI cost ~$0.05 → $1.00 → 1,500 VMO tokens
            return defined('VMO_TOKENS_MONTHLY_BLOG') ? VMO_TOKENS_MONTHLY_BLOG : 1500;
        
        // Competitor Monitoring - Market intelligence scan
        case 'competitor_monitoring':
        case 'competitor_analysis':
            // 20x markup: OpenAI cost ~$0.05 → $1.00 → 1,500 VMO tokens
            return defined('VMO_TOKENS_COMPETITOR_MONITORING') ? VMO_TOKENS_COMPETITOR_MONITORING : 1500;
        
        // Email Strategy Review - Monthly performance analysis
        case 'email_strategy_review':
        case 'email_strategy':
            // 20x markup: OpenAI cost ~$0.04 → $0.80 → 1,200 VMO tokens
            return defined('VMO_TOKENS_EMAIL_STRATEGY_REVIEW') ? VMO_TOKENS_EMAIL_STRATEGY_REVIEW : 1200;
        
        // Content Embeddings - Daily AI knowledge base update
        case 'content_embeddings':
        case 'embeddings':
            return defined('VMO_TOKENS_CONTENT_EMBEDDINGS') ? VMO_TOKENS_CONTENT_EMBEDDINGS : 300;
        
        // Call Summary - Phone call transcription + AI summary
        case 'call_summary':
        case 'call_transcription':
            return defined('VMO_TOKENS_CALL_SUMMARY') ? VMO_TOKENS_CALL_SUMMARY : 450;
        
        // Publishing
        case 'publish':
            return vmo_get_publish_cost();
        
        // Premium Features
        case 'premium':
            return defined('VMO_TOKENS_PREMIUM_FEATURES') ? VMO_TOKENS_PREMIUM_FEATURES : 1000;
        
        // ═══════════════════════════════════════════════════════════════════
        // ✅ TWILIO TELEPHONY COSTS v9.0.0 - Per-usage billing at 2.5x markup
        // 1 VMO Token = $0.000667 (1,500 tokens = $1.00)
        // ═══════════════════════════════════════════════════════════════════
        
        // Outbound call: Twilio $0.014/min → 2.5x = $0.035/min ≈ 53 tokens/min
        case 'call_outbound':
        case 'call_outbound_min':
            return defined('VMO_TOKENS_CALL_OUTBOUND_MIN') ? VMO_TOKENS_CALL_OUTBOUND_MIN : 53;
        
        // Inbound call: Twilio $0.0085/min → 2.5x = $0.021/min ≈ 33 tokens/min
        case 'call_inbound':
        case 'call_inbound_min':
            return defined('VMO_TOKENS_CALL_INBOUND_MIN') ? VMO_TOKENS_CALL_INBOUND_MIN : 33;
        
        // Outbound SMS: Twilio $0.0079 → 2.5x = $0.020 ≈ 30 tokens/msg
        case 'sms_outbound':
            return defined('VMO_TOKENS_SMS_OUTBOUND') ? VMO_TOKENS_SMS_OUTBOUND : 30;
        
        // Inbound SMS: Twilio $0.0075 → 2.5x = $0.019 ≈ 29 tokens/msg
        case 'sms_inbound':
            return defined('VMO_TOKENS_SMS_INBOUND') ? VMO_TOKENS_SMS_INBOUND : 29;
        
        // A2P surcharge per message: Twilio $0.005 → 2.5x = $0.013 ≈ 20 tokens
        case 'a2p_surcharge':
            return defined('VMO_TOKENS_A2P_SURCHARGE') ? VMO_TOKENS_A2P_SURCHARGE : 20;
        
        // Call recording: Twilio $0.0025/min → 2.5x = $0.006/min ≈ 11 tokens/min
        case 'recording':
        case 'call_recording':
            return defined('VMO_TOKENS_RECORDING_MIN') ? VMO_TOKENS_RECORDING_MIN : 11;
        
        // Phone TTS (OpenAI Speech): $0.015/1K chars → 9x = $0.135 → 203 tokens/1K
        // AI operation connected to phone system - charged at 9x vs OpenAI cost
        case 'phone_tts':
        case 'phone_tts_1k':
            return defined('VMO_TOKENS_PHONE_TTS_1K') ? VMO_TOKENS_PHONE_TTS_1K : 203;
        
        // Phone AI conversation turn (GPT-4o-mini): $0.003/turn → 9x = $0.027 → 41 tokens
        // AI operation connected to phone system - charged at 9x vs OpenAI cost
        case 'phone_ai_turn':
        case 'phone_gpt_turn':
            return defined('VMO_TOKENS_PHONE_AI_TURN') ? VMO_TOKENS_PHONE_AI_TURN : 41;
        
        // Phone number activation: Twilio $1 → 2.5x = $2.50 ≈ 3,750 tokens
        case 'phone_activation':
            return defined('VMO_TOKENS_PHONE_ACTIVATION') ? VMO_TOKENS_PHONE_ACTIVATION : 3750;
        
        // Phone number monthly rental: Twilio $1.15/mo → 2.5x = $2.50/mo ≈ 3,750 tokens
        case 'phone_rental':
        case 'phone_monthly':
            return defined('VMO_TOKENS_PHONE_RENTAL') ? VMO_TOKENS_PHONE_RENTAL : 3750;
        
        // A2P Brand registration: Twilio $4 one-time → 2.5x = $10 ≈ 15,000 tokens
        case 'a2p_brand':
            return defined('VMO_TOKENS_A2P_BRAND') ? VMO_TOKENS_A2P_BRAND : 15000;
        
        // A2P Campaign monthly: Twilio $15/mo → 2.5x = $37.50/mo ≈ 56,250 tokens
        case 'a2p_campaign':
            return defined('VMO_TOKENS_A2P_CAMPAIGN_MONTHLY') ? VMO_TOKENS_A2P_CAMPAIGN_MONTHLY : 56250;
        
        // Simultaneous ring extra leg: Twilio $0.014/min → 2.5x ≈ 53 tokens/min
        case 'extra_call_leg':
            return defined('VMO_TOKENS_EXTRA_LEG_MIN') ? VMO_TOKENS_EXTRA_LEG_MIN : 53;
        
        default:
            // Log unknown operation for debugging
            error_log('VMO Token Manager: Unknown operation type: ' . $operation);
            return 0;
    }
}

/**
 * Get publishing cost based on user subscription status.
 *
 * @param int $user_id Optional user ID, defaults to current user
 * @return int Token cost for publishing
 */
function vmo_get_publish_cost($user_id = null) {
    if (!$user_id) $user_id = get_current_user_id();
    
    $subscription_status = get_user_meta($user_id, 'vmo_subscription_status', true);
    $token_type = get_user_meta($user_id, 'vmo_token_type', true);
    
    // Treat all paid plans (legacy and new packs) as subscribers for publish cost
    $subscriber_statuses = [
        'starter', 'pro', 'elite', // legacy
        'starter_pack', 'pro_pack', 'business_pack', 'enterprise_pack', // new packs
        'business', 'enterprise', 'professional' // other legacy aliases
    ];
    if (in_array($subscription_status, $subscriber_statuses, true)) {
        return defined('VMO_TOKENS_PUBLISH_SUBSCRIBER') ? VMO_TOKENS_PUBLISH_SUBSCRIBER : 500;
    } elseif ($token_type === 'topup') {
        return defined('VMO_TOKENS_PUBLISH_TOPUP') ? VMO_TOKENS_PUBLISH_TOPUP : 550;
    } else {
        return defined('VMO_TOKENS_PUBLISH_FREE') ? VMO_TOKENS_PUBLISH_FREE : 625;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// PLAN-BASED BACKGROUND OPERATIONS v9.0.0
// Tester: no background ops
// Starter: monthly background ops
// Pro: twice-monthly background ops
// Elite/Enterprise: weekly background ops
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Get background operations configuration based on user's plan.
 * 
 * @param int $user_id
 * @return array Configuration with enabled, frequency, cron_interval, reason
 */
function vmo_get_background_ops_config($user_id) {
    $subscription_status = get_user_meta($user_id, 'vmo_subscription_status', true);

    if (function_exists('vmo_get_plan_background_ops_config')) {
        return vmo_get_plan_background_ops_config($subscription_status);
    }

    return [
        'enabled' => false,
        'frequency' => 'none',
        'cron_interval' => null,
        'reason' => 'Background operations are not available until a paid plan is active.',
        'monthly_ops' => 0,
        'plan' => 'free',
    ];
}

/**
 * Check if user's plan allows background operations.
 * 
 * @param int $user_id
 * @return bool True if background ops are enabled for this plan
 */
function vmo_can_run_background_ops($user_id) {
    $config = vmo_get_background_ops_config($user_id);
    return $config['enabled'] === true;
}

/**
 * Get the WordPress cron interval for a user's background ops.
 * 
 * @param int $user_id
 * @return string|null WordPress cron interval ('weekly', 'twicemonthly', 'monthly') or null if disabled
 */
function vmo_get_background_ops_interval($user_id) {
    $config = vmo_get_background_ops_config($user_id);
    return $config['cron_interval'];
}

/**
 * Send upgrade prompt when Tester user attempts to use background ops feature.
 * 
 * @param int $user_id
 * @param string $operation The operation that was blocked
 */
function vmo_send_background_ops_upgrade_prompt($user_id, $operation) {
    $config = vmo_get_background_ops_config($user_id);
    
    if ($config['enabled']) {
        return; // User has access, no prompt needed
    }
    
    // Operation display names
    $operation_names = [
        'weekly_deep_research' => 'Weekly Deep Business Research',
        'weekly_email_research' => 'Weekly Email Marketing Automation',
        'seo_audit' => 'SEO Performance Audit',
        'competitor_monitoring' => 'Competitor Intelligence Monitoring',
        'blog_generation' => 'Automated SEO Blog Generation',
        'ranking_tracking' => 'Keyword Ranking Tracking',
        'email_strategy_review' => 'Email Strategy Review',
    ];
    
    $op_name = $operation_names[$operation] ?? ucwords(str_replace('_', ' ', (string) $operation));
    
    // Store notification for dashboard display
    $notifications = get_user_meta($user_id, 'vmo_upgrade_prompts', true) ?: [];
    $notifications[] = [
        'operation' => $operation,
        'operation_name' => $op_name,
        'message' => "💡 {$op_name} is a premium feature. Upgrade to Starter ($99.99/mo) for monthly automation, Pro ($199.99/mo) for twice-monthly automation, or Elite ($499.99/mo) for weekly automation.",
        'reason' => $config['reason'],
        'timestamp' => current_time('mysql'),
    ];
    
    // Keep only last 10 notifications
    $notifications = array_slice($notifications, -10);
    update_user_meta($user_id, 'vmo_upgrade_prompts', $notifications);
    
    // Log for debugging
    error_log("VMO Background Ops: Upgrade prompt sent to user {$user_id} for {$operation}");
}

/**
 * Register custom cron schedules for plan-based recurring operations.
 */
add_filter('cron_schedules', function($schedules) {
    if (!isset($schedules['monthly'])) {
        $schedules['monthly'] = [
            'interval' => 30 * DAY_IN_SECONDS,
            'display' => __('Monthly (Every 30 Days)', 'vmo'),
        ];
    }
    if (!isset($schedules['twicemonthly'])) {
        $schedules['twicemonthly'] = [
            'interval' => 14 * DAY_IN_SECONDS, // 14 days
            'display' => __('Twice Monthly (Every 14 Days)', 'vmo'),
        ];
    }
    return $schedules;
});

/**
 * Add tokens with expiration tracking (v7.0.1).
 *
 * @param int $user_id
 * @param int $amount
 * @param string $type 'trial', 'subscriber', 'topup'
 */
function vmo_add_tokens_with_expiration($user_id, $amount, $type) {
    $token_history = get_user_meta($user_id, 'vmo_token_history', true) ?: [];
    
    // Calculate expiration based on type
    $expiration = 0;
    switch ($type) {
        case 'trial':
            $expiration = current_time('timestamp') + (7 * 24 * 60 * 60); // 7 days
            break;
        case 'subscriber':
            $expiration = current_time('timestamp') + (6 * 30 * 24 * 60 * 60); // 6 months
            break;
        case 'topup':
            $expiration = current_time('timestamp') + (3 * 30 * 24 * 60 * 60); // 3 months
            break;
    }
    
    // Add new token batch
    $token_history[] = [
        'amount' => $amount,
        'type' => $type,
        'added_at' => current_time('timestamp'),
        'expires_at' => $expiration,
        'remaining' => $amount
    ];
    
    update_user_meta($user_id, 'vmo_token_history', $token_history);
    
    // Update total balance
    $current_balance = vmo_get_token_balance($user_id);
    update_user_meta($user_id, 'vmo_token_balance', $current_balance + $amount);
    update_user_meta($user_id, 'vmo_token_type', $type);
}

/**
 * Deduct tokens using FIFO (oldest first) system.
 *
 * @param int $user_id
 * @param int $amount
 * @return bool Success
 */
function vmo_deduct_tokens_fifo($user_id, $amount) {
    // Clean expired tokens first
    vmo_clean_expired_tokens($user_id);
    
    $current_balance = vmo_get_token_balance($user_id);
    if ($current_balance < $amount) {
        return false;
    }
    
    $token_history = get_user_meta($user_id, 'vmo_token_history', true) ?: [];
    $remaining_to_deduct = $amount;
    
    // Sort by added_at (FIFO)
    usort($token_history, function($a, $b) {
        return $a['added_at'] - $b['added_at'];
    });
    
    // Deduct from oldest tokens first
    foreach ($token_history as &$batch) {
        if ($remaining_to_deduct <= 0) break;
        if ($batch['remaining'] <= 0) continue;
        
        $deduct_from_batch = min($batch['remaining'], $remaining_to_deduct);
        $batch['remaining'] -= $deduct_from_batch;
        $remaining_to_deduct -= $deduct_from_batch;
    }
    
    // Update history and balance
    update_user_meta($user_id, 'vmo_token_history', $token_history);
    update_user_meta($user_id, 'vmo_token_balance', $current_balance - $amount);
    
    return true;
}

/**
 * Clean expired tokens from user's history.
 *
 * @param int $user_id
 */
function vmo_clean_expired_tokens($user_id) {
    $token_history = get_user_meta($user_id, 'vmo_token_history', true) ?: [];
    $current_time = current_time('timestamp');
    $total_expired = 0;
    
    // Remove expired batches and calculate expired amount
    $token_history = array_filter($token_history, function($batch) use ($current_time, &$total_expired) {
        if ($current_time > $batch['expires_at']) {
            $total_expired += $batch['remaining'];
            return false;
        }
        return true;
    });
    
    if ($total_expired > 0) {
        // Update history and balance
        update_user_meta($user_id, 'vmo_token_history', $token_history);
        $current_balance = vmo_get_token_balance($user_id);
        update_user_meta($user_id, 'vmo_token_balance', max(0, $current_balance - $total_expired));
    }
}

/**
 * Deduct tokens for a specific operation (v7.0.1 updated).
 *
 * @param int $user_id
 * @param string $operation 'full_page', 'section', 'refinement', 'image', 'effects', 'publish'
 * @return bool Success
 */
function vmo_deduct_tokens_for_operation($user_id, $operation) {
    // ADMIN BYPASS: Admins and Editors are not charged tokens
    if (user_can($user_id, 'manage_options') || user_can($user_id, 'edit_pages')) {
        return true;
    }

    $required = vmo_get_token_cost($operation);
    $current = vmo_get_token_balance($user_id);
    
    if ($current < $required) {
        return false;
    }
    
    // Use FIFO deduction system
    $success = vmo_deduct_tokens_fifo($user_id, $required);
    
    if ($success) {
        // Log the operation for analytics
        vmo_log_token_usage($user_id, $operation, $required);
        
        // Check if user needs upgrade notification
        vmo_check_upgrade_notification($user_id);
    }
    
    return $success;
}

/**
 * Log token usage for analytics (v7.0.1).
 *
 * @param int $user_id
 * @param string $operation
 * @param int $tokens_used
 */
function vmo_log_token_usage($user_id, $operation, $tokens_used) {
    $log_entry = [
        'user_id' => $user_id,
        'operation' => $operation,
        'tokens_used' => $tokens_used,
        'dollar_value' => $tokens_used * VMO_TOKEN_RATE,
        'timestamp' => current_time('mysql')
    ];
    
    // Store in WordPress option for analytics
    $logs = get_option('vmo_token_usage_logs', []);
    $logs[] = $log_entry;
    
    // Keep only last 10,000 entries for performance
    if (count($logs) > 10000) {
        $logs = array_slice($logs, -10000);
    }
    
    update_option('vmo_token_usage_logs', $logs);
}

/**
 * Check if user needs upgrade notification (70% depletion threshold).
 *
 * @param int $user_id
 */
function vmo_check_upgrade_notification($user_id) {
    $current_balance = vmo_get_token_balance($user_id);
    $subscription_status = get_user_meta($user_id, 'vmo_subscription_status', true);
    $last_notification = get_user_meta($user_id, 'vmo_last_upgrade_notification', true);
    
    // Notify free users (no tokens) to purchase a plan
    if ($subscription_status === 'free' && $current_balance === 0) {
        if ((time() - (int)$last_notification) > 86400) {
            update_user_meta($user_id, 'vmo_last_upgrade_notification', time());
            update_user_meta($user_id, 'vmo_needs_upgrade_notification', true);
        }
        return;
    }
    
    // For paid users, notify when balance is low (below 10% of plan allocation)
    $plan_tokens = defined('VMO_TOKENS_STARTER_PLAN') ? VMO_TOKENS_STARTER_PLAN : 72326;
    $percentage_remaining = ($plan_tokens > 0) ? ($current_balance / $plan_tokens) * 100 : 0;
    
    if ($percentage_remaining <= 10 && (time() - (int)$last_notification) > 86400) {
        update_user_meta($user_id, 'vmo_last_upgrade_notification', time());
        update_user_meta($user_id, 'vmo_needs_upgrade_notification', true);
    }
}

/**
 * Legacy function for backward compatibility.
 * 
 * @deprecated Use vmo_deduct_tokens_for_operation() instead
 * @param int $user_id
 * @param int $openai_token_cost
 * @return bool Success
 */
function vmo_deduct_tokens_by_openai_usage($user_id, $openai_token_cost) {
    // Estimate operation type based on token usage
    if ($openai_token_cost > 1000) {
        $operation = 'content';
    } elseif ($openai_token_cost > 500) {
        $operation = 'image';
    } else {
        $operation = 'refinement';
    }
    
    return vmo_deduct_tokens_for_operation($user_id, $operation);
}

/**
 * Generic token deduction with admin bypass and logging.
 *
 * @param int $user_id
 * @param int $amount
 * @param string $operation_type
 * @param string $description Optional description
 * @return bool Success
 */
function vmo_deduct_tokens($user_id, $amount, $operation_type = 'generic', $description = '') {
    // ADMIN BYPASS: Admins and Editors are not charged tokens
    if (user_can($user_id, 'manage_options') || user_can($user_id, 'edit_pages')) {
        return true;
    }

    $current = vmo_get_token_balance($user_id);
    if ($current < $amount) {
        return false;
    }

    // Use FIFO deduction system
    $success = vmo_deduct_tokens_fifo($user_id, $amount);
    
    if ($success) {
        // Log the operation for analytics
        vmo_log_token_usage($user_id, $operation_type, $amount);
        
        // Check if user needs upgrade notification
        vmo_check_upgrade_notification($user_id);
    }
    
    return $success;
}
