<?php
/**
 * Class for handling credit usage
 * 
 */

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

require_once BOTAMI_PLUGIN_PATH . 'includes/class-api-config.php';

class Botami_Token_Usage {
    /**
     * Get credit usage data from the API
     *
     * @return array|WP_Error Credit usage statistics or error
     */
    public static function get_token_usage() {
        $api_key = get_option('botami_api_key', '');
        
        if (empty($api_key)) {
            return new WP_Error('missing_api_key', 'API key is not configured');
        }
        
        $api_url = Botami_API_Config::get_token_usage_endpoint();
        
        $response = wp_remote_get($api_url, [
            'headers' => [
                'X-API-Key' => $api_key,
                'Content-Type' => 'application/json'
            ],
            'timeout' => 15
        ]);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code !== 200) {
            return new WP_Error(
                'api_error',
                'Error communicating with API: ' . $status_code,
                ['status' => $status_code]
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new WP_Error('json_error', 'Error parsing API response');
        }
        
        if (!isset($data['success']) || !$data['success']) {
            return new WP_Error(
                'api_response_error',
                isset($data['detail']) ? $data['detail'] : 'Unknown error'
            );
        }
        
        // Set options for local access
        if (isset($data['data'])) {
            update_option('botami_token_usage', $data['data']['token_usage']);
            update_option('botami_token_limit', $data['data']['token_limit']);
            update_option('botami_plan_name', $data['data']['plan_name']);
        }
        
        return $data['data'] ?? [];
    }
    
    /**
     * Update credit usage data in WordPress options
     * This should be called when viewing the dashboard
     *
     * @return bool Success status
     */
    public static function update_token_usage() {
        $result = self::get_token_usage();
        
        if (is_wp_error($result)) {
            return false;
        }
        
        return true;
    }
    
    /**
     * Get credit usage percentage
     * 
     * @return float Usage percentage (0-100)
     */
    public static function get_usage_percentage() {
        $usage = get_option('botami_token_usage', 0);
        $limit = get_option('botami_token_limit', 1);
        
        if ($limit <= 0) {
            return 0;
        }
        
        return min(100, ($usage / $limit) * 100);
    }
    
    /**
     * Get formatted credit usage
     * 
     * @return string Formatted number
     */
    public static function get_formatted_usage() {
        $usage = get_option('botami_token_usage', 0);
        return number_format($usage);
    }
    
    /**
     * Get formatted credit limit
     * 
     * @return string Formatted number
     */
    public static function get_formatted_limit() {
        $limit = get_option('botami_token_limit', 0);
        return number_format($limit);
    }
    
    /**
     * Check if credit limit is exceeded
     * 
     * @return bool True if limit is exceeded
     */
    public static function is_limit_exceeded() {
        $usage = get_option('botami_token_usage', 0);
        $limit = get_option('botami_token_limit', 1);
        
        return $usage >= $limit;
    }
    
    /**
     * Get CSS color class based on usage percentage
     * 
     * @return string CSS color class
     */
    public static function get_usage_color_class() {
        $percentage = self::get_usage_percentage();
        
        if ($percentage >= 90) {
            return 'bg-red-500';
        } elseif ($percentage >= 75) {
            return 'bg-orange-500';
        } else {
            return 'bg-green-500';
        }
    }
}