<?php
/**
 * Blog 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 blog_posts WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Yazı silindi.']);
                break;
                
            case 'generate':
                $title = $input['title'] ?? '';
                $ai = new AiAssistant();
                $result = $ai->generateProductDescription($title, 'Blog');
                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;
}

$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);

// Form gönderimi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    try {
        $data = [
            'title' => trim($_POST['title'] ?? ''),
            'slug' => SeoAuditor::generateSlug($_POST['title'] ?? ''),
            'excerpt' => trim($_POST['excerpt'] ?? ''),
            'content' => $_POST['content'] ?? '',
            'category' => trim($_POST['category'] ?? 'Genel'),
            'meta_title' => trim($_POST['meta_title'] ?? ''),
            'meta_description' => trim($_POST['meta_description'] ?? ''),
            'status' => $_POST['status'] ?? 'draft'
        ];
        
        if ($id > 0) {
            $db->execute(
                "UPDATE blog_posts SET title = ?, slug = ?, excerpt = ?, content = ?, category = ?, meta_title = ?, meta_description = ?, status = ? WHERE id = ?",
                [$data['title'], $data['slug'], $data['excerpt'], $data['content'], $data['category'], $data['meta_title'], $data['meta_description'], $data['status'], $id]
            );
        } else {
            $db->execute(
                "INSERT INTO blog_posts (title, slug, excerpt, content, category, meta_title, meta_description, status, published_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())",
                [$data['title'], $data['slug'], $data['excerpt'], $data['content'], $data['category'], $data['meta_title'], $data['meta_description'], $data['status']]
            );
        }
        
        header("Location: blog.php?success=Kaydedildi");
        exit;
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

$posts = $db->fetchAll("SELECT * FROM blog_posts ORDER BY created_at DESC");
$post = $id > 0 ? $db->fetchOne("SELECT * FROM blog_posts WHERE id = ?", [$id]) : null;

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 ($action === 'list'): ?>
    <div class="flex items-center justify-between mb-6">
        <div>
            <h2 class="text-xl font-semibold text-white">Blog Yazıları</h2>
            <p class="text-white/60 text-sm"><?= count($posts) ?> yazı</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 Yazı
        </a>
    </div>
    
    <div class="glass-card rounded-2xl overflow-hidden">
        <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">Başlık</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">Tarih</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 ($posts as $p): ?>
                <tr class="hover:bg-white/5">
                    <td class="px-6 py-4">
                        <p class="text-white font-medium"><?= htmlspecialchars($p['title']) ?></p>
                        <p class="text-white/40 text-sm">/blog/<?= htmlspecialchars($p['slug']) ?></p>
                    </td>
                    <td class="px-6 py-4">
                        <span class="px-2 py-1 rounded bg-blue-500/20 text-blue-400 text-sm"><?= htmlspecialchars($p['category']) ?></span>
                    </td>
                    <td class="px-6 py-4">
                        <?php if ($p['status'] === 'published'): ?>
                        <span class="text-green-400 flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-green-400"></span>Yayında</span>
                        <?php else: ?>
                        <span class="text-white/40 flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-white/40"></span>Taslak</span>
                        <?php endif; ?>
                    </td>
                    <td class="px-6 py-4 text-white/60"><?= date('d.m.Y', strtotime($p['created_at'])) ?></td>
                    <td class="px-6 py-4 text-right">
                        <a href="?action=edit&id=<?= $p['id'] ?>" class="p-2 rounded-lg hover:bg-white/10 text-white/60 hover:text-white inline-block">
                            <i data-lucide="edit" class="w-4 h-4"></i>
                        </a>
                        <button onclick="deletePost(<?= $p['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>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <script>
    async function deletePost(id) {
        const confirmed = await confirmAction('Bu yazıyı silmek istediğinize emin misiniz?');
        if (!confirmed) return;
        const result = await apiRequest('blog.php', { action: 'delete', id });
        if (result.success) { showToast(result.message, 'success'); location.reload(); }
    }
    </script>
    
    <?php else: ?>
    <form method="POST" class="grid lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2 space-y-6">
            <div class="glass-card rounded-2xl p-6">
                <h3 class="text-lg font-semibold text-white mb-4">İçerik</h3>
                <div class="space-y-4">
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Başlık</label>
                        <input type="text" name="title" 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($post['title'] ?? '') ?>">
                    </div>
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Özet</label>
                        <textarea name="excerpt" 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"><?= htmlspecialchars($post['excerpt'] ?? '') ?></textarea>
                    </div>
                    <div>
                        <label class="block text-white/70 text-sm mb-2">İçerik <button type="button" onclick="generateContent()" class="text-gold text-xs hover:underline ml-2"><i data-lucide="sparkles" class="w-3 h-3 inline"></i> AI ile Oluştur</button></label>
                        <textarea name="content" id="content" rows="15" class="w-full bg-dark-800 border border-white/10 rounded-lg px-4 py-3 text-white focus:border-gold focus:outline-none"><?= htmlspecialchars($post['content'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="space-y-6">
            <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>
            
            <div class="glass-card rounded-2xl p-6 space-y-4">
                <div>
                    <label class="block text-white/70 text-sm mb-2">Kategori</label>
                    <input type="text" 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" value="<?= htmlspecialchars($post['category'] ?? 'Genel') ?>">
                </div>
                <div>
                    <label class="block text-white/70 text-sm mb-2">Durum</label>
                    <select name="status" 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="draft" <?= ($post['status'] ?? '') === 'draft' ? 'selected' : '' ?>>Taslak</option>
                        <option value="published" <?= ($post['status'] ?? '') === 'published' ? 'selected' : '' ?>>Yayında</option>
                    </select>
                </div>
                <div>
                    <label class="block text-white/70 text-sm mb-2">SEO Başlık</label>
                    <input type="text" name="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($post['meta_title'] ?? '') ?>">
                </div>
                <div>
                    <label class="block text-white/70 text-sm mb-2">SEO Açıklama</label>
                    <textarea name="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"><?= htmlspecialchars($post['meta_description'] ?? '') ?></textarea>
                </div>
            </div>
        </div>
    </form>
    
    <script>
    async function generateContent() {
        const title = document.querySelector('input[name="title"]').value;
        if (!title) { showToast('Başlık girin', 'warning'); return; }
        showToast('İçerik oluşturuluyor...', 'info');
        const result = await apiRequest('blog.php', { action: 'generate', title });
        if (result.success) { document.getElementById('content').value = result.content; showToast('İçerik oluşturuldu!', 'success'); }
        else showToast(result.error, 'error');
    }
    </script>
    <?php endif; ?>
</div>

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