<?php
/**
 * AI Helper — Gemini + ChatGPT API Integration
 */

/**
 * Get active AI provider settings from DB
 */
function get_ai_provider($provider = null)
{
    global $pdo;
    try {
        if ($provider) {
            $stmt = $pdo->prepare("SELECT * FROM ai_settings WHERE provider = ? AND status = 'active' LIMIT 1");
            $stmt->execute([$provider]);
        } else {
            $stmt = $pdo->query("SELECT * FROM ai_settings WHERE status = 'active' ORDER BY id ASC LIMIT 1");
        }
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (PDOException $e) {
        return null;
    }
}

/**
 * Get AI training data (business context)
 */
function get_ai_training_data()
{
    global $pdo;
    try {
        $stmt = $pdo->query("SELECT * FROM ai_training WHERE status = 'active' ORDER BY id DESC LIMIT 1");
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    } catch (PDOException $e) {
        return null;
    }
}

/**
 * Build system prompt from training data
 */
function build_ai_system_prompt($training = null)
{
    if (!$training)
        $training = get_ai_training_data();

    $prompt = "You are an expert SMS marketing copywriter. ";

    if ($training) {
        $prompt .= "You work for '{$training['business_name']}'. ";
        $prompt .= "Business: {$training['business_description']}. ";
        if (!empty($training['business_type']))
            $prompt .= "Industry: {$training['business_type']}. ";
        if (!empty($training['target_audience']))
            $prompt .= "Target: {$training['target_audience']}. ";
        if (!empty($training['key_products']))
            $prompt .= "Products/Services: {$training['key_products']}. ";
        $prompt .= "Tone: {$training['brand_tone']}. ";
        if (!empty($training['special_instructions']))
            $prompt .= "Instructions: {$training['special_instructions']}. ";
    }

    $prompt .= "\n\nRules:\n";
    $prompt .= "- Create SMS messages that are concise and impactful\n";
    $prompt .= "- Stay within character limits when specified\n";
    $prompt .= "- Use persuasive language appropriate to the brand tone\n";
    $prompt .= "- Include a clear call-to-action\n";
    $prompt .= "- Return ONLY the SMS text, no explanations or quotes\n";

    return $prompt;
}

/**
 * Call Gemini API
 */
function call_gemini_api($prompt, $api_key, $model = 'gemini-2.0-flash')
{
    $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$api_key}";

    $system_prompt = build_ai_system_prompt();

    $data = [
        'contents' => [
            ['role' => 'user', 'parts' => [['text' => $system_prompt . "\n\n" . $prompt]]]
        ],
        'generationConfig' => [
            'temperature' => 0.8,
            'maxOutputTokens' => 500,
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_error)
        return ['success' => false, 'error' => "Curl: $curl_error"];

    $json = json_decode($response, true);
    if ($http_code !== 200) {
        $err = $json['error']['message'] ?? "HTTP $http_code";
        return ['success' => false, 'error' => $err];
    }

    $text = $json['candidates'][0]['content']['parts'][0]['text'] ?? '';
    $text = trim($text, " \n\r\t\"'");

    return ['success' => true, 'text' => $text, 'raw' => $response];
}

/**
 * Call ChatGPT API
 */
function call_chatgpt_api($prompt, $api_key, $model = 'gpt-4o-mini')
{
    $url = "https://api.openai.com/v1/chat/completions";

    $system_prompt = build_ai_system_prompt();

    $data = [
        'model' => $model,
        'messages' => [
            ['role' => 'system', 'content' => $system_prompt],
            ['role' => 'user', 'content' => $prompt]
        ],
        'temperature' => 0.8,
        'max_tokens' => 500
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_error)
        return ['success' => false, 'error' => "Curl: $curl_error"];

    $json = json_decode($response, true);
    if ($http_code !== 200) {
        $err = $json['error']['message'] ?? "HTTP $http_code";
        return ['success' => false, 'error' => $err];
    }

    $text = $json['choices'][0]['message']['content'] ?? '';
    $text = trim($text, " \n\r\t\"'");

    return ['success' => true, 'text' => $text, 'raw' => $response];
}

/**
 * Generate SMS template using configured AI
 */
function ai_generate_sms($prompt, $preferred_provider = null)
{
    $provider_config = get_ai_provider($preferred_provider);

    if (!$provider_config) {
        return ['success' => false, 'error' => 'No active AI provider configured. Go to AI Settings to add API keys.'];
    }

    $provider = $provider_config['provider'];
    $api_key = $provider_config['api_key'];
    $model = $provider_config['model_name'];

    if ($provider === 'gemini') {
        $result = call_gemini_api($prompt, $api_key, $model ?: 'gemini-2.0-flash');
    } elseif ($provider === 'chatgpt') {
        $result = call_chatgpt_api($prompt, $api_key, $model ?: 'gpt-4o-mini');
    } else {
        return ['success' => false, 'error' => "Unknown provider: $provider"];
    }

    $result['provider'] = $provider;

    // Log generation
    if ($result['success']) {
        log_ai_generation($provider, $prompt, $result['text']);
    }

    return $result;
}

/**
 * Log AI template generation
 */
function log_ai_generation($provider, $prompt, $response, $template_id = null)
{
    global $pdo;
    try {
        $type = isset($_SESSION['admin_id']) ? 'admin' : 'user';
        $id = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? 0;
        $stmt = $pdo->prepare("INSERT INTO ai_template_log (provider, prompt, response, template_id, created_by_type, created_by_id) VALUES (?,?,?,?,?,?)");
        $stmt->execute([$provider, $prompt, $response, $template_id, $type, $id]);
    } catch (PDOException $e) { /* silent */
    }
}

/**
 * Test AI provider connection
 */
function test_ai_connection($provider, $api_key, $model = null)
{
    $test_prompt = "Say 'Connection successful' in one line.";

    if ($provider === 'gemini') {
        $result = call_gemini_api($test_prompt, $api_key, $model ?: 'gemini-2.0-flash');
    } elseif ($provider === 'chatgpt') {
        $result = call_chatgpt_api($test_prompt, $api_key, $model ?: 'gpt-4o-mini');
    } else {
        return ['success' => false, 'error' => 'Unknown provider'];
    }

    return $result;
}
?>