<?php
/**
 * SEO Conductor Dashboard
 * Aegean Dominance Admin Panel
 */

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

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

$db = Database::getInstance();
$conductor = new Conductor();

// 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 'audit':
                echo json_encode(['success' => true, 'report' => $conductor->conductFullAudit()]);
                break;
                
            case 'heal_service':
                $id = (int)($input['id'] ?? 0);
                $result = $conductor->healService($id);
                echo json_encode($result);
                break;
                
            case 'heal_city':
                $id = (int)($input['id'] ?? 0);
                $result = $conductor->healCity($id);
                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;
}

// Handle Auto Pilot Toggle Action specifically
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $input = json_decode(file_get_contents('php://input'), true);
    if (($input['action'] ?? '') === 'toggle_autopilot') {
        try {
            $conductor->setAutoPilot((bool)$input['enabled']);
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }
    
    // Handle Heal All
    if (($input['action'] ?? '') === 'heal_all') {
        try {
            $result = $conductor->runAutoPilotRoutine(true); // Force run
            echo json_encode($result);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }
}

include 'partials/header.php';
?>

<div class="p-6">
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
            <h2 class="text-2xl font-bold text-white flex items-center gap-2">
                <i data-lucide="zap" class="text-gold"></i>
                SEO Conductor
            </h2>
            <p class="text-white/60">Sitenizi Google'da 1. sıraya taşımak için otonom iyileştirme asistanı.</p>
        </div>
        
        <div class="flex items-center gap-4">
            <!-- Auto Pilot Toggle -->
            <div class="flex items-center gap-3 bg-dark-800 border border-white/10 rounded-xl px-4 py-2" x-data="{ enabled: <?= $conductor->isAutoPilotEnabled() ? 'true' : 'false' ?> }">
                <span class="text-sm font-medium" :class="enabled ? 'text-green-400' : 'text-white/60'">
                    Oto-Pilot <span x-text="enabled ? 'Açık' : 'Kapalı'"></span>
                </span>
                <button 
                    @click="toggleAutoPilot()" 
                    class="relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-gold focus:ring-offset-2 focus:ring-offset-dark-900"
                    :class="enabled ? 'bg-green-500' : 'bg-white/20'"
                >
                    <span
                        class="inline-block h-4 w-4 transform rounded-full bg-white transition duration-200 ease-in-out"
                        :class="enabled ? 'translate-x-6' : 'translate-x-1'"
                    ></span>
                </button>
            </div>

            <button onclick="runAudit()" id="auditBtn" class="gold-gradient text-dark-900 font-bold py-3 px-6 rounded-xl flex items-center gap-2 hover:opacity-90 transition-all shadow-lg shadow-gold/10">
                <i data-lucide="scan-search" class="w-5 h-5"></i>
                <span>Saha Denetimini Başlat</span>
            </button>
        </div>
    </div>

    <!-- AI Status Card -->
    <?php $ai = new AiAssistant(); ?>
    <?php if (!$ai->isConfigured()): ?>
    <div class="bg-yellow-500/10 border border-yellow-500/20 rounded-xl p-4 mb-8 flex items-center gap-4">
        <div class="w-10 h-10 rounded-full bg-yellow-500/20 flex items-center justify-center">
            <i data-lucide="alert-triangle" class="text-yellow-500"></i>
        </div>
        <div class="flex-1">
            <p class="text-yellow-500 font-semibold">AI API Yapılandırılmadı</p>
            <p class="text-yellow-500/70 text-sm">Otonom iyileştirme özelliklerini kullanmak için API anahtarını ekleyin.</p>
        </div>
        <a href="api.php" class="bg-yellow-500 text-dark-900 px-4 py-2 rounded-lg font-bold text-sm">Ayarlara Git</a>
    </div>
    <?php endif; ?>

    <div id="auditResults" class="hidden space-y-8">
        <!-- Mass Actions -->
        <div class="flex justify-end">
            <button onclick="healAll()" id="healAllBtn" class="bg-green-500/10 text-green-400 border border-green-500/20 px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 hover:bg-green-500/20 transition-all">
                <i data-lucide="wand-2" class="w-4 h-4"></i>
                Tümünü Otomatik İyileştir
            </button>
        </div>

        <!-- Services Audit -->
        <div class="glass-card rounded-2xl overflow-hidden">
            <div class="px-6 py-4 border-b border-white/10 flex items-center justify-between bg-white/5">
                <h3 class="text-lg font-semibold text-white">Hizmet Sayfaları Analizi</h3>
                <span id="serviceCount" class="text-xs font-mono bg-white/10 px-2 py-1 rounded text-white/60">0 Sayfa</span>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="text-white/40 text-xs uppercase tracking-wider border-b border-white/5">
                            <th class="px-6 py-4 font-medium">Sayfa Adı</th>
                            <th class="px-6 py-4 font-medium">SEO Skoru</th>
                            <th class="px-6 py-4 font-medium">Durum / Sorunlar</th>
                            <th class="px-6 py-4 font-medium text-right">Eylem</th>
                        </tr>
                    </thead>
                    <tbody id="servicesTable" class="text-white/80">
                        <!-- AJAX content -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Cities Audit -->
        <div class="glass-card rounded-2xl overflow-hidden">
            <div class="px-6 py-4 border-b border-white/10 flex items-center justify-between bg-white/5">
                <h3 class="text-lg font-semibold text-white">Şehir Landing Sayfaları</h3>
                <span id="cityCount" class="text-xs font-mono bg-white/10 px-2 py-1 rounded text-white/60">0 Sayfa</span>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="text-white/40 text-xs uppercase tracking-wider border-b border-white/5">
                            <th class="px-6 py-4 font-medium">Şehir</th>
                            <th class="px-6 py-4 font-medium">İçerik Durumu</th>
                            <th class="px-6 py-4 font-medium">Eylem</th>
                        </tr>
                    </thead>
                    <tbody id="citiesTable" class="text-white/80">
                        <!-- AJAX content -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Logs Section -->
    <div id="logsSection" class="hidden mt-8">
        <h3 class="text-white/40 text-sm font-medium mb-3 flex items-center gap-2">
            <i data-lucide="terminal" class="w-4 h-4"></i>
            Sistem Kayıtları
        </h3>
        <div id="logsBox" class="bg-dark-900 border border-white/5 rounded-xl p-4 font-mono text-xs text-green-400/80 h-48 overflow-y-auto scrollbar-thin space-y-1">
            <!-- Logs content -->
        </div>
    </div>
</div>

<script>
async function runAudit() {
    const btn = document.getElementById('auditBtn');
    btn.disabled = true;
    btn.innerHTML = '<i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i><span>Denetleniyor...</span>';
    lucide.createIcons();

    try {
        const result = await apiRequest('conductor.php', { action: 'audit' });
        if (result.success) {
            renderResults(result.report);
            addLog("Saha denetimi tamamlandı. Rapor hazır.");
        }
    } catch (e) {
        showToast('Denetim hatası', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = '<i data-lucide="scan-search" class="w-5 h-5"></i><span>Saha Denetimini Başlat</span>';
        lucide.createIcons();
    }
}

function renderResults(report) {
    document.getElementById('auditResults').classList.remove('hidden');
    document.getElementById('logsSection').classList.remove('hidden');

    // Services
    const sTable = document.getElementById('servicesTable');
    document.getElementById('serviceCount').textContent = report.services.length + ' Sayfa';
    sTable.innerHTML = report.services.map(s => {
        const color = s.score >= 85 ? 'green' : (s.score >= 60 ? 'yellow' : 'red');
        return `
            <tr class="border-b border-white/5 hover:bg-white/5 transition-colors">
                <td class="px-6 py-4 font-medium text-white">${s.name}</td>
                <td class="px-6 py-4">
                    <div class="flex items-center gap-2">
                        <div class="w-12 bg-dark-700 h-1.5 rounded-full overflow-hidden">
                            <div class="bg-${color}-500 h-full" style="width: ${s.score}%"></div>
                        </div>
                        <span class="text-sm font-bold text-${color}-400">${s.score}</span>
                    </div>
                </td>
                <td class="px-6 py-4">
                    ${s.issues.length ? `<span class="text-xs text-white/50">${s.issues[0]} (+${s.issues.length-1})</span>` : '<span class="text-green-400 text-xs">✓ Sorun yok</span>'}
                </td>
                <td class="px-6 py-4 text-right">
                    ${s.needs_healing ? 
                        `<button onclick="healService(${s.id})" id="healBtn_${s.id}" class="text-gold border border-gold/20 hover:bg-gold hover:text-dark-900 px-3 py-1 rounded-lg text-xs font-bold transition-all">İyileştir</button>` : 
                        '<span class="text-green-400 text-xs font-bold">OPTIMIZE</span>'}
                </td>
            </tr>
        `;
    }).join('');

    // Cities
    const cTable = document.getElementById('citiesTable');
    document.getElementById('cityCount').textContent = report.cities.length + ' Sayfa';
    cTable.innerHTML = report.cities.map(c => `
        <tr class="border-b border-white/5 hover:bg-white/5 transition-colors">
            <td class="px-6 py-4 font-medium text-white">${c.name}</td>
            <td class="px-6 py-4">
                <span class="text-yellow-400/80 text-xs">⚠ İçerik bulunamadı</span>
            </td>
            <td class="px-6 py-4">
                <button onclick="healCity(${c.id})" id="cityBtn_${c.id}" class="gold-gradient text-dark-900 px-3 py-1 rounded-lg text-xs font-bold">Sayfayı Oluştur</button>
            </td>
        </tr>
    `).join('');
    
    lucide.createIcons();
}

async function healService(id) {
    const btn = document.getElementById('healBtn_' + id);
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i data-lucide="loader-2" class="w-3 h-3 animate-spin inline mr-1"></i>...';
    lucide.createIcons();

    const result = await apiRequest('conductor.php', { action: 'heal_service', id });
    if (result.success) {
        addLog("İyileştirme başarılı: " + result.updated_fields.join(', '));
        showToast('Sayfa AI tarafından iyileştirildi.', 'success');
        runAudit(); // Refresh
    } else {
        showToast(result.error, 'error');
        btn.disabled = false;
        btn.innerHTML = originalText;
    }
}

async function healCity(id) {
    const btn = document.getElementById('cityBtn_' + id);
    btn.disabled = true;
    btn.innerHTML = 'Oluşturuluyor...';
    
    const result = await apiRequest('conductor.php', { action: 'heal_city', id });
    if (result.success) {
        addLog("Şehir sayfası AI ile oluşturuldu.");
        showToast('Şehir sayfası başarıyla oluşturuldu.', 'success');
        runAudit();
    } else {
        showToast(result.error, 'error');
        btn.disabled = false;
        btn.innerHTML = 'Tekrar Dene';
    }
}

function addLog(msg) {
    const box = document.getElementById('logsBox');
    const time = new Date().toLocaleTimeString();
    box.innerHTML += `<div><span class="text-white/30">[${time}]</span> ${msg}</div>`;
    box.scrollTop = box.scrollHeight;
}

// Global API helper
async function apiRequest(url, data) {
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify(data)
    });
    return await response.json();
}

function showToast(msg, type = 'info') {
    const colors = { success: 'bg-green-500', error: 'bg-red-500', warning: 'bg-yellow-500', info: 'bg-blue-500' };
    const toast = document.createElement('div');
    toast.className = `fixed bottom-4 right-4 ${colors[type]} text-white px-6 py-3 rounded-xl shadow-lg z-[9999] transition-all transform translate-y-20`;
    toast.textContent = msg;
    document.body.appendChild(toast);
    setTimeout(() => toast.classList.remove('translate-y-20'), 100);
    setTimeout(() => {
        toast.classList.add('translate-y-20');
        setTimeout(() => toast.remove(), 500);
    }, 3000);
}

async function toggleAutoPilot() {
    // AlpineJS handles the UI state, we just need to sync with server
    // Wait a tick for Alpine to update state variable if accessed via DOM, 
    // but here we are inside an Alpine component scope effectively.
    // However, the function is outside. Let's use the click event context or a simpler approach.
    
    // Better approach: Re-fetch current state to toggle
    const btn = document.querySelector('[x-data]').__x.$data;
    const newState = !btn.enabled;
    btn.enabled = newState; // Optimistic UI update

    const result = await apiRequest('conductor.php', { 
        action: 'toggle_autopilot', 
        enabled: newState 
    });

    if (result.success) {
        showToast('Oto-Pilot ' + (newState ? 'açıldı' : 'kapatıldı'), 'success');
        addLog('Oto-Pilot durumu değiştirildi: ' + (newState ? 'AÇIK' : 'KAPALI'));
    } else {
        btn.enabled = !newState; // Revert
        showToast('Hata oluştu', 'error');
    }
}

async function healAll() {
    if (!confirm('Tüm sorunlu sayfalar için AI içerik üretimi başlatılacak. Bu işlem birkaç dakika sürebilir. Onaylıyor musunuz?')) return;

    const btn = document.getElementById('healAllBtn');
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> İşleniyor...';
    lucide.createIcons();

    addLog("Toplu iyileştirme başlatıldı...");

    try {
        const result = await apiRequest('conductor.php', { action: 'heal_all' });
        if (result.success) {
            addLog("Toplu işlem tamamlandı. " + result.processed_count + " sayfa güncellendi.");
            result.actions.forEach(act => addLog(" > " + act));
            showToast(result.processed_count + ' işlem başarıyla tamamlandı.', 'success');
            runAudit(); // Refresh results
        } else {
            showToast(result.error || 'İşlem başarısız.', 'error');
        }
    } catch (e) {
        showToast('Sunucu zaman aşımı veya hatası.', 'error');
    } finally {
        btn.disabled = false;
        btn.innerHTML = originalText;
        lucide.createIcons();
    }
}
</script>

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