<?php

namespace App\Services\Agency;

use App\Models\Agency\Agency;
use App\Models\Agency\AgencyPage;
use App\Models\Agency\AgencyPageSection;
use App\Models\Agency\AgencyTheme;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class AgencyPageService
{
    /**
     * Get or create agency page
     */
    public function getOrCreatePage(Agency $agency): AgencyPage
    {
        if ($agency->agencyPage) {
            return $agency->agencyPage;
        }

        return $this->createDefaultPage($agency);
    }

    /**
     * Create default page with first theme
     */
    public function createDefaultPage(Agency $agency): AgencyPage
    {
        try {
            $defaultTheme = AgencyTheme::where('name', 'default')->first();

            if (!$defaultTheme) {
                throw new \Exception('Varsayılan tema bulunamadı. Lütfen tema seeder\'ını çalıştırın.');
            }

            return DB::transaction(function () use ($agency, $defaultTheme) {
                $page = AgencyPage::create([
                    'agency_id' => $agency->id,
                    'theme_id' => $defaultTheme->id,
                    'meta_title' => $agency->name,
                    'meta_description' => $agency->description,
                    'layout_style' => 'full-width',
                    'is_published' => false,
                    'created_by' => auth()->id(),
                ]);

                // Create default sections
                $this->createDefaultSections($page);

                return $page->load('sections');
            });
        } catch (\Exception $e) {
            \Log::error('AgencyPageService::createDefaultPage - Error: ' . $e->getMessage(), [
                'agency_id' => $agency->id,
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }

    /**
     * Create default sections for new page
     */
    protected function createDefaultSections(AgencyPage $page): void
    {
        $defaultSections = [
            [
                'section_type' => 'hero',
                'title' => 'Macera Sizi Bekliyor',
                'subtitle' => 'En İyi Turları Keşfedin',
                'sort_order' => 1,
                'settings' => [
                    'style' => 'fullscreen',
                    'overlay' => true,
                    'overlay_opacity' => 0.5,
                ],
            ],
            [
                'section_type' => 'about',
                'title' => 'Hakkımızda',
                'subtitle' => 'Kim Olduğumuzu Öğrenin',
                'content' => $page->agency->description,
                'sort_order' => 2,
                'settings' => [
                    'layout' => 'image-left',
                    'show_stats' => true,
                ],
            ],
            [
                'section_type' => 'tours_grid',
                'title' => 'Popüler Turlar',
                'subtitle' => 'En Çok Tercih Edilen Turlarımız',
                'sort_order' => 3,
                'settings' => [
                    'columns' => 3,
                    'limit' => 6,
                    'show_filters' => true,
                    'filter_by' => 'featured',
                ],
            ],
            [
                'section_type' => 'categories',
                'title' => 'Tur Kategorileri',
                'subtitle' => 'İlginizi Çeken Kategoriyi Seçin',
                'sort_order' => 4,
                'settings' => [
                    'style' => 'grid',
                    'columns' => 4,
                    'show_count' => true,
                ],
            ],
            [
                'section_type' => 'contact',
                'title' => 'İletişime Geçin',
                'subtitle' => 'Size Yardımcı Olmaktan Mutluluk Duyarız',
                'sort_order' => 5,
                'settings' => [
                    'show_form' => true,
                    'show_map' => true,
                    'show_info' => true,
                ],
                'data' => [
                    'phone' => $page->agency->contact_phone,
                    'email' => $page->agency->contact_email,
                    'address' => $page->agency->contact_address,
                ],
            ],
        ];

        foreach ($defaultSections as $sectionData) {
            $page->sections()->create(array_merge($sectionData, [
                'is_active' => true,
                'created_by' => auth()->id(),
            ]));
        }
    }

    /**
     * Update page settings
     */
    public function updatePage(AgencyPage $page, array $data): AgencyPage
    {
        return DB::transaction(function () use ($page, $data) {
            // Create revision before update
            $page->createRevision('Manual update');

            $page->update($data);

            return $page->fresh();
        });
    }

    /**
     * Change theme
     */
    public function changeTheme(AgencyPage $page, int $themeId): AgencyPage
    {
        try {
            $theme = AgencyTheme::findOrFail($themeId);

            // Check if theme is active (except default theme which is always available)
            if (!$theme->is_active && $theme->name !== 'default') {
                throw new \Exception('Bu tema henüz aktif değil. Lütfen aktif bir tema seçin.');
            }

            return DB::transaction(function () use ($page, $theme) {
                $page->createRevision('Theme changed to: ' . $theme->display_name);

                $page->update([
                    'theme_id' => $theme->id,
                    'theme_overrides' => [], // Reset overrides
                ]);

                return $page->fresh();
            });
        } catch (\Exception $e) {
            \Log::error('AgencyPageService::changeTheme - Error: ' . $e->getMessage(), [
                'page_id' => $page->id,
                'theme_id' => $themeId,
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }

    /**
     * Update theme overrides
     */
    public function updateThemeSettings(AgencyPage $page, array $settings): AgencyPage
    {
        $overrides = $page->theme_overrides ?? [];

        foreach ($settings as $key => $value) {
            data_set($overrides, $key, $value);
        }

        $page->update(['theme_overrides' => $overrides]);

        return $page->fresh();
    }

    /**
     * Add section
     */
    public function addSection(AgencyPage $page, array $data): AgencyPageSection
    {
        $maxOrder = $page->sections()->max('sort_order') ?? 0;

        return $page->sections()->create(array_merge($data, [
            'sort_order' => $maxOrder + 1,
            'is_active' => true,
            'created_by' => auth()->id(),
        ]));
    }

    /**
     * Update section
     */
    public function updateSection(AgencyPageSection $section, array $data): AgencyPageSection
    {
        $section->update($data);
        return $section->fresh();
    }

    /**
     * Delete section
     */
    public function deleteSection(AgencyPageSection $section): bool
    {
        return $section->delete();
    }

    /**
     * Reorder sections
     */
    public function reorderSections(AgencyPage $page, array $order): void
    {
        DB::transaction(function () use ($order) {
            foreach ($order as $index => $sectionId) {
                AgencyPageSection::where('id', $sectionId)
                    ->update(['sort_order' => $index + 1]);
            }
        });
    }

    /**
     * Duplicate section
     */
    public function duplicateSection(AgencyPageSection $section): AgencyPageSection
    {
        return $section->duplicate();
    }

    /**
     * Toggle section visibility
     */
    public function toggleSection(AgencyPageSection $section): AgencyPageSection
    {
        $section->update(['is_active' => !$section->is_active]);
        return $section->fresh();
    }

    /**
     * Publish page
     */
    public function publish(AgencyPage $page): AgencyPage
    {
        $page->publish();
        return $page->fresh();
    }

    /**
     * Unpublish page
     */
    public function unpublish(AgencyPage $page): AgencyPage
    {
        $page->unpublish();
        return $page->fresh();
    }

    /**
     * Get page preview data
     */
    public function getPreviewData(AgencyPage $page): array
    {
        return [
            'page' => $page->load(['theme', 'agency']),
            'sections' => $page->sections()->active()->ordered()->get(),
            'theme_settings' => $this->getCompiledThemeSettings($page),
        ];
    }

    /**
     * Get published version of the page (from revision)
     */
    public function getPublishedPage(Agency $agency): ?AgencyPage
    {
        $page = $agency->agencyPage;
        if (!$page || !$page->is_published) {
            return null;
        }

        if (!$page->published_revision_id) {
            // Eski sistemden kalma ise mevcut veriyi döndür
            return $page->load(['theme', 'sections' => fn($q) => $q->active()->ordered()]);
        }

        $revision = $page->publishedRevision;
        if (!$revision) {
            return $page->load(['theme', 'sections' => fn($q) => $q->active()->ordered()]);
        }

        // Sayfayı revizyondaki verilerle oluştur (veritabanına kaydetmeden)
        $publishedPage = (new AgencyPage())->forceFill($revision->page_data);
        $publishedPage->id = $page->id; // ID'yi koru
        $publishedPage->exists = true; // Kayıt varmış gibi davran
        $publishedPage->setRelation('theme', $page->theme);
        $publishedPage->setRelation('agency', $agency);

        // Sectionları oluştur
        $sections = collect($revision->sections_data)
            ->filter(fn($s) => ($s['is_active'] ?? true))
            ->sortBy('sort_order')
            ->map(function ($data) {
                // Section modelini doldur
                $section = (new AgencyPageSection())->forceFill($data);
                $section->exists = true;
                return $section;
            });

        // Relation'ı doldur
        $publishedPage->setRelation('sections', $sections);

        return $publishedPage;
    }

    /**
     * Get compiled theme settings (theme defaults + overrides)
     */
    public function getCompiledThemeSettings(AgencyPage $page): array
    {
        $defaults = $page->theme->default_settings;
        $overrides = $page->theme_overrides ?? [];

        return array_replace_recursive($defaults, $overrides);
    }

    /**
     * Upload section image
     */
    public function uploadSectionImage(AgencyPageSection $section, $file, string $key = 'image'): string
    {
        try {
            if (!$file || !$file->isValid()) {
                throw new \Exception('Geçersiz dosya yüklendi.');
            }

            $path = $file->store('agency-pages/' . $section->agency_page_id . '/sections', 'public');

            // Delete old image if exists
            $oldImage = $section->getData($key);
            if ($oldImage && Storage::disk('public')->exists($oldImage)) {
                Storage::disk('public')->delete($oldImage);
            }

            $section->setData($key, $path);

            return $path;
        } catch (\Exception $e) {
            \Log::error('AgencyPageService::uploadSectionImage - Error: ' . $e->getMessage(), [
                'section_id' => $section->id,
                'key' => $key,
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }


    /**
     * Restore from revision
     */
    public function restoreRevision(AgencyPage $page, int $revisionId): AgencyPage
    {
        try {
            $revision = $page->revisions()->findOrFail($revisionId);

            return DB::transaction(function () use ($page, $revision) {
                // Create new revision before restore
                $page->createRevision('Before restore to revision #' . $revision->id);

                // Restore
                $revision->restore();

                return $page->fresh();
            });
        } catch (\Exception $e) {
            \Log::error('AgencyPageService::restoreRevision - Error: ' . $e->getMessage(), [
                'page_id' => $page->id,
                'revision_id' => $revisionId,
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }

    /**
     * Get available section types for theme
     */
    public function getAvailableSectionTypes(AgencyPage $page): array
    {
        $availableSections = $page->theme->available_sections ?? [];
        $sectionDefinitions = $this->getSectionDefinitions();

        // Get agency's active product type codes
        $agencyProductTypeCodes = $page->agency->productTypes()
            ->where('agency_product_types.is_active', true)
            ->pluck('code')
            ->toArray();

        return collect($availableSections)
            ->map(fn($type) => $sectionDefinitions[$type] ?? null)
            ->filter(function ($section) use ($agencyProductTypeCodes) {
                if (!$section) {
                    return false;
                }

                // If section requires specific product types
                if (isset($section['required_product_types'])) {
                    // Check if agency has at least one of the required product types
                    return !empty(array_intersect($section['required_product_types'], $agencyProductTypeCodes));
                }

                // Section has no requirements, always show it
                return true;
            })
            ->values()
            ->toArray();
    }

    /**
     * Section definitions
     */
    protected function getSectionDefinitions(): array
    {
        return [
            'hero' => [
                'type' => 'hero',
                'name' => 'Hero Banner',
                'icon' => 'heroicons-photo',
                'description' => 'Büyük görsel veya video içeren giriş bölümü',
                'category' => 'header',
            ],
            'about' => [
                'type' => 'about',
                'name' => 'Hakkımızda',
                'icon' => 'heroicons-information-circle',
                'description' => 'Şirket tanıtım bölümü',
                'category' => 'content',
            ],
            'features' => [
                'type' => 'features',
                'name' => 'Özellikler',
                'icon' => 'heroicons-star',
                'description' => 'Neden bizi seçmelisiniz kartları',
                'category' => 'content',
            ],
            'services' => [
                'type' => 'services',
                'name' => 'Hizmetler',
                'icon' => 'heroicons-briefcase',
                'description' => 'Sunulan hizmetler listesi',
                'category' => 'content',
            ],
            'tours_grid' => [
                'type' => 'tours_grid',
                'name' => 'Turlar (Grid)',
                'icon' => 'heroicons-view-grid',
                'description' => 'Turları grid düzeninde göster',
                'category' => 'tours',
                'required_product_types' => ['kultur-turu', 'gunubirlik-tur'],
            ],
            'tours_carousel' => [
                'type' => 'tours_carousel',
                'name' => 'Turlar (Carousel)',
                'icon' => 'heroicons-chevron-double-right',
                'description' => 'Turları carousel düzeninde göster',
                'category' => 'tours',
                'required_product_types' => ['kultur-turu', 'gunubirlik-tur'],
            ],
            'tours_list' => [
                'type' => 'tours_list',
                'name' => 'Turlar (Liste)',
                'icon' => 'heroicons-view-list',
                'description' => 'Turları liste düzeninde göster',
                'category' => 'tours',
                'required_product_types' => ['kultur-turu', 'gunubirlik-tur'],
            ],
            'tours_map' => [
                'type' => 'tours_map',
                'name' => 'Turlar (Harita)',
                'icon' => 'heroicons-map',
                'description' => 'Turları harita üzerinde göster',
                'category' => 'tours',
                'required_product_types' => ['kultur-turu', 'gunubirlik-tur'],
            ],
            'tours_masonry' => [
                'type' => 'tours_masonry',
                'name' => 'Turlar (Masonry)',
                'icon' => 'heroicons-template',
                'description' => 'Turları masonry düzeninde göster',
                'category' => 'tours',
                'required_product_types' => ['kultur-turu', 'gunubirlik-tur'],
            ],
            'categories' => [
                'type' => 'categories',
                'name' => 'Kategoriler',
                'icon' => 'heroicons-collection',
                'description' => 'Ürün kategorileri listesi',
                'category' => 'content',
            ],
            'statistics' => [
                'type' => 'statistics',
                'name' => 'İstatistikler',
                'icon' => 'heroicons-chart-bar',
                'description' => 'Sayısal veriler ve istatistikler',
                'category' => 'content',
            ],
            'testimonials' => [
                'type' => 'testimonials',
                'name' => 'Müşteri Yorumları',
                'icon' => 'heroicons-chat-alt-2',
                'description' => 'Müşteri deneyimleri ve yorumları',
                'category' => 'social',
            ],
            'team' => [
                'type' => 'team',
                'name' => 'Ekibimiz',
                'icon' => 'heroicons-users',
                'description' => 'Ekip üyeleri tanıtımı',
                'category' => 'content',
            ],
            'blog' => [
                'type' => 'blog',
                'name' => 'Blog Yazıları',
                'icon' => 'heroicons-newspaper',
                'description' => 'Son blog yazıları',
                'category' => 'content',
            ],
            'gallery' => [
                'type' => 'gallery',
                'name' => 'Galeri',
                'icon' => 'heroicons-photograph',
                'description' => 'Fotoğraf galerisi',
                'category' => 'media',
            ],
            'faq' => [
                'type' => 'faq',
                'name' => 'SSS',
                'icon' => 'heroicons-question-mark-circle',
                'description' => 'Sık sorulan sorular',
                'category' => 'content',
            ],
            'contact' => [
                'type' => 'contact',
                'name' => 'İletişim',
                'icon' => 'heroicons-phone',
                'description' => 'İletişim formu ve bilgileri',
                'category' => 'footer',
            ],
            'newsletter' => [
                'type' => 'newsletter',
                'name' => 'Bülten',
                'icon' => 'heroicons-mail',
                'description' => 'E-posta bülteni kayıt formu',
                'category' => 'footer',
            ],
            'custom_html' => [
                'type' => 'custom_html',
                'name' => 'Özel HTML',
                'icon' => 'heroicons-code',
                'description' => 'Özel HTML/CSS/JS kodu',
                'category' => 'advanced',
            ],
            'tour_search' => [
                'type' => 'tour_search',
                'name' => 'Tur Arama Motoru',
                'icon' => 'heroicons-search',
                'description' => 'Kalkış noktası ve tarih ile tur arama',
                'category' => 'tours',
                'required_product_types' => ['kultur-turu', 'gunubirlik-tur'],
            ],
        ];
    }
}
