{% extends 'admin/base.html.twig' %}

{% block title %}{{ config.agencyName }} Ayarlari{% endblock %}
{% block page_title %}{{ config.agencyName }} Yapilandirmasi{% endblock %}

{% block body %}
    {# Breadcrumb #}
    <div class="mb-6">
        <nav class="flex items-center gap-2 text-sm text-gray-500">
            <a href="{{ path('admin_agency') }}" class="hover:text-primary-600 transition-colors">
                <i class="fas fa-rss mr-1"></i> Ajanslar
            </a>
            <i class="fas fa-chevron-right text-xs text-gray-300"></i>
            <span class="text-gray-900 font-medium">{{ config.agencyName }}</span>
        </nav>
    </div>

    <form method="post" action="{{ path('admin_agency_edit', {id: config.id}) }}" class="space-y-6">
        <input type="hidden" name="_token" value="{{ csrf_token('agency_form') }}">

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {# Left: Main form #}
            <div class="lg:col-span-2 space-y-6">
                {% if config.agencySlug == 'rss' %}
                {# ===== RSS OZEL: Haber Kaynaklari ===== #}
                <div class="card" x-data="rssFeeds()" x-init="
                    $el.closest('form').addEventListener('submit', function() {
                        document.querySelector('[name=rss_feeds_json]').value = JSON.stringify(getEnabledFeeds());
                        document.querySelector('[name=rss_custom_feeds_json]').value = JSON.stringify(customFeeds);
                    })
                ">
                    <div class="card-body">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-base font-bold text-gray-900 flex items-center gap-2">
                                <i class="fas fa-rss-square text-orange-600"></i> RSS Haber Kaynaklari
                                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-green-100 text-green-700">
                                    <i class="fas fa-gift mr-1"></i> UCRETSIZ
                                </span>
                            </h3>
                        </div>

                        <p class="text-sm text-gray-500 mb-4">
                            Turkiye'nin onde gelen haber sitelerinden ucretsiz RSS ile haber cekin. Istediginiz kaynaklari secin.
                        </p>

                        {# Hazir Kaynaklar #}
                        <div class="mb-6">
                            <h4 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                                <i class="fas fa-star text-yellow-500"></i> Hazir Kaynaklar
                            </h4>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                                <template x-for="(feed, key) in predefinedFeeds" :key="key">
                                    <label class="flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-all"
                                           :class="feed.enabled ? 'border-orange-300 bg-orange-50' : 'border-gray-200 bg-white hover:bg-gray-50'">
                                        <input type="checkbox"
                                               :name="'rss_feed_' + key"
                                               :value="key"
                                               x-model="feed.enabled"
                                               class="w-4 h-4 text-orange-600 rounded border-gray-300 focus:ring-orange-500">
                                        <div class="flex-1 min-w-0">
                                            <div class="flex items-center gap-2">
                                                <i :class="feed.icon" class="text-sm" :style="'color:' + feed.color"></i>
                                                <span class="text-sm font-medium text-gray-900" x-text="feed.name"></span>
                                            </div>
                                            <p class="text-xs text-gray-400 truncate mt-0.5" x-text="feed.url"></p>
                                        </div>
                                    </label>
                                </template>
                            </div>
                        </div>

                        {# Ozel RSS Kaynaklari #}
                        <div>
                            <h4 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                                <i class="fas fa-plus-circle text-blue-500"></i> Ozel RSS Kaynaklari
                            </h4>
                            <div class="space-y-3">
                                <template x-for="(custom, index) in customFeeds" :key="index">
                                    <div class="flex items-center gap-2">
                                        <input type="checkbox" x-model="custom.enabled"
                                               class="w-4 h-4 text-orange-600 rounded border-gray-300 focus:ring-orange-500">
                                        <input type="text" x-model="custom.name"
                                               placeholder="Kaynak adi"
                                               class="form-input w-1/3 text-sm">
                                        <input type="url" x-model="custom.url"
                                               placeholder="https://example.com/rss"
                                               class="form-input flex-1 text-sm">
                                        <button type="button" @click="customFeeds.splice(index, 1)"
                                                class="p-2 text-red-400 hover:text-red-600 transition-colors">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </div>
                                </template>
                                <button type="button" @click="customFeeds.push({name: '', url: '', enabled: true})"
                                        class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-100 transition-colors">
                                    <i class="fas fa-plus"></i> Ozel Kaynak Ekle
                                </button>
                            </div>
                        </div>

                        {# Hidden inputs - JSON olarak kaydet #}
                        <input type="hidden" name="rss_feeds_json" value="">
                        <input type="hidden" name="rss_custom_feeds_json" value="">

                        {# Test Connection Button #}
                        <div class="pt-4 border-t border-gray-100 mt-4" x-data="{ testing: false, result: null }">
                            <button type="button"
                                    @click="
                                        testing = true;
                                        result = null;
                                        fetch('{{ path('admin_agency_test', {id: config.id}) }}', {
                                            method: 'POST',
                                            headers: {'X-Requested-With': 'XMLHttpRequest'}
                                        })
                                        .then(r => r.json())
                                        .then(data => { result = data; testing = false; })
                                        .catch(() => { result = {success: false, message: 'Baglanti hatasi'}; testing = false; })
                                    "
                                    :disabled="testing"
                                    class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg bg-orange-100 text-orange-700 hover:bg-orange-200 transition-colors disabled:opacity-50">
                                <template x-if="testing">
                                    <i class="fas fa-spinner fa-spin"></i>
                                </template>
                                <template x-if="!testing">
                                    <i class="fas fa-satellite-dish"></i>
                                </template>
                                <span x-text="testing ? 'Test Ediliyor...' : 'Feed Baglantisini Test Et'"></span>
                            </button>
                            <template x-if="result">
                                <div class="mt-3 p-3 rounded-lg text-sm"
                                     :class="result.success ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'">
                                    <i :class="result.success ? 'fas fa-check-circle' : 'fas fa-times-circle'" class="mr-1"></i>
                                    <span x-text="result.message"></span>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
                {% else %}
                {# ===== UCRETLI AJANSLAR: API Baglanti Bilgileri ===== #}
                <div class="card">
                    <div class="card-body">
                        <h3 class="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
                            <i class="fas fa-plug text-primary-600"></i> API Baglanti Bilgileri
                        </h3>

                        <div class="space-y-4">
                            <div>
                                <label for="api_url" class="block text-sm font-medium text-gray-700 mb-1">API URL</label>
                                <input type="url" id="api_url" name="api_url"
                                       value="{{ config.apiUrl }}"
                                       placeholder="https://api.aa.com.tr/v1/"
                                       class="form-input w-full">
                                <p class="text-xs text-gray-400 mt-1">Ajans API endpoint adresi.</p>
                            </div>

                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="api_key" class="block text-sm font-medium text-gray-700 mb-1">API Anahtari (Key)</label>
                                    <input type="text" id="api_key" name="api_key"
                                           value="{{ config.apiKey }}"
                                           placeholder="API anahtarinizi girin"
                                           class="form-input w-full">
                                </div>
                                <div>
                                    <label for="api_secret" class="block text-sm font-medium text-gray-700 mb-1">API Gizli Anahtar (Secret)</label>
                                    <input type="password" id="api_secret" name="api_secret"
                                           value="{{ config.apiSecret }}"
                                           placeholder="API secret anahtarinizi girin"
                                           class="form-input w-full">
                                </div>
                            </div>

                            {# Test Connection Button #}
                            <div class="pt-2" x-data="{ testing: false, result: null }">
                                <button type="button"
                                        @click="
                                            testing = true;
                                            result = null;
                                            fetch('{{ path('admin_agency_test', {id: config.id}) }}', {
                                                method: 'POST',
                                                headers: {'X-Requested-With': 'XMLHttpRequest'}
                                            })
                                            .then(r => r.json())
                                            .then(data => { result = data; testing = false; })
                                            .catch(() => { result = {success: false, message: 'Baglanti hatasi'}; testing = false; })
                                        "
                                        :disabled="testing"
                                        class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors disabled:opacity-50">
                                    <template x-if="testing">
                                        <i class="fas fa-spinner fa-spin"></i>
                                    </template>
                                    <template x-if="!testing">
                                        <i class="fas fa-plug"></i>
                                    </template>
                                    <span x-text="testing ? 'Test Ediliyor...' : 'Baglantiyi Test Et'"></span>
                                </button>
                                <template x-if="result">
                                    <div class="mt-3 p-3 rounded-lg text-sm"
                                         :class="result.success ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'">
                                        <i :class="result.success ? 'fas fa-check-circle' : 'fas fa-times-circle'" class="mr-1"></i>
                                        <span x-text="result.message"></span>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>
                {% endif %}

                {# Haber Cekme Ayarlari #}
                <div class="card">
                    <div class="card-body">
                        <h3 class="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
                            <i class="fas fa-download text-green-600"></i> Haber Cekme Ayarlari
                        </h3>

                        <div class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label for="fetch_interval" class="block text-sm font-medium text-gray-700 mb-1">Cekme Araligi (Dakika)</label>
                                    <input type="number" id="fetch_interval" name="fetch_interval"
                                           value="{{ config.fetchInterval }}"
                                           min="5" max="1440" step="5"
                                           class="form-input w-full">
                                    <p class="text-xs text-gray-400 mt-1">Haberler ne siklikla cekilecek (5-1440 dk).</p>
                                </div>
                                <div>
                                    <label for="default_category_id" class="block text-sm font-medium text-gray-700 mb-1">Varsayilan Kategori</label>
                                    <select id="default_category_id" name="default_category_id" class="form-input w-full">
                                        <option value="">-- Kategori Secin --</option>
                                        {% for category in categories %}
                                            <option value="{{ category.id }}"
                                                    {% if config.defaultCategoryId == category.id %}selected{% endif %}>
                                                {{ category.title }}
                                            </option>
                                        {% endfor %}
                                    </select>
                                    <p class="text-xs text-gray-400 mt-1">Import edilen haberlerin varsayilan kategorisi.</p>
                                </div>
                            </div>

                            <div>
                                <label for="filter_keywords" class="block text-sm font-medium text-gray-700 mb-1">Anahtar Kelime Filtresi</label>
                                <input type="text" id="filter_keywords" name="filter_keywords"
                                       value="{{ config.config.filter_keywords|default([])|join(', ') }}"
                                       placeholder="spor, ekonomi, siyaset"
                                       class="form-input w-full">
                                <p class="text-xs text-gray-400 mt-1">Virgul ile ayrilmis. Sadece bu kelimeleri iceren haberler cekilir. Bos birakilirsa tum haberler cekilir.</p>
                            </div>

                            <div>
                                <label for="filter_categories" class="block text-sm font-medium text-gray-700 mb-1">Ajans Kategori Filtresi</label>
                                <input type="text" id="filter_categories" name="filter_categories"
                                       value="{{ config.config.filter_categories|default([])|join(', ') }}"
                                       placeholder="gundem, spor, ekonomi"
                                       class="form-input w-full">
                                <p class="text-xs text-gray-400 mt-1">Virgul ile ayrilmis ajans kategorileri. Sadece bu kategorilerdeki haberler cekilir.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {# Right: Sidebar options #}
            <div class="space-y-6">
                {# Durum #}
                <div class="card">
                    <div class="card-body">
                        <h3 class="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
                            <i class="fas fa-toggle-on text-blue-600"></i> Durum
                        </h3>

                        <div class="space-y-3">
                            <label class="flex items-center justify-between cursor-pointer">
                                <span class="text-sm text-gray-700">Ajans Aktif</span>
                                <div class="relative">
                                    <input type="checkbox" name="is_active" value="1"
                                           {% if config.isActive %}checked{% endif %}
                                           class="sr-only peer">
                                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
                                </div>
                            </label>

                            <label class="flex items-center justify-between cursor-pointer">
                                <span class="text-sm text-gray-700">Otomatik Yayinla</span>
                                <div class="relative">
                                    <input type="checkbox" name="auto_publish" value="1"
                                           {% if config.isAutoPublish %}checked{% endif %}
                                           class="sr-only peer">
                                    <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-300 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-600"></div>
                                </div>
                            </label>
                        </div>

                        <p class="text-xs text-gray-400 mt-3">
                            Otomatik yayinla aciksa, cekilen haberler dogrudan yayinlanir.
                            Kapaliysa bekleyen haberleri manuel olarak import edebilirsiniz.
                        </p>
                    </div>
                </div>

                {# Ajans Bilgileri #}
                <div class="card">
                    <div class="card-body">
                        <h3 class="text-base font-bold text-gray-900 mb-4 flex items-center gap-2">
                            <i class="fas fa-info-circle text-gray-500"></i> Ajans Bilgileri
                        </h3>

                        <dl class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <dt class="text-gray-500">Ajans Kodu:</dt>
                                <dd class="font-medium text-gray-900">{{ config.agencySlug|upper }}</dd>
                            </div>
                            <div class="flex justify-between">
                                <dt class="text-gray-500">Ajans Adi:</dt>
                                <dd class="font-medium text-gray-900">{{ config.agencyName }}</dd>
                            </div>
                            {% if config.lastFetchedAt %}
                                <div class="flex justify-between">
                                    <dt class="text-gray-500">Son Cekme:</dt>
                                    <dd class="font-medium text-gray-900">{{ config.lastFetchedAt|date('d.m.Y H:i') }}</dd>
                                </div>
                            {% endif %}
                            <div class="flex justify-between">
                                <dt class="text-gray-500">Olusturma:</dt>
                                <dd class="font-medium text-gray-900">{{ config.createdAt|date('d.m.Y') }}</dd>
                            </div>
                        </dl>
                    </div>
                </div>

                {# Submit #}
                <div class="flex flex-col gap-3">
                    <button type="submit" class="btn-primary w-full justify-center">
                        <i class="fas fa-save mr-2"></i> Kaydet
                    </button>
                    <a href="{{ path('admin_agency') }}"
                       class="btn-secondary w-full justify-center text-center">
                        <i class="fas fa-arrow-left mr-2"></i> Geri Don
                    </a>
                </div>
            </div>
        </div>
    </form>

    {% if config.agencySlug == 'rss' %}
    <script>
        function rssFeeds() {
            // Mevcut konfigurasyondaki feed'ler
            const existingFeeds = {{ config.config.feeds|default([])|json_encode|raw }};
            const existingCustom = {{ config.config.custom_feeds|default([])|json_encode|raw }};

            // Onceden tanimli feed'ler
            const allPredefined = {
                trt_haber: { name: 'TRT Haber', url: 'https://www.trthaber.com/sondakika.rss', icon: 'fas fa-tv', color: '#1a73e8', enabled: false },
                cumhuriyet: { name: 'Cumhuriyet', url: 'https://www.cumhuriyet.com.tr/rss', icon: 'fas fa-newspaper', color: '#dc2626', enabled: false },
                ntv: { name: 'NTV', url: 'https://www.ntv.com.tr/son-dakika.rss', icon: 'fas fa-broadcast-tower', color: '#f59e0b', enabled: false },
                haberturk: { name: 'Haberturk', url: 'https://www.haberturk.com/rss', icon: 'fas fa-satellite-dish', color: '#0891b2', enabled: false },
                hurriyet: { name: 'Hurriyet', url: 'https://www.hurriyet.com.tr/rss/anasayfa', icon: 'fas fa-globe', color: '#7c3aed', enabled: false },
            };

            // Mevcut feed'lerden aktif olanlari isaretle
            if (existingFeeds && existingFeeds.length > 0) {
                existingFeeds.forEach(f => {
                    // URL'ye gore eslestir
                    for (const [key, pre] of Object.entries(allPredefined)) {
                        if (f.url === pre.url && f.enabled) {
                            allPredefined[key].enabled = true;
                        }
                    }
                });
            }

            return {
                predefinedFeeds: allPredefined,
                customFeeds: existingCustom && existingCustom.length > 0 ? existingCustom : [],

                getEnabledFeeds() {
                    const feeds = [];
                    for (const [key, feed] of Object.entries(this.predefinedFeeds)) {
                        if (feed.enabled) {
                            feeds.push({
                                name: feed.name,
                                url: feed.url,
                                enabled: true
                            });
                        }
                    }
                    return feeds;
                }
            };
        }
    </script>
    {% endif %}
{% endblock %}
