<?php

/**
 * Analytics tracking for AI Magic plugin
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.7
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */

/**
 * Tracks and reports plugin usage analytics
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 * @author     AI Magic <info@insya.com>
 */
class Ai_Magic_Analytics
{
    /**
     * Token costs per model (per 1K tokens)
     *
     * @since    1.0.7
     * @var      array
     */
    private static $token_costs = array(
        'gpt-4' => array('input' => 0.03, 'output' => 0.06),
        'gpt-4-turbo' => array('input' => 0.01, 'output' => 0.03),
        'gpt-3.5-turbo' => array('input' => 0.0005, 'output' => 0.0015),
        'gpt-3.5-turbo-16k' => array('input' => 0.003, 'output' => 0.004),
    );

    /**
     * Track an API call
     *
     * @since    1.0.7
     * @param    array    $data  Analytics data
     * @return   int|false       Analytics ID or false on failure
     */
    public static function track($data)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_analytics';

        // Calculate cost
        $cost = self::calculate_cost($data['model'], $data['tokens_used']);

        $result = $wpdb->insert(
            $table,
            array(
                'user_id' => get_current_user_id(),
                'action_type' => sanitize_text_field($data['action_type']),
                'model' => sanitize_text_field($data['model']),
                'tokens_used' => intval($data['tokens_used']),
                'cost' => $cost,
                'success' => isset($data['success']) ? intval($data['success']) : 1,
                'error_message' => isset($data['error_message']) ? sanitize_text_field($data['error_message']) : null,
                'created_at' => current_time('mysql')
            ),
            array('%d', '%s', '%s', '%d', '%f', '%d', '%s', '%s')
        );

        return $result ? $wpdb->insert_id : false;
    }

    /**
     * Calculate cost for tokens
     *
     * @since    1.0.7
     * @param    string    $model        Model name
     * @param    int       $tokens       Number of tokens
     * @return   float                   Cost in dollars
     */
    public static function calculate_cost($model, $tokens)
    {
        // Find matching model cost
        $cost_per_1k = 0.002; // Default fallback

        foreach (self::$token_costs as $model_key => $costs) {
            if (strpos($model, $model_key) !== false) {
                // Use average of input and output for simplicity
                $cost_per_1k = ($costs['input'] + $costs['output']) / 2;
                break;
            }
        }

        return ($tokens / 1000) * $cost_per_1k;
    }

    /**
     * Get statistics for a date range
     *
     * @since    1.0.7
     * @param    string    $start_date  Start date (Y-m-d)
     * @param    string    $end_date    End date (Y-m-d)
     * @param    int       $user_id     Optional user ID filter
     * @return   object                 Statistics object
     */
    public static function get_stats($start_date, $end_date, $user_id = null)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_analytics';

        $where = array("DATE(created_at) BETWEEN %s AND %s");
        $where_values = array($start_date, $end_date);

        if ($user_id) {
            $where[] = "user_id = %d";
            $where_values[] = $user_id;
        }

        $where_clause = 'WHERE ' . implode(' AND ', $where);

        $query = "SELECT 
			COUNT(*) as total_requests,
			SUM(tokens_used) as total_tokens,
			SUM(cost) as total_cost,
			AVG(tokens_used) as avg_tokens,
			SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful_requests,
			SUM(CASE WHEN success = 0 THEN 1 ELSE 0 END) as failed_requests
		FROM $table $where_clause";

        $query = $wpdb->prepare($query, $where_values);

        return $wpdb->get_row($query);
    }

    /**
     * Get usage by model
     *
     * @since    1.0.7
     * @param    string    $start_date  Start date (Y-m-d)
     * @param    string    $end_date    End date (Y-m-d)
     * @return   array                  Array of model usage
     */
    public static function get_usage_by_model($start_date, $end_date)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_analytics';

        $query = $wpdb->prepare(
            "SELECT 
				model,
				COUNT(*) as request_count,
				SUM(tokens_used) as total_tokens,
				SUM(cost) as total_cost
			FROM $table
			WHERE DATE(created_at) BETWEEN %s AND %s
			GROUP BY model
			ORDER BY request_count DESC",
            $start_date,
            $end_date
        );

        return $wpdb->get_results($query);
    }

    /**
     * Get daily usage for chart
     *
     * @since    1.0.7
     * @param    string    $start_date  Start date (Y-m-d)
     * @param    string    $end_date    End date (Y-m-d)
     * @return   array                  Array of daily usage
     */
    public static function get_daily_usage($start_date, $end_date)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_analytics';

        $query = $wpdb->prepare(
            "SELECT 
				DATE(created_at) as date,
				COUNT(*) as request_count,
				SUM(tokens_used) as total_tokens,
				SUM(cost) as total_cost
			FROM $table
			WHERE DATE(created_at) BETWEEN %s AND %s
			GROUP BY DATE(created_at)
			ORDER BY date ASC",
            $start_date,
            $end_date
        );

        return $wpdb->get_results($query);
    }

    /**
     * Get usage by action type
     *
     * @since    1.0.7
     * @param    string    $start_date  Start date (Y-m-d)
     * @param    string    $end_date    End date (Y-m-d)
     * @return   array                  Array of action type usage
     */
    public static function get_usage_by_action($start_date, $end_date)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_analytics';

        $query = $wpdb->prepare(
            "SELECT 
				action_type,
				COUNT(*) as request_count,
				SUM(tokens_used) as total_tokens,
				SUM(cost) as total_cost
			FROM $table
			WHERE DATE(created_at) BETWEEN %s AND %s
			GROUP BY action_type
			ORDER BY request_count DESC",
            $start_date,
            $end_date
        );

        return $wpdb->get_results($query);
    }

    /**
     * Get recent errors
     *
     * @since    1.0.7
     * @param    int    $limit  Number of errors to retrieve
     * @return   array          Array of error records
     */
    public static function get_recent_errors($limit = 10)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_analytics';

        return $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM $table WHERE success = 0 ORDER BY created_at DESC LIMIT %d",
            $limit
        ));
    }

    /**
     * Get total cost for user
     *
     * @since    1.0.7
     * @param    int    $user_id  User ID
     * @return   float            Total cost
     */
    public static function get_user_total_cost($user_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_analytics';

        return floatval($wpdb->get_var($wpdb->prepare(
            "SELECT SUM(cost) FROM $table WHERE user_id = %d",
            $user_id
        )));
    }
}
