<?php
/**
 * SEO Tools
 * Aegean Dominance Admin Panel
 */

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

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

$db = Database::getInstance();
$auditor = new SeoAuditor();

// 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 'analyze':
                $title = $input['title'] ?? '';
                $content = $input['content'] ?? '';
                $meta = $input['meta'] ?? '';
                $result = $auditor->analyze($title, $content, $meta);
                echo json_encode($result);
                break;
                
            case 'generate_slug':
                $text = $input['text'] ?? '';
                echo json_encode(['success' => true, 'slug' => SeoAuditor::generateSlug($text)]);
                break;
                
            case 'suggest_meta':
                $title = $input['title'] ?? '';
                $category = $input['category'] ?? '';
                echo json_encode([
                    'success' => true,
                    'title' => $auditor->suggestTitle($title, $category),
                    'description' => $auditor->suggestDescription($title, $category)
                ]);
                break;
                
            default:
                echo json_encode(['success' => false, 'error' => 'Geçersiz işlem.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// SEO istatistikleri - using existing columns
$stats = [
    // services tablosunda meta_description yerine short_description kullanıyoruz
    'services_no_meta' => $db->fetchColumn("SELECT COUNT(*) FROM services WHERE short_description IS NULL OR short_description = ''"),
    'images_no_alt' => $db->fetchColumn("SELECT COUNT(*) FROM service_images WHERE alt_text IS NULL OR alt_text = ''"),
    // blog_posts tablosunda meta_description yerine excerpt kullanıyoruz
    'blog_no_meta' => $db->fetchColumn("SELECT COUNT(*) FROM blog_posts WHERE excerpt IS NULL OR excerpt = ''")
];

include 'partials/header.php';
?>

<div class="p-6">
    <div class="mb-6">
        <h2 class="text-xl font-semibold text-white">SEO Araçları</h2>
        <p class="text-white/60 text-sm">SEO analizi ve optimizasyon araçları</p>
    </div>
    
    <!-- SEO Health -->
    <div class="grid md:grid-cols-3 gap-6 mb-8">
        <div class="glass-card rounded-xl p-6">
            <div class="flex items-center justify-between mb-2">
                <span class="text-white/60 text-sm">Meta Eksik Hizmet</span>
                <i data-lucide="briefcase" class="w-5 h-5 text-<?= $stats['services_no_meta'] > 0 ? 'yellow' : 'green' ?>-400"></i>
            </div>
            <p class="text-2xl font-bold text-white"><?= $stats['services_no_meta'] ?></p>
            <?php if ($stats['services_no_meta'] > 0): ?>
            <a href="services.php" class="text-yellow-400 text-sm hover:underline">Düzenle →</a>
            <?php else: ?>
            <span class="text-green-400 text-sm">✓ Tamamlandı</span>
            <?php endif; ?>
        </div>
        
        <div class="glass-card rounded-xl p-6">
            <div class="flex items-center justify-between mb-2">
                <span class="text-white/60 text-sm">Alt-Tag Eksik Görsel</span>
                <i data-lucide="image" class="w-5 h-5 text-<?= $stats['images_no_alt'] > 0 ? 'red' : 'green' ?>-400"></i>
            </div>
            <p class="text-2xl font-bold text-white"><?= $stats['images_no_alt'] ?></p>
            <?php if ($stats['images_no_alt'] > 0): ?>
            <a href="gallery.php" class="text-red-400 text-sm hover:underline">Düzenle →</a>
            <?php else: ?>
            <span class="text-green-400 text-sm">✓ Tamamlandı</span>
            <?php endif; ?>
        </div>
        
        <div class="glass-card rounded-xl p-6">
            <div class="flex items-center justify-between mb-2">
                <span class="text-white/60 text-sm">Meta Eksik Blog</span>
                <i data-lucide="file-text" class="w-5 h-5 text-<?= $stats['blog_no_meta'] > 0 ? 'yellow' : 'green' ?>-400"></i>
            </div>
            <p class="text-2xl font-bold text-white"><?= $stats['blog_no_meta'] ?></p>
            <?php if ($stats['blog_no_meta'] > 0): ?>
            <a href="blog.php" class="text-yellow-400 text-sm hover:underline">Düzenle →</a>
            <?php else: ?>
            <span class="text-green-400 text-sm">✓ Tamamlandı</span>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="grid lg:grid-cols-2 gap-6">
        <!-- Content Analyzer -->
        <div class="glass-card rounded-2xl p-6">
            <h3 class="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                <i data-lucide="search" class="w-5 h-5 text-gold"></i>
                İçerik Analizi
            </h3>
            
            <div class="space-y-4">
                <div>
                    <label class="block text-white/70 text-sm mb-2">Başlık</label>
                    <input type="text" id="analyze_title" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="Sayfa başlığı">
                </div>
                
                <div>
                    <label class="block text-white/70 text-sm mb-2">Meta Açıklama</label>
                    <textarea id="analyze_meta" rows="2" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="Meta description"></textarea>
                </div>
                
                <div>
                    <label class="block text-white/70 text-sm mb-2">İçerik</label>
                    <textarea id="analyze_content" rows="6" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="Sayfa içeriği"></textarea>
                </div>
                
                <button onclick="analyzeContent()" class="w-full gold-gradient text-dark-900 font-semibold py-2 px-4 rounded-lg hover:opacity-90">
                    <i data-lucide="scan" class="w-4 h-4 inline mr-2"></i>
                    Analiz Et
                </button>
                
                <div id="analyze_result" class="hidden"></div>
            </div>
        </div>
        
        <!-- Meta Generator -->
        <div class="glass-card rounded-2xl p-6">
            <h3 class="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                <i data-lucide="sparkles" class="w-5 h-5 text-gold"></i>
                Meta Oluşturucu
            </h3>
            
            <div class="space-y-4">
                <div>
                    <label class="block text-white/70 text-sm mb-2">Ürün/Sayfa Adı</label>
                    <input type="text" id="gen_title" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="Örn: Bioklimatik Pergola">
                </div>
                
                <div>
                    <label class="block text-white/70 text-sm mb-2">Kategori</label>
                    <select id="gen_category" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none">
                        <option value="">Seçin...</option>
                        <option value="Pergola">Pergola</option>
                        <option value="Tente">Tente</option>
                        <option value="Perde">Perde</option>
                        <option value="Cam">Cam Sistemleri</option>
                    </select>
                </div>
                
                <button onclick="generateMeta()" class="w-full gold-gradient text-dark-900 font-semibold py-2 px-4 rounded-lg hover:opacity-90">
                    <i data-lucide="wand-2" class="w-4 h-4 inline mr-2"></i>
                    Meta Oluştur
                </button>
                
                <div id="gen_result" class="hidden space-y-4">
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Önerilen Başlık</label>
                        <input type="text" id="suggested_title" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white" readonly>
                    </div>
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Önerilen Açıklama</label>
                        <textarea id="suggested_desc" rows="2" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white" readonly></textarea>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Slug Generator -->
        <div class="glass-card rounded-2xl p-6 lg:col-span-2">
            <h3 class="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                <i data-lucide="link" class="w-5 h-5 text-gold"></i>
                URL Slug Oluşturucu
            </h3>
            
            <div class="flex gap-4">
                <input type="text" id="slug_input" class="flex-1 bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white focus:border-gold focus:outline-none" placeholder="Başlık veya metin girin" oninput="generateSlug()">
                <div class="flex items-center gap-2 bg-dark-800 rounded-lg px-4">
                    <span class="text-white/40">Slug:</span>
                    <span id="slug_output" class="text-gold font-mono">-</span>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
async function analyzeContent() {
    const title = document.getElementById('analyze_title').value;
    const meta = document.getElementById('analyze_meta').value;
    const content = document.getElementById('analyze_content').value;
    
    if (!title) { showToast('Başlık girin', 'warning'); return; }
    
    const result = await apiRequest('seo.php', { action: 'analyze', title, meta, content });
    const div = document.getElementById('analyze_result');
    
    if (result.success) {
        const gradeColors = { 'A+': 'green', 'A': 'green', 'B': 'yellow', 'C': 'orange', 'D': 'red', 'F': 'red' };
        const color = gradeColors[result.grade] || 'white';
        
        let html = `<div class="p-4 rounded-lg bg-dark-800"><div class="flex items-center justify-between mb-4"><span class="text-white">SEO Skoru</span><span class="px-3 py-1 rounded-lg font-bold bg-${color}-500/20 text-${color}-400">${result.grade} (${result.score}/100)</span></div>`;
        
        if (result.errors.length) html += `<div class="mb-3"><p class="text-red-400 text-sm font-medium mb-1">Hatalar:</p><ul class="text-red-400/80 text-sm list-disc list-inside">${result.errors.map(e => `<li>${e}</li>`).join('')}</ul></div>`;
        if (result.warnings.length) html += `<div class="mb-3"><p class="text-yellow-400 text-sm font-medium mb-1">Uyarılar:</p><ul class="text-yellow-400/80 text-sm list-disc list-inside">${result.warnings.map(w => `<li>${w}</li>`).join('')}</ul></div>`;
        if (result.suggestions.length) html += `<div><p class="text-green-400 text-sm font-medium mb-1">Öneriler:</p><ul class="text-green-400/80 text-sm list-disc list-inside">${result.suggestions.map(s => `<li>${s}</li>`).join('')}</ul></div>`;
        
        html += '</div>';
        div.innerHTML = html;
        div.classList.remove('hidden');
    }
}

async function generateMeta() {
    const title = document.getElementById('gen_title').value;
    const category = document.getElementById('gen_category').value;
    
    if (!title) { showToast('İsim girin', 'warning'); return; }
    
    const result = await apiRequest('seo.php', { action: 'suggest_meta', title, category });
    
    if (result.success) {
        document.getElementById('suggested_title').value = result.title;
        document.getElementById('suggested_desc').value = result.description;
        document.getElementById('gen_result').classList.remove('hidden');
    }
}

async function generateSlug() {
    const text = document.getElementById('slug_input').value;
    if (!text) { document.getElementById('slug_output').textContent = '-'; return; }
    
    const result = await apiRequest('seo.php', { action: 'generate_slug', text });
    if (result.success) document.getElementById('slug_output').textContent = result.slug;
}
</script>

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