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

/**
 * VMO Usage Calculator - Smart Flexible Allocation System
 * Calculates usage percentages, category breakdowns, and provides AI recommendations
 */

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

class VMO_Usage_Calculator {
    
    /**
     * Get complete usage data for current user
     *
     * @param int $user_id Optional user ID (defaults to current user)
     * @return array Usage data including percentages, categories, days remaining
     */
    public static function get_usage_data($user_id = null) {
        if (!$user_id) {
            $user_id = get_current_user_id();
        }
        
        if (function_exists('vmo_is_internal_unmetered_user') && vmo_is_internal_unmetered_user($user_id)) {
            return [
                'plan' => 'enterprise_pack',
                'plan_name' => 'Master Account',
                'current_balance' => 999999999,
                'plan_tokens' => 999999999,
                'tokens_used' => 0,
                'usage_percent' => 0,
                'days_remaining' => 'Lifetime', // String instead of int
                'renewal_date' => '2099-12-31',
                'categories' => [],
                'business_type' => 'enterprise',
                'recommendations' => [],
                'status' => 'active'
            ];
        }

        // Get current plan and token balance
        $plan = get_user_meta($user_id, 'vmo_subscription_status', true) ?: 'free';
        $current_balance = (int) get_user_meta($user_id, 'vmo_token_balance', true);
        
        // Get plan token allocation
        $plan_tokens = self::get_plan_allocation($plan);
        
        // Calculate usage percentage
        $tokens_used = max(0, $plan_tokens - $current_balance);
        $usage_percent = $plan_tokens > 0 ? round(($tokens_used / $plan_tokens) * 100, 1) : 0;
        
        // Get renewal date
        $renewal_date = get_user_meta($user_id, 'vmo_subscription_renewal_date', true);
        $days_remaining = self::get_days_remaining($renewal_date);
        
        // Get category breakdown
        $categories = self::get_category_usage($user_id);
        
        // Get business type and recommendations
        $business_type = get_user_meta($user_id, 'vmo_business_type', true) ?: 'other';
        $recommendations = self::get_ai_recommendations($usage_percent, $categories, $business_type, $days_remaining);
        
        return [
            'plan' => $plan,
            'plan_name' => self::get_plan_display_name($plan),
            'current_balance' => $current_balance,
            'plan_tokens' => $plan_tokens,
            'tokens_used' => $tokens_used,
            'usage_percent' => $usage_percent,
            'days_remaining' => $days_remaining,
            'renewal_date' => $renewal_date,
            'categories' => $categories,
            'business_type' => $business_type,
            'recommendations' => $recommendations,
            'status' => self::get_usage_status($usage_percent)
        ];
    }
    
    /**
     * Get token allocation for a plan
     * Updated: Nov 2025 - 23% net margin sustainable model
     */
    private static function get_plan_allocation($plan) {
        if (class_exists('VMO_Plan_Policy')) {
            $plan_policy = VMO_Plan_Policy::get_plan($plan);
            return (int) ($plan_policy['recurring_tokens'] ?? 0);
        }

        switch ($plan) {
            case 'tester':
            case 'tester_pack':
                return defined('VMO_TOKENS_TESTER_PACKAGE') ? VMO_TOKENS_TESTER_PACKAGE : 36034;
            case 'starter':
            case 'starter_pack':
                return defined('VMO_TOKENS_STARTER_PLAN') ? VMO_TOKENS_STARTER_PLAN : 72326;
            case 'pro':
            case 'pro_pack':
            case 'premium':
            case 'professional':
                return defined('VMO_TOKENS_PRO_PLAN') ? VMO_TOKENS_PRO_PLAN : 144909;
            case 'elite':
            case 'business':
            case 'business_pack':
                return defined('VMO_TOKENS_ELITE_PLAN') ? VMO_TOKENS_ELITE_PLAN : 362659;
            case 'enterprise':
            case 'enterprise_pack':
                return defined('VMO_TOKENS_ENTERPRISE_PLAN') ? VMO_TOKENS_ENTERPRISE_PLAN : 500000;
            default:
                return 0; // Free plan
        }
    }
    
    /**
     * Get display name for plan
     */
    private static function get_plan_display_name($plan) {
        $names = [
            'tester' => __('Tester Package', 'vmo-consultant'),
            'tester_pack' => __('Tester Package', 'vmo-consultant'),
            'starter' => __('Starter Plan', 'vmo-consultant'),
            'starter_pack' => __('Starter Plan', 'vmo-consultant'),
            'pro' => __('Pro Plan', 'vmo-consultant'),
            'pro_pack' => __('Pro Plan', 'vmo-consultant'),
            'premium' => __('Pro Plan', 'vmo-consultant'), // Map old premium to Pro
            'professional' => __('Pro Plan', 'vmo-consultant'),
            'elite' => __('Elite Plan', 'vmo-consultant'),
            'business' => __('Elite Plan', 'vmo-consultant'),
            'business_pack' => __('Elite Plan', 'vmo-consultant'),
            'enterprise' => __('Enterprise Plan', 'vmo-consultant'),
            'enterprise_pack' => __('Enterprise Plan', 'vmo-consultant'),
            'free' => __('No Plan', 'vmo-consultant')
        ];
        return $names[$plan] ?? __('Unknown', 'vmo-consultant');
    }
    
    /**
     * Get days remaining until renewal
     */
    private static function get_days_remaining($renewal_date) {
        if (!$renewal_date) {
            return 30; // Default to 30 if not set
        }
        
        $renewal_timestamp = is_numeric($renewal_date) ? $renewal_date : strtotime($renewal_date);
        $now = current_time('timestamp');
        
        $days = ceil(($renewal_timestamp - $now) / DAY_IN_SECONDS);
        return max(0, $days); // Never negative
    }
    
    /**
     * Get category-based usage breakdown
     * Tracks phone, content, research, automation separately
     */
    private static function get_category_usage($user_id) {
        global $wpdb;
        
        // Check if tracking table exists
        $table_name = $wpdb->prefix . 'vmo_usage_tracking';
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
        
        if (!$table_exists) {
            // Return estimated breakdown based on typical usage
            return self::get_estimated_category_usage($user_id);
        }
        
        // Get actual tracked usage
        $categories = [
            'phone' => 0,
            'content' => 0,
            'research' => 0,
            'automation' => 0
        ];
        
        // Query usage by category
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT feature_type, SUM(tokens_used) as total_tokens 
            FROM $table_name 
            WHERE user_id = %d 
            AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            GROUP BY feature_type",
            $user_id
        ));
        
        foreach ($results as $row) {
            if (isset($categories[$row->feature_type])) {
                $categories[$row->feature_type] = (int) $row->total_tokens;
            }
        }
        
        return $categories;
    }
    
    /**
     * Estimate category usage when tracking table doesn't exist yet
     */
    private static function get_estimated_category_usage($user_id) {
        // For now, return empty usage - will be populated as features are used
        return [
            'phone' => 0,
            'content' => 0,
            'research' => 0,
            'automation' => 0
        ];
    }
    
    /**
     * Get AI recommendations based on usage patterns
     */
    private static function get_ai_recommendations($usage_percent, $categories, $business_type, $days_remaining) {
        $recommendations = [];
        
        // Check if running out too fast
        // ✅ FIX: Prevent division by zero when $days_remaining >= 30 or when at start of cycle
        $days_elapsed = 30 - $days_remaining;
        $daily_rate = ($days_elapsed > 0) ? $usage_percent / $days_elapsed : 0;
        $projected_usage = $daily_rate * 30;
        
        if ($projected_usage > 110) {
            $recommendations[] = [
                'type' => 'warning',
                'message' => sprintf(__('You\'re on track to exceed your monthly allocation by %d%%. Consider upgrading or using features more strategically.', 'vmo-consultant'), round($projected_usage - 100))
            ];
        }
        
        // Business-type specific recommendations
        $ideal_mix = self::get_ideal_category_mix($business_type);
        $total_category_usage = array_sum($categories);
        
        if ($total_category_usage > 0) {
            foreach ($ideal_mix as $category => $ideal_percent) {
                $actual_percent = ($categories[$category] / $total_category_usage) * 100;
                
                if ($actual_percent < ($ideal_percent - 20)) {
                    $recommendations[] = [
                        'type' => 'suggestion',
                        'message' => sprintf(__('%s businesses typically use more %s features. You might be missing opportunities!', 'vmo-consultant'), ucfirst($business_type), $category)
                    ];
                }
            }
        }
        
        // Throttling warnings
        if ($usage_percent >= 90) {
            $recommendations[] = [
                'type' => 'alert',
                'message' => __('You\'ve used 90% of your monthly allocation. High-usage features may be throttled. Consider a top-up or upgrade.', 'vmo-consultant')
            ];
        } elseif ($usage_percent >= 75) {
            $recommendations[] = [
                'type' => 'notice',
                'message' => __('You\'ve used 75% of your allocation with ' . $days_remaining . ' days remaining. Plan accordingly!', 'vmo-consultant')
            ];
        }
        
        return $recommendations;
    }
    
    /**
     * Get ideal category mix for business type
     */
    private static function get_ideal_category_mix($business_type) {
        $mixes = [
            'hotel' => ['phone' => 70, 'content' => 10, 'research' => 10, 'automation' => 10],
            'service' => ['phone' => 60, 'content' => 15, 'research' => 15, 'automation' => 10],
            'ecommerce' => ['phone' => 30, 'content' => 40, 'research' => 20, 'automation' => 10],
            'content' => ['phone' => 20, 'content' => 60, 'research' => 10, 'automation' => 10],
            'restaurant' => ['phone' => 50, 'content' => 25, 'research' => 15, 'automation' => 10],
            'professional' => ['phone' => 45, 'content' => 25, 'research' => 20, 'automation' => 10],
            'other' => ['phone' => 40, 'content' => 30, 'research' => 20, 'automation' => 10]
        ];
        
        return $mixes[$business_type] ?? $mixes['other'];
    }
    
    /**
     * Get usage status (ok, warning, critical)
     */
    private static function get_usage_status($usage_percent) {
        if ($usage_percent >= 90) return 'critical';
        if ($usage_percent >= 75) return 'warning';
        return 'ok';
    }
    
    /**
     * Track feature usage
     * Call this whenever tokens are consumed
     */
    public static function track_usage($user_id, $feature_type, $action, $tokens_used, $metadata = []) {
        global $wpdb;

        if (function_exists('vmo_cfo_log_token_usage')) {
            vmo_cfo_log_token_usage($user_id, $feature_type, $action, $tokens_used, [
                'description' => 'Usage calculator event',
                'metadata' => $metadata,
            ]);
        }
        
        $table_name = $wpdb->prefix . 'vmo_usage_tracking';
        
        // Check if table exists, if not, skip tracking for now
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
        if (!$table_exists) {
            return; // Silently skip - table will be created in future update
        }
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert(
            $table_name,
            [
                'user_id' => $user_id,
                'feature_type' => $feature_type,
                'action' => $action,
                'tokens_used' => $tokens_used,
                'metadata' => json_encode($metadata),
                'created_at' => current_time('mysql')
            ],
            ['%d', '%s', '%s', '%d', '%s', '%s']
        );
    }
}
