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

{% block title %}{{ ad ? 'Reklam Düzenle' : 'Yeni Reklam' }}{% endblock %}
{% block page_title %}{{ ad ? 'Reklam Düzenle: ' ~ ad.name : 'Yeni Reklam Oluştur' }}{% endblock %}

{% block body %}
    <form method="post"
          action="{{ ad ? path('admin_ad_edit', {id: ad.id}) : path('admin_ad_create') }}"
          enctype="multipart/form-data"
          x-data="adForm()"
          x-init="init()">
        <input type="hidden" name="_token" value="{{ csrf_token('ad_form') }}">

        <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
            {# Left column (8/12) #}
            <div class="lg:col-span-8 space-y-6">

                {# ======================== Reklam Bilgileri Card ======================== #}
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-ad mr-2 text-primary-500"></i>Reklam Bilgileri</h3>
                    </div>
                    <div class="card-body space-y-4">
                        {# Name #}
                        <div>
                            <label for="name" class="form-label">Reklam Adı <span class="text-red-500">*</span></label>
                            <input type="text" id="name" name="name" required
                                   value="{{ ad ? ad.name : '' }}"
                                   class="form-input w-full"
                                   placeholder="Reklam adı">
                        </div>

                        {# Position Category #}
                        <div>
                            <label for="position_category" class="form-label">Pozisyon Kategorisi <span class="text-red-500">*</span></label>
                            <select id="position_category" name="position_category" class="form-input w-full" required
                                    x-model="selectedCategory" @change="updatePositions()">
                                <option value="">-- Seçiniz --</option>
                                <option value="alan_reklam">Alan Reklamları</option>
                                <option value="altsayfa">Altsayfa Reklamları</option>
                                <option value="genel">Genel Reklamlar</option>
                                <option value="paragraf">Paragraf Reklamları</option>
                                <option value="yan">Yan Reklamlar</option>
                            </select>
                        </div>

                        {# Position #}
                        <div>
                            <label for="position" class="form-label">Pozisyon <span class="text-red-500">*</span></label>
                            <div x-effect="
                                let sel = $refs.positionSelect;
                                sel.innerHTML = '';
                                if (positionList.length === 0) {
                                    let opt = document.createElement('option');
                                    opt.value = '';
                                    opt.textContent = '-- Önce kategori seçiniz --';
                                    sel.appendChild(opt);
                                } else {
                                    let defOpt = document.createElement('option');
                                    defOpt.value = '';
                                    defOpt.textContent = '-- Pozisyon seçiniz --';
                                    sel.appendChild(defOpt);
                                    positionList.forEach(function(pos) {
                                        let opt = document.createElement('option');
                                        opt.value = pos.key;
                                        opt.textContent = pos.label;
                                        if (pos.key === selectedPosition) opt.selected = true;
                                        sel.appendChild(opt);
                                    });
                                }
                            "></div>
                            <select id="position" name="position" class="form-input w-full" required
                                    x-ref="positionSelect"
                                    @change="selectedPosition = $event.target.value">
                                <option value="">-- Önce kategori seçiniz --</option>
                            </select>
                        </div>

                        {# Ad Type #}
                        <div>
                            <label for="ad_type" class="form-label">Reklam Tipi <span class="text-red-500">*</span></label>
                            <select id="ad_type" name="ad_type" class="form-input w-full" required x-model="adType">
                                <option value="image">Görsel</option>
                                <option value="video">Video</option>
                                <option value="adsense">AdSense</option>
                                <option value="custom_html">Özel HTML</option>
                            </select>
                        </div>
                    </div>
                </div>

                {# ======================== Reklam İçeriği Card ======================== #}
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-photo-video mr-2 text-primary-500"></i>Reklam İçeriği</h3>
                    </div>
                    <div class="card-body space-y-4">

                        {# === Görsel Yükleme (image type) === #}
                        <div x-show="adType === 'image'" x-cloak>
                            <label class="form-label">Reklam Görseli</label>

                            {# Current image preview #}
                            <template x-if="imagePreview || existingImageUrl">
                                <div class="mb-3">
                                    <div class="relative inline-block">
                                        <img :src="imagePreview || existingImageUrl"
                                             alt="Reklam görseli"
                                             class="max-w-md max-h-64 h-auto rounded-lg border border-gray-200 shadow-sm">
                                        <button type="button"
                                                @click="removeImage()"
                                                class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full text-xs flex items-center justify-center hover:bg-red-600 transition-colors shadow-md">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                            </template>

                            {# Upload zone #}
                            <template x-if="!imagePreview && !existingImageUrl">
                                <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-primary-400 transition-colors cursor-pointer"
                                     @click="$refs.imageInput.click()"
                                     @dragover.prevent="dragOver = true"
                                     @dragleave.prevent="dragOver = false"
                                     @drop.prevent="handleImageDrop($event)"
                                     :class="{ 'border-primary-400 bg-blue-50': dragOver }">
                                    <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3 block"></i>
                                    <p class="text-sm text-gray-600 mb-1">Görsel yüklemek için tıklayın veya sürükleyip bırakın</p>
                                    <p class="text-xs text-gray-400">JPG, PNG, GIF, WebP — Max 5MB</p>
                                </div>
                            </template>
                            <input type="file" name="ad_image" accept="image/*"
                                   class="hidden" x-ref="imageInput"
                                   @change="handleImageSelect($event)">

                            {# Or enter URL #}
                            <div class="mt-3">
                                <label class="text-xs text-gray-500 font-medium">veya görsel URL girin:</label>
                                <input type="url" name="image_url"
                                       x-model="existingImageUrl"
                                       class="form-input w-full mt-1"
                                       placeholder="https://ornek.com/reklam-gorseli.jpg">
                            </div>
                        </div>

                        {# === Video Yükleme (video type) === #}
                        <div x-show="adType === 'video'" x-cloak>
                            <label class="form-label">Reklam Videosu</label>

                            {# Current video preview #}
                            <template x-if="videoPreview">
                                <div class="mb-3">
                                    <div class="relative inline-block">
                                        <video :src="videoPreview" controls
                                               class="max-w-md h-auto rounded-lg border border-gray-200 shadow-sm"></video>
                                        <button type="button"
                                                @click="removeVideo()"
                                                class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full text-xs flex items-center justify-center hover:bg-red-600 transition-colors shadow-md">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                </div>
                            </template>

                            {# Upload zone #}
                            <template x-if="!videoPreview">
                                <div class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-primary-400 transition-colors cursor-pointer"
                                     @click="$refs.videoInput.click()"
                                     @dragover.prevent="dragOver = true"
                                     @dragleave.prevent="dragOver = false"
                                     @drop.prevent="handleVideoDrop($event)"
                                     :class="{ 'border-primary-400 bg-blue-50': dragOver }">
                                    <i class="fas fa-film text-4xl text-gray-400 mb-3 block"></i>
                                    <p class="text-sm text-gray-600 mb-1">Video yüklemek için tıklayın veya sürükleyip bırakın</p>
                                    <p class="text-xs text-gray-400">MP4, WebM — Max 50MB</p>
                                </div>
                            </template>
                            <input type="file" name="ad_video" accept="video/mp4,video/webm"
                                   class="hidden" x-ref="videoInput"
                                   @change="handleVideoSelect($event)">

                            {# Or enter embed code #}
                            <div class="mt-3">
                                <label class="text-xs text-gray-500 font-medium">veya video embed kodu girin:</label>
                                <textarea name="content" rows="3"
                                          class="form-input w-full font-mono text-sm mt-1"
                                          placeholder="Video embed kodu veya URL...">{{ ad and ad.adType == 'video' ? ad.content : '' }}</textarea>
                            </div>
                        </div>

                        {# === AdSense / Custom HTML Code === #}
                        <div x-show="adType === 'adsense' || adType === 'custom_html'" x-cloak>
                            <label for="content" class="form-label">
                                <span x-show="adType === 'adsense'">AdSense Kodu</span>
                                <span x-show="adType === 'custom_html'">Özel HTML / JavaScript Kodu</span>
                            </label>
                            <textarea id="content" name="content" rows="10"
                                      class="form-input w-full font-mono text-sm"
                                      placeholder="Reklam HTML veya JavaScript kodu...">{{ ad and (ad.adType == 'adsense' or ad.adType == 'custom_html') ? ad.content : '' }}</textarea>
                            <p class="text-xs text-gray-500 mt-1">
                                <span x-show="adType === 'adsense'"><i class="fab fa-google mr-1"></i>Google AdSense reklam kodunu yapıştırın.</span>
                                <span x-show="adType === 'custom_html'"><i class="fas fa-code mr-1"></i>HTML, CSS veya JavaScript kodu yapıştırın.</span>
                            </p>
                        </div>

                        {# Target URL (for image/video types) #}
                        <div x-show="adType === 'image' || adType === 'video'" x-cloak>
                            <label for="target_url" class="form-label">Hedef URL</label>
                            <input type="url" id="target_url" name="target_url"
                                   value="{{ ad ? ad.targetUrl : '' }}"
                                   class="form-input w-full"
                                   placeholder="https://ornek.com/hedef-sayfa">
                            <p class="text-xs text-gray-500 mt-1">Reklama tıklandığında yönlendirilecek adres.</p>
                        </div>
                    </div>
                </div>

                {# ======================== Boyut Card ======================== #}
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title"><i class="fas fa-expand-arrows-alt mr-2 text-primary-500"></i>Boyut</h3>
                    </div>
                    <div class="card-body">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label for="width" class="form-label">Genişlik</label>
                                <input type="text" id="width" name="width"
                                       value="{{ ad ? ad.width : '' }}"
                                       class="form-input w-full"
                                       placeholder="Ör: 620, 100%, auto">
                            </div>
                            <div>
                                <label for="height" class="form-label">Yükseklik</label>
                                <input type="text" id="height" name="height"
                                       value="{{ ad ? ad.height : '' }}"
                                       class="form-input w-full"
                                       placeholder="Ör: 250, auto">
                            </div>
                        </div>
                        <p class="text-xs text-gray-500 mt-2">Piksel veya yüzde değeri girebilirsiniz.</p>
                    </div>
                </div>

            </div>

            {# Right column (4/12) #}
            <div class="lg:col-span-4 space-y-6">

                {# ======================== Yayın Ayarları ======================== #}
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Yayın Ayarları</h3>
                    </div>
                    <div class="card-body space-y-4">
                        <div>
                            <label for="status" class="form-label">Durum</label>
                            <select id="status" name="status" class="form-input w-full">
                                {% set status_value = ad ? ad.status : 'draft' %}
                                <option value="draft" {{ status_value == 'draft' ? 'selected' : '' }}>Taslak</option>
                                <option value="active" {{ status_value == 'active' ? 'selected' : '' }}>Aktif</option>
                                <option value="paused" {{ status_value == 'paused' ? 'selected' : '' }}>Duraklatılmış</option>
                                <option value="expired" {{ status_value == 'expired' ? 'selected' : '' }}>Süresi Dolmuş</option>
                            </select>
                        </div>
                        <div>
                            <label for="starts_at" class="form-label">Başlangıç Tarihi</label>
                            <input type="datetime-local" id="starts_at" name="starts_at"
                                   value="{{ ad and ad.startsAt ? ad.startsAt|date('Y-m-d\\TH:i') : '' }}"
                                   class="form-input w-full">
                        </div>
                        <div>
                            <label for="ends_at" class="form-label">Bitiş Tarihi</label>
                            <input type="datetime-local" id="ends_at" name="ends_at"
                                   value="{{ ad and ad.endsAt ? ad.endsAt|date('Y-m-d\\TH:i') : '' }}"
                                   class="form-input w-full">
                        </div>
                        <div>
                            <label class="flex items-center gap-3 cursor-pointer">
                                <input type="checkbox" name="is_pinned" value="1"
                                       {{ ad and ad.isPinned ? 'checked' : '' }}
                                       class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                                <span class="form-label mb-0">Sabitlenmiş</span>
                            </label>
                            <p class="text-xs text-gray-500 mt-1">Sabitlenmiş reklamlar her zaman gösterilir.</p>
                        </div>
                        <div>
                            <label for="display_order" class="form-label">Gösterim Sırası</label>
                            <input type="number" id="display_order" name="display_order"
                                   value="{{ ad ? ad.displayOrder : 0 }}"
                                   class="form-input w-full" min="0">
                            <p class="text-xs text-gray-500 mt-1">Küçük sayı önce gösterilir.</p>
                        </div>
                    </div>
                </div>

                {# ======================== Hedefleme ======================== #}
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Hedefleme</h3>
                    </div>
                    <div class="card-body space-y-4">
                        <div>
                            <label class="form-label">Hedef Kategoriler</label>
                            <p class="text-xs text-gray-500 mb-2">Boş bırakılırsa tüm kategorilerde gösterilir.</p>
                            <div class="max-h-48 overflow-y-auto border border-gray-200 rounded-lg p-3 space-y-2">
                                {% set selected_cats = ad and ad.targetCategories ? ad.targetCategories : [] %}
                                {% for category in categories %}
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" name="target_categories[]" value="{{ category.id }}"
                                               {{ category.id in selected_cats ? 'checked' : '' }}
                                               class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                                        <span class="text-sm text-gray-700">{{ category.title }}</span>
                                    </label>
                                {% else %}
                                    <p class="text-sm text-gray-400">Kategori bulunamadı.</p>
                                {% endfor %}
                            </div>
                        </div>
                        <div>
                            <label for="target_pages" class="form-label">Hedef Sayfalar</label>
                            <textarea id="target_pages" name="target_pages" rows="3"
                                      class="form-input w-full text-sm"
                                      placeholder="anasayfa, haber-detay, kategori">{{ ad and ad.targetPages ? ad.targetPages|join(', ') : '' }}</textarea>
                            <p class="text-xs text-gray-500 mt-1">Virgülle ayırarak sayfa türlerini belirtin.</p>
                        </div>
                    </div>
                </div>

                {# ======================== İstatistikler ======================== #}
                {% if ad %}
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">İstatistikler</h3>
                        </div>
                        <div class="card-body">
                            <div class="grid grid-cols-2 gap-4">
                                <div class="text-center p-3 bg-blue-50 rounded-lg">
                                    <p class="text-2xl font-bold text-blue-700">{{ ad.impressionCount|number_format(0, ',', '.') }}</p>
                                    <p class="text-xs text-blue-600 mt-1">Gösterim</p>
                                </div>
                                <div class="text-center p-3 bg-green-50 rounded-lg">
                                    <p class="text-2xl font-bold text-green-700">{{ ad.clickCount|number_format(0, ',', '.') }}</p>
                                    <p class="text-xs text-green-600 mt-1">Tıklama</p>
                                </div>
                            </div>
                            {% if ad.impressionCount > 0 %}
                                <div class="mt-3 text-center">
                                    <p class="text-sm text-gray-500">
                                        CTR: <span class="font-semibold text-gray-700">{{ ((ad.clickCount / ad.impressionCount) * 100)|number_format(2) }}%</span>
                                    </p>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                {% endif %}

                {# Action Buttons #}
                <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>
                        {{ ad ? 'Güncelle' : 'Kaydet' }}
                    </button>
                    <a href="{{ path('admin_advertisements') }}" class="btn-outline w-full justify-center">
                        <i class="fas fa-arrow-left mr-2"></i> Geri Dön
                    </a>
                </div>
            </div>
        </div>
    </form>

    <script>
        function adForm() {
            return {
                selectedCategory: '{{ ad ? ad.positionCategory : (preselected_category ?? '') }}',
                selectedPosition: '{{ ad ? ad.position : (preselected_position ?? '') }}',
                adType: '{{ ad ? ad.adType : "image" }}',
                positionList: [],
                imagePreview: null,
                videoPreview: null,
                existingImageUrl: '{{ ad and ad.imageUrl ? ad.imageUrl : '' }}',
                dragOver: false,

                positionsByCategory: {
                    'alan_reklam': [
                        { key: 'foto_galeri_akis_reklam', label: 'Foto Galeri Akış Reklam' },
                        { key: 'slayt_arasi', label: 'Slayt Arası' }
                    ],
                    'altsayfa': [
                        { key: 'sayfa_baslangici', label: 'Sayfa Başlangıcı' },
                        { key: 'sayfa_sonu', label: 'Sayfa Sonu' },
                        { key: 'baslik_alti', label: 'Başlık Altı' },
                        { key: 'baslik_ustu', label: 'Başlık Üstü' },
                        { key: 'spot_alti', label: 'Spot Altı' },
                        { key: 'fotograf_alti', label: 'Fotoğraf Altı' },
                        { key: 'ilginizi_cekebilir_alti', label: 'İlginizi Çekebilir Altı' }
                    ],
                    'genel': [
                        { key: 'kategori_alti', label: 'Kategori Altı' },
                        { key: 'kategori_mansetler_alti', label: 'Kategori-Manşetler Altı' },
                        { key: 'acilis_reklami', label: 'Açılış Reklamı' },
                        { key: 'en_ust', label: 'En Üst' }
                    ],
                    'paragraf': [
                        { key: 'paragraf_tekrar_eden', label: 'Paragraf Tekrar Eden' }
                    ],
                    'yan': [
                        { key: 'sidebar_ust', label: 'Sidebar Üst' },
                        { key: 'sidebar_orta', label: 'Sidebar Orta' },
                        { key: 'sidebar_alt', label: 'Sidebar Alt' },
                        { key: 'sidebar_yapiskan', label: 'Sidebar Yapışkan' },
                        { key: 'sol_kenar', label: 'Sol Kenar' },
                        { key: 'sag_kenar', label: 'Sağ Kenar' }
                    ]
                },

                init() {
                    this.updatePositions();
                },

                updatePositions() {
                    if (this.selectedCategory && this.positionsByCategory[this.selectedCategory]) {
                        this.positionList = this.positionsByCategory[this.selectedCategory];
                        // Keep selectedPosition if it exists in the new list
                        const found = this.positionList.find(p => p.key === this.selectedPosition);
                        if (!found) {
                            this.selectedPosition = this.positionList.length > 0 ? '' : '';
                        }
                    } else {
                        this.positionList = [];
                        this.selectedPosition = '';
                    }
                },

                // === Image handling ===
                handleImageSelect(event) {
                    const file = event.target.files[0];
                    if (file) this.previewImage(file);
                },
                handleImageDrop(event) {
                    this.dragOver = false;
                    const file = event.dataTransfer.files[0];
                    if (file && file.type.startsWith('image/')) {
                        // Copy files to the hidden input
                        const dt = new DataTransfer();
                        dt.items.add(file);
                        this.$refs.imageInput.files = dt.files;
                        this.previewImage(file);
                    }
                },
                previewImage(file) {
                    if (file.size > 5 * 1024 * 1024) {
                        alert('Dosya boyutu 5MB\'dan büyük olamaz.');
                        return;
                    }
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        this.imagePreview = e.target.result;
                        this.existingImageUrl = '';
                    };
                    reader.readAsDataURL(file);
                },
                removeImage() {
                    this.imagePreview = null;
                    this.existingImageUrl = '';
                    if (this.$refs.imageInput) this.$refs.imageInput.value = '';
                },

                // === Video handling ===
                handleVideoSelect(event) {
                    const file = event.target.files[0];
                    if (file) this.previewVideo(file);
                },
                handleVideoDrop(event) {
                    this.dragOver = false;
                    const file = event.dataTransfer.files[0];
                    if (file && file.type.startsWith('video/')) {
                        const dt = new DataTransfer();
                        dt.items.add(file);
                        this.$refs.videoInput.files = dt.files;
                        this.previewVideo(file);
                    }
                },
                previewVideo(file) {
                    if (file.size > 50 * 1024 * 1024) {
                        alert('Video dosya boyutu 50MB\'dan büyük olamaz.');
                        return;
                    }
                    const url = URL.createObjectURL(file);
                    this.videoPreview = url;
                },
                removeVideo() {
                    this.videoPreview = null;
                    if (this.$refs.videoInput) this.$refs.videoInput.value = '';
                }
            }
        }
    </script>
{% endblock %}
