<?php

class ThiaAPIHandler {
    private $api_url = 'https://thiaide.com/api/';
    
    public function call($prompt, $temperature = 0.7) {
        global $wpdb;
        
        $api_key = $this->get_api_key();
        
        if (!$api_key) {
            $this->update_api_stats(false, 0);
            return array('error' => 'API key not set. Please configure it in Thia Creator > Settings');
        }
        
        $start_time = microtime(true);
        
        $request_body = array(
            'api_key' => $api_key,
            'prompt' => $prompt,
            'temperature' => $temperature,
            'timestamp' => time()
        );
        
        $response = wp_remote_post($this->api_url, array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'User-Agent' => 'Thia-Creator-WordPress-Plugin/' . THIAIDE_CREATOR_VERSION
            ),
            'body' => json_encode($request_body),
            'timeout' => 60,
            'sslverify' => true
        ));
        
        $response_time = round((microtime(true) - $start_time) * 1000, 2);
        
        if (is_wp_error($response)) {
            $this->update_api_stats(false, 0);
            return array('error' => 'Connection error: ' . $response->get_error_message());
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        
        if ($status_code !== 200) {
            $this->update_api_stats(false, 0);
            $decoded = json_decode($body, true);
            $error_msg = isset($decoded['error']) ? $decoded['error'] : 'HTTP ' . $status_code;
            return array('error' => $error_msg);
        }
        
        $decoded = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->update_api_stats(false, 0);
            return array('error' => 'Invalid JSON response: ' . json_last_error_msg());
        }
        
        if (isset($decoded['error'])) {
            $this->update_api_stats(false, 0);
            return array('error' => $decoded['error']);
        }

        $tokens_used = isset($decoded['tokens_used']) ? $decoded['tokens_used'] : strlen($prompt) / 4;
        $this->update_api_stats(true, $tokens_used);
        return array(
            'text' => $decoded['response'] ?? $decoded['text'] ?? $decoded['result'] ?? '',
            'tokens_used' => $tokens_used,
            'response_time' => $response_time
        );
    }
    
    private function get_api_key() {
        global $wpdb;
        $table = $wpdb->prefix . 'thiaide_content_api_keys';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $table_exists = $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table ) );
        
        if ($table_exists != $table) {
            return '';
        }
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $key = $wpdb->get_var("SELECT api_key FROM `$table` WHERE id = 1");
        
        return $key ? trim($key) : '';
    }
    
    private function update_api_stats($success = true, $tokens_used = 0) {
    global $wpdb;
    
    $stats_table = $wpdb->prefix . 'thiaide_content_api_stats';
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $table_exists = $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $stats_table ) );
    
    if ($table_exists != $stats_table) {
        return;
    }
    
    $today = current_time('Y-m-d');
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $existing = $wpdb->get_var($wpdb->prepare("SELECT id FROM `$stats_table` WHERE date = %s", $today));
    
    if ($existing) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $wpdb->query($wpdb->prepare("UPDATE `$stats_table` SET api_calls = api_calls + 1, total_tokens = total_tokens + %d, successful_calls = successful_calls + %d, failed_calls = failed_calls + %d, updated = NOW() WHERE date = %s", $tokens_used, $success ? 1 : 0, $success ? 0 : 1, $today));
    } else {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $wpdb->insert(
            $stats_table,
            array(
                'date' => $today,
                'api_calls' => 1,
                'total_tokens' => $tokens_used,
                'successful_calls' => $success ? 1 : 0,
                'failed_calls' => $success ? 0 : 1,
                'created' => current_time('mysql'),
                'updated' => current_time('mysql')
            ),
            array('%s', '%d', '%d', '%d', '%d', '%s', '%s')
        );
    }
}
}