<?php
/**
 * API Settings Management
 * Aegean Dominance Admin Panel
 */

session_start();
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireLogin();

$db = Database::getInstance();
$googleApi = new GoogleApi();
$aiAssistant = new AiAssistant();

// AJAX İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');
    
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
    
    try {
        switch ($action) {
            case 'save_google':
                $json = $input['service_account'] ?? '';
                $result = $googleApi->saveServiceAccount($json);
                echo json_encode($result);
                break;
                
            case 'test_indexing':
                $url = $input['url'] ?? BASE_URL;
                $result = $googleApi->requestIndexing($url);
                echo json_encode($result);
                break;
                
            case 'save_ai':
                $provider = $input['provider'] ?? 'gemini';
                $apiKey = $input['api_key'] ?? '';
                $key = $provider === 'openai' ? 'openai_api_key' : 'gemini_api_key';
                $googleApi->saveSetting($key, $apiKey, true);
                echo json_encode(['success' => true, 'message' => 'API anahtarı kaydedildi.']);
                break;
                
            case 'test_ai':
                $result = $aiAssistant->generateMetaDescription('Test Hizmeti');
                echo json_encode($result);
                break;
                
            default:
                echo json_encode(['success' => false, 'error' => 'Geçersiz işlem.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

include 'partials/header.php';
?>

<div class="p-6">
    <div class="mb-6">
        <h2 class="text-xl font-semibold text-white">API Ayarları</h2>
        <p class="text-white/60 text-sm">Google ve AI servis entegrasyonlarını yapılandırın</p>
    </div>
    
    <div class="grid lg:grid-cols-2 gap-6">
        <!-- Google API -->
        <div class="glass-card rounded-2xl p-6">
            <div class="flex items-center gap-3 mb-6">
                <div class="w-12 h-12 rounded-xl bg-blue-500/20 flex items-center justify-center">
                    <i data-lucide="cloud" class="w-6 h-6 text-blue-400"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Google Indexing API</h3>
                    <p class="text-white/60 text-sm">URL'leri hızlıca indeksleyin</p>
                </div>
            </div>
            
            <div class="space-y-4">
                <div>
                    <label class="block text-white/70 text-sm mb-2">Service Account JSON</label>
                    <textarea id="google_service_account" rows="4"
                        class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white text-xs font-mono focus:border-gold focus:outline-none"
                        placeholder='{"type": "service_account", ...}'></textarea>
                </div>
                
                <div class="flex gap-3">
                    <button type="button" onclick="saveGoogleApi()" class="flex-1 bg-blue-500 text-white py-2 px-4 rounded-lg hover:bg-blue-600">Kaydet</button>
                    <button type="button" onclick="testIndexing()" class="bg-dark-700 text-white py-2 px-4 rounded-lg hover:bg-dark-600">Test</button>
                </div>
            </div>
        </div>
        
        <!-- AI API -->
        <div class="glass-card rounded-2xl p-6">
            <div class="flex items-center gap-3 mb-6">
                <div class="w-12 h-12 rounded-xl bg-purple-500/20 flex items-center justify-center">
                    <i data-lucide="sparkles" class="w-6 h-6 text-purple-400"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">AI Asistan</h3>
                    <p class="text-white/60 text-sm">Gemini veya OpenAI</p>
                </div>
            </div>
            
            <div class="space-y-4">
                <div>
                    <label class="block text-white/70 text-sm mb-2">Sağlayıcı</label>
                    <select id="ai_provider" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none">
                        <option value="gemini">Google Gemini</option>
                        <option value="openai">OpenAI GPT-4</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-white/70 text-sm mb-2">API Key</label>
                    <input type="password" id="ai_api_key" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none" placeholder="API anahtarınız">
                </div>
                
                <div class="flex gap-3">
                    <button type="button" onclick="saveAiApi()" class="flex-1 bg-purple-500 text-white py-2 px-4 rounded-lg hover:bg-purple-600">Kaydet</button>
                    <button type="button" onclick="testAi()" class="bg-dark-700 text-white py-2 px-4 rounded-lg hover:bg-dark-600">Test</button>
                </div>
                
                <div class="p-3 rounded-lg bg-dark-800 flex items-center justify-between">
                    <span class="text-white/60 text-sm">Durum</span>
                    <?php if ($aiAssistant->isConfigured()): ?>
                    <span class="text-green-400 text-sm">✓ Aktif</span>
                    <?php else: ?>
                    <span class="text-yellow-400 text-sm">⚠ Yapılandırılmadı</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- URL Indexing -->
        <div class="glass-card rounded-2xl p-6 lg:col-span-2">
            <h3 class="text-lg font-semibold text-white mb-4">Hızlı URL İndeksleme</h3>
            <div class="flex gap-3">
                <input type="url" id="index_url" class="flex-1 bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none" value="<?= BASE_URL ?>" placeholder="URL girin">
                <button type="button" onclick="requestIndexing()" class="gold-gradient text-dark-900 font-semibold py-2 px-6 rounded-lg hover:opacity-90">İndeksle</button>
            </div>
            <div id="index_result" class="hidden mt-4 p-4 rounded-lg"></div>
        </div>
    </div>
</div>

<script>
async function saveGoogleApi() {
    const json = document.getElementById('google_service_account').value;
    if (!json) { showToast('JSON gerekli', 'warning'); return; }
    const result = await apiRequest('api.php', { action: 'save_google', service_account: json });
    showToast(result.success ? result.message : result.error, result.success ? 'success' : 'error');
}

async function testIndexing() {
    showToast('Test ediliyor...', 'info');
    const result = await apiRequest('api.php', { action: 'test_indexing', url: '<?= BASE_URL ?>' });
    showToast(result.success ? 'Bağlantı başarılı!' : result.error, result.success ? 'success' : 'error');
}

async function saveAiApi() {
    const provider = document.getElementById('ai_provider').value;
    const apiKey = document.getElementById('ai_api_key').value;
    if (!apiKey) { showToast('API Key gerekli', 'warning'); return; }
    const result = await apiRequest('api.php', { action: 'save_ai', provider, api_key: apiKey });
    if (result.success) { showToast(result.message, 'success'); document.getElementById('ai_api_key').value = ''; }
    else showToast(result.error, 'error');
}

async function testAi() {
    showToast('AI test ediliyor...', 'info');
    const result = await apiRequest('api.php', { action: 'test_ai' });
    showToast(result.success ? 'AI bağlantısı başarılı!' : result.error, result.success ? 'success' : 'error');
}

async function requestIndexing() {
    const url = document.getElementById('index_url').value;
    if (!url) { showToast('URL gerekli', 'warning'); return; }
    showToast('Gönderiliyor...', 'info');
    const result = await apiRequest('api.php', { action: 'test_indexing', url });
    const div = document.getElementById('index_result');
    div.className = 'mt-4 p-4 rounded-lg ' + (result.success ? 'bg-green-500/10 text-green-400' : 'bg-red-500/10 text-red-400');
    div.textContent = result.success ? 'URL başarıyla bildirildi!' : result.error;
    div.classList.remove('hidden');
}
</script>

<?php include 'partials/footer.php'; ?>
