<?php
namespace App\Controllers;

class ConfigController {
    public function saveAIConfig() {
        header('Content-Type: application/json');
        
        $input = json_decode(file_get_contents('php://input'), true);
        
        // Store in session (in production, use database)
        $_SESSION['ai_provider'] = $input['ai_provider'] ?? '';
        $_SESSION['api_key'] = $input['api_key'] ?? '';
        $_SESSION['api_base_url'] = $input['api_base_url'] ?? '';
        
        echo json_encode(['success' => true]);
    }
    
    public function saveTemplate() {
        header('Content-Type: application/json');
        
        $input = json_decode(file_get_contents('php://input'), true);
        
        $_SESSION[$input['type']] = $input['content'] ?? '';
        
        echo json_encode(['success' => true]);
    }
    
    public function checkAIStatus() {
        header('Content-Type: application/json');
        
        // Simple API connection test
        $provider = $_SESSION['ai_provider'] ?? 'openai';
        $apiKey = $_SESSION['api_key'] ?? '';
        
        if (empty($apiKey)) {
            echo json_encode([
                'connected' => false,
                'error' => 'No API key configured'
            ]);
            return;
        }
        
        // Basic validation (in production, make actual API call)
        if (strlen($apiKey) > 10) {
            echo json_encode([
                'connected' => true,
                'provider' => $provider,
                'balance' => null // Could implement balance check for supported providers
            ]);
        } else {
            echo json_encode([
                'connected' => false,
                'error' => 'Invalid API key format'
            ]);
        }
    }
}