<?php

namespace App\Http\Controllers\Page;

use App\Http\Controllers\Controller;
use App\Models\Agency\Agency;
use App\Models\Tour\Tour;
use Illuminate\Http\Request;

class HomeController extends Controller
{
    public function index(Request $request)
    {
        // Arama filtrelerini al
        $query = Tour::with(['agency', 'coverImage.galleryImage', 'departureCity', 'arrivalCity'])
            ->active()
            ->public()
            ->bookable();

        // Destinasyon araması
        if ($request->filled('destination')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->destination . '%')
                    ->orWhereHas('departureCity', function ($q) use ($request) {
                        $q->where('city', 'like', '%' . $request->destination . '%');
                    })
                    ->orWhereHas('arrivalCity', function ($q) use ($request) {
                        $q->where('city', 'like', '%' . $request->destination . '%');
                    });
            });
        }

        // Tarih filtresi
        if ($request->filled('date')) {
            $query->whereHas('tourDates', function ($q) use ($request) {
                $q->where('start_date', '>=', $request->date)
                    ->where('is_active', true)
                    ->where('is_bookable', true);
            });
        }

        // Bütçe filtresi — fiyat artık pazaryeri matrisinde (tour_date_marketplace_prices)
        if ($request->filled('budget') && $request->budget != '') {
            $budgetRange = explode('-', $request->budget);
            if (count($budgetRange) == 2) {
                $query->whereHas('tourDates', function ($q) use ($budgetRange) {
                    $q->where('is_active', true)
                        ->whereHas('marketplacePrices', fn ($mq) => $mq->whereBetween('adult_price', [$budgetRange[0], $budgetRange[1]]));
                });
            } elseif (strpos($request->budget, '+') !== false) {
                $minPrice = str_replace('+', '', $request->budget);
                $query->whereHas('tourDates', function ($q) use ($minPrice) {
                    $q->where('is_active', true)
                        ->whereHas('marketplacePrices', fn ($mq) => $mq->where('adult_price', '>=', $minPrice));
                });
            }
        }

        // Tur tipi filtresi
        if ($request->filled('tour_type')) {
            $query->where('tour_type', $request->tour_type);
        }

        // Süre filtresi
        if ($request->filled('duration') && $request->duration != '') {
            if ($request->duration == '1') {
                $query->where('days', 1);
            } elseif ($request->duration == '7+') {
                $query->where('days', '>=', 7);
            } else {
                $durationRange = explode('-', $request->duration);
                if (count($durationRange) == 2) {
                    $query->whereBetween('days', [$durationRange[0], $durationRange[1]]);
                }
            }
        }

        // Acente araması
        $agencyQuery = Agency::with(['tours' => function ($q) {
            $q->active()->public();
        }])
            ->active()
            ->approved()
            ->withCount(['tours' => function ($q) {
                $q->active()->public();
            }]);

        if ($request->filled('agency_name')) {
            $agencyQuery->where('name', 'like', '%' . $request->agency_name . '%');
        }

        if ($request->filled('agency_city')) {
            $agencyQuery->where('city', $request->agency_city);
        }

        // Sonuçları getir
        $tours = $query->orderBy('view_count', 'desc')->paginate(12);
        $agencies = $agencyQuery->orderBy('created_at', 'desc')->take(8)->get();
        $featuredTours = Tour::with(['agency', 'coverImage.galleryImage', 'departureCity', 'arrivalCity'])
            ->active()
            ->public()
            ->bookable()
            ->orderBy('view_count', 'desc')
            ->take(6)
            ->get();

        return view('page.home', compact('tours', 'agencies', 'featuredTours'));
    }
}
