<?php
/**
 * City Landing Pages 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 cities WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Şehir silindi.']);
                break;
                
            case 'generate':
                $city = $input['city'] ?? '';
                $baseContent = $input['base_content'] ?? '';
                $ai = new AiAssistant();
                $result = $ai->generateCityContent($city, $baseContent);
                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 = [
            'name' => trim($_POST['name'] ?? ''),
            'slug' => SeoAuditor::generateSlug($_POST['name'] ?? ''),
            'region' => trim($_POST['region'] ?? 'Ege'),
            'meta_title' => trim($_POST['meta_title'] ?? ''),
            'meta_description' => trim($_POST['meta_description'] ?? ''),
            'content' => $_POST['content'] ?? '',
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'display_order' => (int)($_POST['display_order'] ?? 0)
        ];
        
        if ($id > 0) {
            $db->execute(
                "UPDATE cities SET name = ?, slug = ?, region = ?, meta_title = ?, meta_description = ?, content = ?, is_active = ?, display_order = ? WHERE id = ?",
                [$data['name'], $data['slug'], $data['region'], $data['meta_title'], $data['meta_description'], $data['content'], $data['is_active'], $data['display_order'], $id]
            );
        } else {
            $db->execute(
                "INSERT INTO cities (name, slug, region, meta_title, meta_description, content, is_active, display_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                [$data['name'], $data['slug'], $data['region'], $data['meta_title'], $data['meta_description'], $data['content'], $data['is_active'], $data['display_order']]
            );
        }
        
        header("Location: cities.php?success=Kaydedildi");
        exit;
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

$cities = $db->fetchAll("SELECT * FROM cities ORDER BY display_order");
$city = $id > 0 ? $db->fetchOne("SELECT * FROM cities 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">Şehir Landing Sayfaları</h2>
            <p class="text-white/60 text-sm"><?= count($cities) ?> şehir</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 Şehir
        </a>
    </div>
    
    <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php foreach ($cities as $c): ?>
        <div class="glass-card rounded-2xl p-6">
            <div class="flex items-center justify-between mb-4">
                <div class="flex items-center gap-3">
                    <div class="w-12 h-12 rounded-xl bg-gold/20 flex items-center justify-center">
                        <i data-lucide="map-pin" class="w-6 h-6 text-gold"></i>
                    </div>
                    <div>
                        <h3 class="text-white font-semibold"><?= htmlspecialchars($c['name']) ?></h3>
                        <p class="text-white/40 text-sm"><?= htmlspecialchars($c['region']) ?></p>
                    </div>
                </div>
                <?php if ($c['is_active']): ?>
                <span class="w-3 h-3 rounded-full bg-green-400"></span>
                <?php else: ?>
                <span class="w-3 h-3 rounded-full bg-white/30"></span>
                <?php endif; ?>
            </div>
            
            <p class="text-white/60 text-sm mb-4">/<?= htmlspecialchars($c['slug']) ?>-tente-pergola</p>
            
            <div class="flex gap-2">
                <a href="?action=edit&id=<?= $c['id'] ?>" class="flex-1 bg-dark-700 text-white py-2 px-4 rounded-lg text-center hover:bg-dark-600">Düzenle</a>
                <button onclick="deleteCity(<?= $c['id'] ?>)" class="bg-red-500/20 text-red-400 py-2 px-4 rounded-lg hover:bg-red-500/30">
                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                </button>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    
    <script>
    async function deleteCity(id) {
        const confirmed = await confirmAction('Bu şehri silmek istediğinize emin misiniz?');
        if (!confirmed) return;
        const result = await apiRequest('cities.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">Şehir Bilgileri</h3>
                <div class="grid md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Şehir 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($city['name'] ?? '') ?>">
                    </div>
                    <div>
                        <label class="block text-white/70 text-sm mb-2">Bölge</label>
                        <input type="text" name="region" 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($city['region'] ?? 'Ege') ?>">
                    </div>
                </div>
            </div>
            
            <div class="glass-card rounded-2xl p-6">
                <label class="block text-white/70 text-sm mb-2">Sayfa İçeriği <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($city['content'] ?? '') ?></textarea>
            </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">Meta 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($city['meta_title'] ?? '') ?>">
                </div>
                <div>
                    <label class="block text-white/70 text-sm mb-2">Meta 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($city['meta_description'] ?? '') ?></textarea>
                </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="<?= $city['display_order'] ?? 0 ?>">
                </div>
                <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" <?= ($city['is_active'] ?? 1) ? 'checked' : '' ?>>
                    <span class="text-white">Aktif</span>
                </label>
            </div>
        </div>
    </form>
    
    <script>
    async function generateContent() {
        const city = document.querySelector('input[name="name"]').value;
        if (!city) { showToast('Şehir adı girin', 'warning'); return; }
        const baseContent = 'İzmir ve çevresinde profesyonel tente, pergola ve cam balkon hizmetleri sunuyoruz.';
        showToast('İçerik oluşturuluyor...', 'info');
        const result = await apiRequest('cities.php', { action: 'generate', city, base_content: baseContent });
        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'; ?>
