<?php

namespace App\Http\Controllers\Page;

use App\Http\Controllers\Controller;
use App\Models\Agency\Agency;
use App\Models\Agency\AgencyPage;
use App\Models\Tour\Tour;
use App\Models\DayTour\DayTour;
use App\Services\Agency\AgencyPageService;
use Illuminate\Http\Request;

class AgencyPageController extends Controller
{
    protected $pageService;

    public function __construct(AgencyPageService $pageService)
    {
        $this->pageService = $pageService;
    }

    public function show(Agency $agency)
    {
        // Acente aktif ve onaylı mı kontrol et
        if (!$agency->is_active || !$agency->is_approved) {
            abort(404);
        }

        // Yayınlanan sayfayı al
        $page = $this->pageService->getPublishedPage($agency);

        // Sayfa yayınlanmamışsa veya yoksa 404 döndür
        if (!$page) {
            abort(404, 'Bu sayfa henüz yayınlanmamış veya aktif değil.');
        }

        $theme = $page->theme;
        $themeSettings = $this->pageService->getCompiledThemeSettings($page);
        $sections = $page->sections; // getPublishedPage zaten aktif ve sıralı sections'ları yükledi

        return view('page.agency.index', compact('agency', 'page', 'theme', 'themeSettings', 'sections'));
    }

    /**
     * Search tours for agency
     */
    public function searchTours(Request $request, Agency $agency)
    {
        // Acente aktif ve onaylı mı kontrol et
        if (!$agency->is_active || !$agency->is_approved) {
            abort(404);
        }

        $productType = $request->input('product_type', 'kultur-turu');
        $departureCityId = $request->input('departure_city_id');
        $query = $request->input('q');
        $date = $request->input('date');

        $results = collect();

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

        // Search Kultur Turlari
        if ($productType === 'kultur-turu' && in_array('kultur-turu', $activeProductTypeCodes)) {
            $toursQuery = Tour::where('agency_id', $agency->id)
                ->active()
                ->public()
                ->bookable();

            if ($departureCityId) {
                $toursQuery->where('departure_city_id', $departureCityId);
            }

            if ($query) {
                $toursQuery->where(function ($q) use ($query) {
                    $q->where('name', 'like', '%' . $query . '%')
                        ->orWhere('short_description', 'like', '%' . $query . '%')
                        ->orWhere('description', 'like', '%' . $query . '%');
                });
            }

            if ($date) {
                $toursQuery->whereHas('tourDates', function ($q) use ($date) {
                    $q->where('start_date', '>=', $date)
                        ->where('is_active', true);
                });
            }

            $results = $toursQuery->with(['coverImage', 'departureCity'])->paginate(12);
        }

        // Search Gunubirlik Turlar
        if ($productType === 'gunubirlik-tur' && in_array('gunubirlik-tur', $activeProductTypeCodes)) {
            $dayToursQuery = DayTour::where('agency_id', $agency->id)
                ->where('is_active', true);

            if ($departureCityId) {
                $dayToursQuery->where('departure_city_id', $departureCityId);
            }

            if ($query) {
                $dayToursQuery->where(function ($q) use ($query) {
                    $q->where('name', 'like', '%' . $query . '%')
                        ->orWhere('short_description', 'like', '%' . $query . '%')
                        ->orWhere('description', 'like', '%' . $query . '%');
                });
            }

            if ($date) {
                $dayToursQuery->whereHas('tourDates', function ($q) use ($date) {
                    $q->where('tour_date', '>=', $date)
                        ->where('is_active', true);
                });
            }

            $results = $dayToursQuery->with(['coverImage', 'departureCity'])->paginate(12);
        }

        // Get published page
        $page = $this->pageService->getPublishedPage($agency);
        if (!$page)
            abort(404);

        $theme = $page->theme;
        $themeSettings = $this->pageService->getCompiledThemeSettings($page);

        // Get departure city name for display
        $departureCityName = null;
        if ($departureCityId) {
            $departureCityName = \App\Models\Definition\City::find($departureCityId)?->name;
        }

        return view('page.agency.search-results', compact(
            'agency',
            'page',
            'theme',
            'themeSettings',
            'results',
            'productType',
            'departureCityId',
            'departureCityName',
            'query',
            'date'
        ));
    }

    /**
     * List tours by product type
     */
    public function listTours(Request $request, Agency $agency, string $type)
    {
        // Validate product type
        if (!in_array($type, ['kultur-turu', 'gunubirlik-tur'])) {
            abort(404);
        }

        // Check agency status
        if (!$agency->is_active || !$agency->is_approved) {
            abort(404);
        }

        // Check if agency has this product type
        $hasProductType = $agency->productTypes()
            ->where('agency_product_types.is_active', true)
            ->where('code', $type)
            ->exists();

        if (!$hasProductType) {
            abort(404);
        }

        // Build query
        $departureCityId = $request->input('departure_city_id');
        $query = $request->input('q');
        $date = $request->input('date');
        $sort = $request->input('sort', 'newest');

        if ($type === 'kultur-turu') {
            $toursQuery = Tour::where('agency_id', $agency->id)
                ->active()
                ->public()
                ->bookable();

            if ($departureCityId) {
                $toursQuery->where('departure_city_id', $departureCityId);
            }

            if ($query) {
                $toursQuery->where(function ($q) use ($query) {
                    $q->where('name', 'like', '%' . $query . '%')
                        ->orWhere('short_description', 'like', '%' . $query . '%')
                        ->orWhere('description', 'like', '%' . $query . '%');
                });
            }

            if ($date) {
                $toursQuery->whereHas('tourDates', function ($q) use ($date) {
                    $q->where('start_date', '>=', $date)
                        ->where('is_active', true);
                });
            }

            // Sorting
            switch ($sort) {
                case 'price_asc':
                    $toursQuery->orderByRaw('(SELECT MIN(adult_price) FROM cultural_tour_pricings WHERE cultural_tour_id = cultural_tours.id AND is_active = 1) ASC');
                    break;
                case 'price_desc':
                    $toursQuery->orderByRaw('(SELECT MIN(adult_price) FROM cultural_tour_pricings WHERE cultural_tour_id = cultural_tours.id AND is_active = 1) DESC');
                    break;
                case 'popular':
                    $toursQuery->orderBy('booking_count', 'desc');
                    break;
                default:
                    $toursQuery->orderBy('created_at', 'desc');
            }

            $tours = $toursQuery->with(['coverImage', 'departureCity', 'defaultPricing', 'upcomingDates'])->paginate(12);
        } else {
            $toursQuery = DayTour::where('agency_id', $agency->id)
                ->where('is_active', true)
                ->where('is_public', true);

            if ($departureCityId) {
                $toursQuery->where('departure_city_id', $departureCityId);
            }

            if ($query) {
                $toursQuery->where(function ($q) use ($query) {
                    $q->where('name', 'like', '%' . $query . '%')
                        ->orWhere('short_description', 'like', '%' . $query . '%')
                        ->orWhere('description', 'like', '%' . $query . '%');
                });
            }

            if ($date) {
                $toursQuery->whereHas('tourDates', function ($q) use ($date) {
                    $q->where('tour_date', '>=', $date)
                        ->where('is_active', true);
                });
            }

            // Sorting
            switch ($sort) {
                case 'price_asc':
                    $toursQuery->orderBy('adult_price', 'asc');
                    break;
                case 'price_desc':
                    $toursQuery->orderBy('adult_price', 'desc');
                    break;
                case 'popular':
                    $toursQuery->orderBy('booking_count', 'desc');
                    break;
                default:
                    $toursQuery->orderBy('created_at', 'desc');
            }

            $tours = $toursQuery->with(['coverImage', 'departureCity', 'upcomingDates'])->paginate(12);
        }

        // Get published page
        $page = $this->pageService->getPublishedPage($agency);
        if (!$page)
            abort(404);

        $theme = $page->theme;
        $themeSettings = $this->pageService->getCompiledThemeSettings($page);

        // SEO Overrides for Tour List
        $productType = $type;
        $page->meta_title = ($productType === 'kultur-turu' ? 'Kültür Turları' : 'Günübirlik Turlar');
        $page->meta_description = $agency->name . ' - ' . $page->meta_title;

        $viewName = $productType === 'kultur-turu' ? 'tours.cultural.index' : 'tours.day.index';

        return view('page.agency.themes.' . ($theme->name ?? 'default') . '.' . $viewName, compact(
            'agency',
            'page',
            'theme',
            'themeSettings',
            'tours',
            'productType'
        ));
    }

    /**
     * Show tour detail
     */
    public function showTour(Request $request, Agency $agency, string $type, string $slug)
    {
        // Validate product type
        if (!in_array($type, ['kultur-turu', 'gunubirlik-tur'])) {
            abort(404);
        }

        // Check agency status
        if (!$agency->is_active || !$agency->is_approved) {
            abort(404);
        }

        // Find tour
        if ($type === 'kultur-turu') {
            $tour = Tour::where('agency_id', $agency->id)
                ->where('slug', $slug)
                ->active()
                ->public()
                ->with([
                    'coverImage',
                    'galleryImages',
                    'departureCity',
                    'arrivalCity',
                    'activeItineraries',
                    'activePricings',
                    'categories',
                    'transferPoints'
                ])
                ->firstOrFail();
        } else {
            $tour = DayTour::where('agency_id', $agency->id)
                ->where('slug', $slug)
                ->where('is_active', true)
                ->where('is_public', true)
                ->with([
                    'coverImage',
                    'galleryImages',
                    'departureCity',
                    'arrivalCity',
                    'activeItineraries',
                    'categories'
                ])
                ->firstOrFail();
        }

        // Increment view count
        $tour->increment('view_count');

        // Paginate dates
        $upcomingDates = $tour->upcomingDates()->paginate(10);

        // Get published page
        $page = $this->pageService->getPublishedPage($agency);
        if (!$page)
            abort(404);

        $theme = $page->theme;
        $themeSettings = $this->pageService->getCompiledThemeSettings($page);

        // SEO Overrides for Tour Detail
        $page->meta_title = $tour->meta_title ?: $tour->name;
        if ($tour->meta_description) {
            $page->meta_description = $tour->meta_description;
        } else {
            $desc = $tour->short_description ?: $tour->description;
            $page->meta_description = \Illuminate\Support\Str::limit(strip_tags($desc), 155);
        }
        if ($tour->meta_keywords) {
            $page->meta_keywords = $tour->meta_keywords;
        }

        $productType = $type;

        $viewName = $productType === 'kultur-turu' ? 'tours.cultural.show' : 'tours.day.show';

        return view('page.agency.themes.' . ($theme->name ?? 'default') . '.' . $viewName, compact(
            'agency',
            'page',
            'theme',
            'themeSettings',
            'tour',
            'productType',
            'upcomingDates'
        ));
    }
}
