<?php
/**
 * Services Management
 * Aegean Dominance Admin Panel
 */

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

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

$db = Database::getInstance();

// 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 'delete':
                $id = (int)($input['id'] ?? 0);
                $db->execute("DELETE FROM services WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Hizmet silindi.']);
                break;
                
            case 'toggle':
                $id = (int)($input['id'] ?? 0);
                $db->execute("UPDATE services SET is_active = NOT is_active WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Durum güncellendi.']);
                break;
                
            case 'generate_content':
                $title = $input['title'] ?? '';
                $category = $input['category'] ?? '';
                
                $ai = new AiAssistant();
                $result = $ai->generateProductDescription($title, $category);
                echo json_encode($result);
                break;
                
            case 'analyze_seo':
                $title = $input['title'] ?? '';
                $content = $input['content'] ?? '';
                $meta = $input['meta_description'] ?? '';
                
                $auditor = new SeoAuditor();
                $result = $auditor->analyze($title, $content, $meta);
                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;
}

// Sayfa aksiyonları
$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);

// Form gönderimi (Normal POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    try {
        $data = [
            'name' => trim($_POST['name'] ?? ''),
            'slug' => SeoAuditor::generateSlug($_POST['name'] ?? ''),
            'short_description' => trim($_POST['short_description'] ?? ''),
            'description' => $_POST['description'] ?? '',
            'category' => trim($_POST['category'] ?? ''),
            'icon' => trim($_POST['icon'] ?? 'umbrella'),
            'price_range' => trim($_POST['price_range'] ?? 'Projeye özel fiyatlandırma'),
            'meta_title' => trim($_POST['meta_title'] ?? ''),
            'meta_description' => trim($_POST['meta_description'] ?? ''),
            'meta_keywords' => trim($_POST['meta_keywords'] ?? ''),
            'is_featured' => isset($_POST['is_featured']) ? 1 : 0,
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'display_order' => (int)($_POST['display_order'] ?? 0)
        ];
        
        // Features JSON
        $features = array_filter(array_map('trim', explode("\n", $_POST['features'] ?? '')));
        $data['features'] = json_encode($features, JSON_UNESCAPED_UNICODE);
        
        if ($id > 0) {
            // Güncelle
            $db->execute(
                "UPDATE services SET 
                    name = ?, slug = ?, short_description = ?, description = ?, 
                    category = ?, icon = ?, price_range = ?, meta_title = ?, 
                    meta_description = ?, meta_keywords = ?, features = ?,
                    is_featured = ?, is_active = ?, display_order = ?
                 WHERE id = ?",
                [
                    $data['name'], $data['slug'], $data['short_description'], $data['description'],
                    $data['category'], $data['icon'], $data['price_range'], $data['meta_title'],
                    $data['meta_description'], $data['meta_keywords'], $data['features'],
                    $data['is_featured'], $data['is_active'], $data['display_order'], $id
                ]
            );
            $message = 'Hizmet başarıyla güncellendi.';
        } else {
            // Yeni ekle
            $db->execute(
                "INSERT INTO services (name, slug, short_description, description, category, icon, price_range, meta_title, meta_description, meta_keywords, features, is_featured, is_active, display_order)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                [
                    $data['name'], $data['slug'], $data['short_description'], $data['description'],
                    $data['category'], $data['icon'], $data['price_range'], $data['meta_title'],
                    $data['meta_description'], $data['meta_keywords'], $data['features'],
                    $data['is_featured'], $data['is_active'], $data['display_order']
                ]
            );
            $id = $db->lastInsertId();
            $message = 'Hizmet başarıyla eklendi.';
        }
        
        header("Location: services.php?success=" . urlencode($message));
        exit;
        
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Veri çekme
$services = $db->fetchAll("SELECT * FROM services ORDER BY display_order, id");
$categories = $db->fetchAll("SELECT DISTINCT category FROM services WHERE category IS NOT NULL ORDER BY category");

// Düzenleme için hizmet
$service = null;
if ($action === 'edit' && $id > 0) {
    $service = $db->fetchOne("SELECT * FROM services WHERE id = ?", [$id]);
}

include 'partials/header.php';
?>

<div class="p-6">
    <?php if (isset($_GET['success'])): ?>
    <div class="mb-6 p-4 rounded-lg bg-green-500/10 border border-green-500/30 text-green-400 flex items-center gap-2">
        <i data-lucide="check-circle" class="w-5 h-5"></i>
        <span><?= htmlspecialchars($_GET['success']) ?></span>
    </div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
    <div class="mb-6 p-4 rounded-lg bg-red-500/10 border border-red-500/30 text-red-400 flex items-center gap-2">
        <i data-lucide="alert-circle" class="w-5 h-5"></i>
        <span><?= htmlspecialchars($error) ?></span>
    </div>
    <?php endif; ?>
    
    <?php if ($action === 'list'): ?>
    <!-- Liste Görünümü -->
    <div class="flex items-center justify-between mb-6">
        <div>
            <h2 class="text-xl font-semibold text-white">Hizmet Listesi</h2>
            <p class="text-white/60 text-sm"><?= count($services) ?> hizmet</p>
        </div>
        <a href="?action=new" class="gold-gradient text-dark-900 font-semibold py-2 px-4 rounded-lg hover:opacity-90 flex items-center gap-2">
            <i data-lucide="plus" class="w-5 h-5"></i>
            Yeni Hizmet
        </a>
    </div>
    
    <div class="glass-card rounded-2xl overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-dark-800">
                    <tr>
                        <th class="text-left text-white/60 text-sm font-medium px-6 py-4">Sıra</th>
                        <th class="text-left text-white/60 text-sm font-medium px-6 py-4">Hizmet</th>
                        <th class="text-left text-white/60 text-sm font-medium px-6 py-4">Kategori</th>
                        <th class="text-left text-white/60 text-sm font-medium px-6 py-4">Durum</th>
                        <th class="text-left text-white/60 text-sm font-medium px-6 py-4">Öne Çıkan</th>
                        <th class="text-right text-white/60 text-sm font-medium px-6 py-4">İşlemler</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-white/5">
                    <?php foreach ($services as $s): ?>
                    <tr class="hover:bg-white/5" data-id="<?= $s['id'] ?>">
                        <td class="px-6 py-4 text-white/60"><?= $s['display_order'] ?></td>
                        <td class="px-6 py-4">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 rounded-lg bg-gold/20 flex items-center justify-center">
                                    <i data-lucide="<?= htmlspecialchars($s['icon'] ?: 'umbrella') ?>" class="w-5 h-5 text-gold"></i>
                                </div>
                                <div>
                                    <p class="text-white font-medium"><?= htmlspecialchars($s['name']) ?></p>
                                    <p class="text-white/40 text-sm">/<?= htmlspecialchars($s['slug']) ?></p>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <span class="px-2 py-1 rounded bg-blue-500/20 text-blue-400 text-sm"><?= htmlspecialchars($s['category']) ?></span>
                        </td>
                        <td class="px-6 py-4">
                            <button onclick="toggleStatus(<?= $s['id'] ?>)" class="status-btn" data-active="<?= $s['is_active'] ?>">
                                <?php if ($s['is_active']): ?>
                                <span class="flex items-center gap-1 text-green-400">
                                    <span class="w-2 h-2 rounded-full bg-green-400"></span>
                                    Aktif
                                </span>
                                <?php else: ?>
                                <span class="flex items-center gap-1 text-white/40">
                                    <span class="w-2 h-2 rounded-full bg-white/40"></span>
                                    Pasif
                                </span>
                                <?php endif; ?>
                            </button>
                        </td>
                        <td class="px-6 py-4">
                            <?php if ($s['is_featured']): ?>
                            <i data-lucide="star" class="w-5 h-5 text-gold fill-current"></i>
                            <?php else: ?>
                            <i data-lucide="star" class="w-5 h-5 text-white/20"></i>
                            <?php endif; ?>
                        </td>
                        <td class="px-6 py-4 text-right">
                            <div class="flex items-center justify-end gap-2">
                                <a href="?action=edit&id=<?= $s['id'] ?>" class="p-2 rounded-lg hover:bg-white/10 text-white/60 hover:text-white">
                                    <i data-lucide="edit" class="w-4 h-4"></i>
                                </a>
                                <button onclick="deleteService(<?= $s['id'] ?>)" class="p-2 rounded-lg hover:bg-red-500/20 text-white/60 hover:text-red-400">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <script>
        async function toggleStatus(id) {
            const result = await apiRequest('services.php', { action: 'toggle', id: id });
            if (result.success) {
                location.reload();
            } else {
                showToast(result.error, 'error');
            }
        }
        
        async function deleteService(id) {
            const confirmed = await confirmAction('Bu hizmeti silmek istediğinize emin misiniz?');
            if (!confirmed) return;
            
            const result = await apiRequest('services.php', { action: 'delete', id: id });
            if (result.success) {
                showToast(result.message, 'success');
                location.reload();
            } else {
                showToast(result.error, 'error');
            }
        }
    </script>
    
    <?php else: ?>
    <!-- Düzenleme/Yeni Form -->
    <div class="flex items-center justify-between mb-6">
        <div>
            <h2 class="text-xl font-semibold text-white"><?= $service ? 'Hizmet Düzenle' : 'Yeni Hizmet' ?></h2>
            <p class="text-white/60 text-sm"><?= $service ? htmlspecialchars($service['name']) : 'Yeni bir hizmet ekleyin' ?></p>
        </div>
        <a href="services.php" class="text-white/60 hover:text-white flex items-center gap-2">
            <i data-lucide="arrow-left" class="w-5 h-5"></i>
            Listeye Dön
        </a>
    </div>
    
    <form method="POST" class="grid lg:grid-cols-3 gap-6">
        <!-- Ana İçerik -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Temel Bilgiler -->
            <div class="glass-card rounded-2xl p-6">
                <h3 class="text-lg font-semibold text-white mb-4">Temel Bilgiler</h3>
                
                <div class="space-y-4">
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Hizmet Adı *</label>
                        <input type="text" name="name" required
                            class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none"
                            value="<?= htmlspecialchars($service['name'] ?? '') ?>"
                            placeholder="Örn: Bioklimatik Pergola">
                    </div>
                    
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Kısa Açıklama</label>
                        <textarea name="short_description" rows="2"
                            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="Hizmetin kısa tanımı..."><?= htmlspecialchars($service['short_description'] ?? '') ?></textarea>
                    </div>
                    
                    <div>
                        <label class="block text-white/70 text-sm mb-2">
                            Detaylı Açıklama
                            <button type="button" onclick="generateContent()" class="ml-2 text-gold text-xs hover:underline">
                                <i data-lucide="sparkles" class="w-3 h-3 inline"></i> AI ile Oluştur
                            </button>
                        </label>
                        <textarea name="description" id="description" rows="10"
                            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="Detaylı hizmet açıklaması (HTML desteklenir)..."><?= htmlspecialchars($service['description'] ?? '') ?></textarea>
                    </div>
                    
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Özellikler (Her satır bir madde)</label>
                        <textarea name="features" rows="5"
                            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="Motorlu açılım&#10;Uzaktan kumanda&#10;5 yıl garanti"><?= htmlspecialchars(implode("\n", json_decode($service['features'] ?? '[]', true) ?: [])) ?></textarea>
                    </div>
                </div>
            </div>
            
            <!-- SEO -->
            <div class="glass-card rounded-2xl p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-semibold text-white">SEO Ayarları</h3>
                    <button type="button" onclick="analyzeSeo()" class="text-gold text-sm hover:underline flex items-center gap-1">
                        <i data-lucide="search" class="w-4 h-4"></i>
                        SEO Analizi
                    </button>
                </div>
                
                <div id="seo-score" class="hidden mb-4 p-4 rounded-lg"></div>
                
                <div class="space-y-4">
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Meta Başlık</label>
                        <input type="text" name="meta_title" id="meta_title"
                            class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none"
                            value="<?= htmlspecialchars($service['meta_title'] ?? '') ?>"
                            placeholder="60 karaktere kadar">
                        <p class="text-white/40 text-xs mt-1">Karakter: <span id="meta_title_count">0</span>/60</p>
                    </div>
                    
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Meta Açıklama</label>
                        <textarea name="meta_description" id="meta_description" rows="2"
                            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="120-160 karakter önerilir"><?= htmlspecialchars($service['meta_description'] ?? '') ?></textarea>
                        <p class="text-white/40 text-xs mt-1">Karakter: <span id="meta_desc_count">0</span>/160</p>
                    </div>
                    
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Anahtar Kelimeler</label>
                        <input type="text" name="meta_keywords"
                            class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none"
                            value="<?= htmlspecialchars($service['meta_keywords'] ?? '') ?>"
                            placeholder="virgülle ayırın">
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Sidebar -->
        <div class="space-y-6">
            <!-- Kaydet -->
            <div class="glass-card rounded-2xl p-6">
                <button type="submit" class="w-full gold-gradient text-dark-900 font-semibold py-3 px-4 rounded-lg hover:opacity-90 flex items-center justify-center gap-2">
                    <i data-lucide="save" class="w-5 h-5"></i>
                    Kaydet
                </button>
            </div>
            
            <!-- Detaylar -->
            <div class="glass-card rounded-2xl p-6">
                <h3 class="text-lg font-semibold text-white mb-4">Detaylar</h3>
                
                <div class="space-y-4">
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Kategori</label>
                        <select name="category" 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="">Seçin...</option>
                            <?php foreach (['Pergola', 'Tente', 'Perde', 'Cam'] as $cat): ?>
                            <option value="<?= $cat ?>" <?= ($service['category'] ?? '') === $cat ? 'selected' : '' ?>><?= $cat ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-white/70 text-sm mb-2">İkon (Lucide)</label>
                        <input type="text" name="icon"
                            class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none"
                            value="<?= htmlspecialchars($service['icon'] ?? 'umbrella') ?>"
                            placeholder="umbrella">
                    </div>
                    
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Fiyat Aralığı</label>
                        <input type="text" name="price_range"
                            class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none"
                            value="<?= htmlspecialchars($service['price_range'] ?? 'Projeye özel fiyatlandırma') ?>">
                    </div>
                    
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Sıralama</label>
                        <input type="number" name="display_order"
                            class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none"
                            value="<?= $service['display_order'] ?? 0 ?>">
                    </div>
                </div>
            </div>
            
            <!-- Durum -->
            <div class="glass-card rounded-2xl p-6">
                <h3 class="text-lg font-semibold text-white mb-4">Durum</h3>
                
                <div class="space-y-4">
                    <label class="flex items-center gap-3 cursor-pointer">
                        <input type="checkbox" name="is_active" class="w-5 h-5 rounded border-white/20 bg-dark-800 text-gold focus:ring-gold/50"
                            <?= ($service['is_active'] ?? 1) ? 'checked' : '' ?>>
                        <span class="text-white">Aktif</span>
                    </label>
                    
                    <label class="flex items-center gap-3 cursor-pointer">
                        <input type="checkbox" name="is_featured" class="w-5 h-5 rounded border-white/20 bg-dark-800 text-gold focus:ring-gold/50"
                            <?= ($service['is_featured'] ?? 0) ? 'checked' : '' ?>>
                        <span class="text-white">Öne Çıkan</span>
                    </label>
                </div>
            </div>
        </div>
    </form>
    
    <script>
        // Karakter sayacı
        document.getElementById('meta_title').addEventListener('input', function() {
            document.getElementById('meta_title_count').textContent = this.value.length;
        });
        document.getElementById('meta_description').addEventListener('input', function() {
            document.getElementById('meta_desc_count').textContent = this.value.length;
        });
        
        // Sayfa yüklendiğinde sayaçları güncelle
        document.getElementById('meta_title').dispatchEvent(new Event('input'));
        document.getElementById('meta_description').dispatchEvent(new Event('input'));
        
        // AI ile içerik oluştur
        async function generateContent() {
            const title = document.querySelector('input[name="name"]').value;
            const category = document.querySelector('select[name="category"]').value;
            
            if (!title) {
                showToast('Önce hizmet adını girin', 'warning');
                return;
            }
            
            showToast('İçerik oluşturuluyor...', 'info');
            
            const result = await apiRequest('services.php', {
                action: 'generate_content',
                title: title,
                category: category
            });
            
            if (result.success) {
                document.getElementById('description').value = result.content;
                showToast('İçerik oluşturuldu!', 'success');
            } else {
                showToast(result.error, 'error');
            }
        }
        
        // SEO Analizi
        async function analyzeSeo() {
            const title = document.querySelector('input[name="name"]').value;
            const content = document.getElementById('description').value;
            const meta = document.getElementById('meta_description').value;
            
            const result = await apiRequest('services.php', {
                action: 'analyze_seo',
                title: title,
                content: content,
                meta_description: meta
            });
            
            const scoreDiv = document.getElementById('seo-score');
            
            if (result.success) {
                const gradeColors = {
                    'A+': 'bg-green-500/20 text-green-400',
                    'A': 'bg-green-500/20 text-green-400',
                    'B': 'bg-yellow-500/20 text-yellow-400',
                    'C': 'bg-orange-500/20 text-orange-400',
                    'D': 'bg-red-500/20 text-red-400',
                    'F': 'bg-red-500/20 text-red-400'
                };
                
                let html = `
                    <div class="flex items-center justify-between mb-4">
                        <span class="text-white">SEO Skoru</span>
                        <span class="${gradeColors[result.grade]} px-3 py-1 rounded-lg font-bold">${result.grade} (${result.score}/100)</span>
                    </div>
                `;
                
                if (result.errors.length > 0) {
                    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.forEach(e => html += `<li>${e}</li>`);
                    html += '</ul></div>';
                }
                
                if (result.warnings.length > 0) {
                    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.forEach(w => html += `<li>${w}</li>`);
                    html += '</ul></div>';
                }
                
                if (result.suggestions.length > 0) {
                    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.forEach(s => html += `<li>${s}</li>`);
                    html += '</ul></div>';
                }
                
                scoreDiv.innerHTML = html;
                scoreDiv.className = 'mb-4 p-4 rounded-lg bg-dark-800';
                scoreDiv.classList.remove('hidden');
            } else {
                showToast(result.error, 'error');
            }
        }
    </script>
    <?php endif; ?>
</div>

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