<?php

namespace App\Http\Controllers\Agency\InternationalTour;

use App\Http\Controllers\Controller;
use App\Models\Definition\City;
use App\Models\Definition\Definition;
use App\Models\InternationalTour\InternationalTour;
use App\Models\Product\ProductCategory;
use App\Models\Agency\Marketplace;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class InternationalTourController extends Controller
{
    use AuthorizesRequests;

    public function index(Request $request)
    {
        $query = InternationalTour::with(['categories', 'departureCity', 'arrivalCity'])
            ->byAgency(Auth::user()->currentAgencyId())
            ->where('is_draft', false); // Taslaklar ayrı "Taslaklar" sayfasında listelenir

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                    ->orWhere('code', 'like', '%' . $request->search . '%')
                    ->orWhere('description', 'like', '%' . $request->search . '%');
            });
        }

        if ($request->filled('status')) {
            switch ($request->status) {
                case 'active':
                    $query->active();
                    break;
                case 'inactive':
                    $query->where('is_active', false);
                    break;
                case 'published':
                    $query->where('is_public', true);
                    break;
                case 'draft':
                    $query->where('is_public', false);
                    break;
            }
        }

        if ($request->filled('category')) {
            $query->whereHas('categories', function ($q) use ($request) {
                $q->where('product_categories.id', $request->category);
            });
        }

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

        $sortBy = $request->get('sort', 'created_at');
        $sortDir = $request->get('dir', 'desc');
        $query->orderBy($sortBy, $sortDir);

        $perPage = (int) $request->input('per_page', 12);
        $perPage = in_array($perPage, [12, 24, 48, 96], true) ? $perPage : 12;
        $tours = $query->paginate($perPage)->withQueryString();

        $productType = \App\Models\Product\ProductType::where('slug', 'yurtdisi-turu')->first();
        $categories = ProductCategory::where('product_type_id', $productType->id)
            ->where('agency_id', Auth::user()->currentAgencyId())
            ->active()
            ->orderBy('sort_order')
            ->get();

        // "Taslaklar" butonundaki sayaç
        $draftCount = InternationalTour::byAgency(Auth::user()->currentAgencyId())->where('is_draft', true)->count();

        return view('agency.products.yurtdisi-turlari.index', compact('tours', 'categories', 'draftCount'));
    }

    public function create()
    {
        $productType = \App\Models\Product\ProductType::where('slug', 'yurtdisi-turu')->first();
        $categories = ProductCategory::where('product_type_id', $productType->id)
            ->where('agency_id', Auth::user()->currentAgencyId())
            ->active()
            ->orderBy('sort_order')
            ->get();

        $cities = City::orderBy('city')->get();

        $marketplaces = Marketplace::with(['languages', 'defaultCurrency'])
            ->where('agency_id', Auth::user()->currentAgencyId())
            ->where('is_active', true)
            ->get();

        return view('agency.products.yurtdisi-turlari.create', compact('categories', 'cities', 'marketplaces'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'required|string',
            'short_description' => 'nullable|string|max:500',
            'tour_type' => 'required|in:domestic,international',
            'departure_city_id' => 'required|exists:cities,id',
            'arrival_city_id' => 'required|exists:cities,id',
            'days' => 'required|integer|min:1',
            'nights' => 'nullable|integer|min:0',
            'min_participants' => 'required|integer|min:1',
            'max_participants' => 'nullable|integer|min:1',
            'categories' => 'nullable|array',
            'categories.*' => 'exists:product_categories,id',
            'marketplaces' => 'required|array|min:1',
            'marketplaces.*' => 'exists:marketplaces,id',
        ]);

        DB::beginTransaction();
        try {
            $data = $request->all();
            $data['agency_id'] = Auth::user()->currentAgencyId();
            $data['slug'] = InternationalTour::generateUniqueSlug($request->name);

            $lastTour = InternationalTour::where('agency_id', auth()->user()->agency_id)->latest()->first();
            if (isset($lastTour))
                $data['code'] = (int)$lastTour->code + 1;
            else
                $data['code'] = 1000;

            $data['duration'] = $request->days;
            if (!$request->filled('nights')) {
                $data['nights'] = max(0, $request->days - 1);
            }

            $productType = \App\Models\Product\ProductType::where('slug', 'yurtdisi-turu')->first();

            $tour = InternationalTour::create($data);

            $uniqueSlug = \App\Models\Product\Product::generateUniqueSlug($request->name);

            $product = \App\Models\Product\Product::create([
                'agency_id' => Auth::user()->currentAgencyId(),
                'product_type_id' => $productType->id,
                'productable_type' => InternationalTour::class,
                'productable_id' => $tour->id,
                'code' => $data['code'],
                'name' => $request->name,
                'slug' => $uniqueSlug,
                'description' => $request->description,
                'is_active' => true,
                'is_bookable' => true,
                'created_by' => auth()->id(),
            ]);

            $tour->update(['product_id' => $product->id]);

            if ($request->filled('categories') && is_array($request->categories)) {
                $product->categories()->attach($request->categories);
            }

            if ($request->filled('marketplaces') && is_array($request->marketplaces)) {
                $product->marketplaces()->attach($request->marketplaces);
            }

            DB::commit();

            return redirect()->route('agency.products.yurtdisi-turlari.general', $tour)
                ->with('success', 'Tur başarıyla oluşturuldu. Şimdi detay bilgileri tamamlayabilirsiniz.');

        } catch (\Exception $e) {
            DB::rollback();
            return back()->withInput()->with('error', 'Tur oluşturulurken bir hata oluştu. ' . $e->getMessage());
        }
    }

    public function show(InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('view', $tour);

        $tour->load([
            'categories',
            'departureCity',
            'arrivalCity',
            'activeTourImages',
            'activeItineraries',
            'tourDates',
            'upcomingDates'
        ]);

        return view('agency.products.yurtdisi-turlari.show', compact('tour'));
    }

    public function quickView(InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('view', $tour);

        $tour->load([
            'categories',
            'departureCity',
            'arrivalCity',
            'activeTourImages',
            'activeItineraries',
            'tourDates.marketplacePrices',
            'upcomingDates',
            'product.marketplaces.languages',
            'product.marketplaces.defaultCurrency',
        ]);

        $cities = City::orderBy('city')->get();
        $allMarketplaces = Marketplace::where('agency_id', Auth::user()->currentAgencyId())->where('is_active', true)->get();

        // General formu için (drawer'da tam düzenleme): kategori ağacı + şablonlar
        $agencyId = Auth::user()->currentAgencyId();
        $yurtdisiTuruType = \App\Models\Product\ProductType::where('slug', 'yurtdisi-turu')->first();
        $categories = ProductCategory::where('product_type_id', $yurtdisiTuruType?->id)
            ->where('agency_id', $agencyId)->active()->orderBy('sort_order')->get();
        $defByType = fn ($typeName) => Definition::byAgency($agencyId)
            ->whereHas('definitionType', fn ($q) => $q->where('name', $typeName))
            ->active()->orderBy('name')->get();
        $cancellationPolicies = $defByType('cancellation_policy');
        $termsConditions = $defByType('terms_conditions');
        $inclusionsTemplates = $defByType('tour_inclusions');
        $exclusionsTemplates = $defByType('tour_exclusions');

        $pricingClasses = Auth::user()->agency->getActiveClasses();

        return view('agency.products.yurtdisi-turlari.quick-view', compact(
            'tour', 'cities', 'allMarketplaces', 'categories', 'pricingClasses',
            'cancellationPolicies', 'termsConditions', 'inclusionsTemplates', 'exclusionsTemplates'
        ))->render();
    }

    public function syncMarketplaces(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $data = $request->validate(['marketplaces' => 'nullable|array', 'marketplaces.*' => 'integer', 'primary_marketplace_id' => 'nullable|integer']);
        if ($tour->product) {
            $ids = array_map('intval', $data['marketplaces'] ?? []);
            $tour->product->marketplaces()->sync($ids);

            // Ana pazar: gönderildiyse onu al, yoksa mevcudu koru; seçili listede değilse ilkine düş
            $primary = $request->has('primary_marketplace_id')
                ? (int) ($data['primary_marketplace_id'] ?? 0)
                : (int) $tour->product->primary_marketplace_id;
            if (!in_array($primary, $ids, true)) {
                $primary = $ids[0] ?? null;
            }
            $tour->product->update(['primary_marketplace_id' => $primary ?: null]);
        }

        return response()->json(['success' => true, 'message' => 'Pazaryerleri güncellendi.']);
    }

    public function updateField(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $request->validate(['field' => 'required|string', 'value' => 'nullable']);
        $field = $request->field;
        $value = $request->value;

        $textFields    = ['name', 'code', 'short_description', 'meta_title', 'meta_description', 'meta_keywords', 'difficulty_description', 'departure_flight_number', 'transportation_notes', 'departure_airports', 'arrival_airports'];
        $htmlFields    = ['description', 'places_to_visit', 'inclusions', 'exclusions', 'cancellation_policy', 'terms_conditions'];
        $intFields     = ['days', 'nights', 'min_participants', 'max_participants', 'min_age', 'max_age', 'child_min_age', 'child_max_age', 'infant_min_age', 'infant_max_age', 'priority', 'booking_deadline_hours', 'cancellation_deadline_hours'];
        $decimalFields = ['online_deposit_percent'];
        $cityFields    = ['departure_city_id', 'arrival_city_id'];
        $boolFields    = ['is_active', 'is_public', 'is_bookable', 'is_featured', 'is_bestseller', 'is_new', 'instant_booking', 'refundable', 'child_friendly', 'infant_allowed', 'auto_guarantee_on_min', 'online_payment_enabled', 'payment_plan_enabled', 'has_transfer_points'];
        $selectFields  = ['tour_type', 'difficulty_level', 'transportation_method'];
        $timeFields    = ['flight_departure_time'];
        $dateFields    = ['published_at', 'expires_at'];
        $csvFields     = ['tags'];

        $allowed = array_merge($textFields, $htmlFields, $intFields, $decimalFields, $cityFields, $boolFields, $selectFields, $timeFields, $dateFields, $csvFields);
        if (!in_array($field, $allowed, true)) {
            return response()->json(['success' => false, 'message' => 'Bu alan düzenlenemez.'], 422);
        }

        if (in_array($field, $boolFields, true)) {
            $value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
        } elseif (in_array($field, $intFields, true) || in_array($field, $cityFields, true)) {
            $value = ($value === '' || $value === null) ? null : (int) $value;
        } elseif (in_array($field, $decimalFields, true)) {
            $value = ($value === '' || $value === null) ? null : (float) $value;
        } elseif (in_array($field, $csvFields, true)) {
            $value = collect(explode(',', (string) $value))->map(fn ($t) => trim($t))->filter()->values()->all();
        } elseif (in_array($field, $dateFields, true) || in_array($field, $timeFields, true)) {
            $value = $value ?: null;
        } elseif (in_array($field, $htmlFields, true)) {
            $value = ($value === '' || $value === null) ? null : $value;
        }

        // Alan güncellemesi + yan etkiler (slug / duration senkron)
        $updateData = [$field => $value];
        if ($field === 'name') {
            $updateData['slug'] = InternationalTour::generateUniqueSlug((string) $value, $tour->id);
        } elseif ($field === 'days') {
            $updateData['duration'] = (int) $value;
            if ((int) ($tour->nights ?? 0) < 1) {
                $updateData['nights'] = max(0, (int) $value - 1);
            }
        }
        $tour->update($updateData);

        // İsim değişince ürün adı/slug senkronu
        if ($field === 'name' && $tour->product_id) {
            $tour->product()->update([
                'name' => $value,
                'slug' => \App\Models\Product\Product::generateUniqueSlug((string) $value, $tour->product_id),
            ]);
        }

        $display = $value;
        if (in_array($field, $boolFields, true)) {
            $display = $value ? 'Evet' : 'Hayır';
        } elseif ($field === 'tour_type') {
            $display = $tour->tour_type_display_name ?? $value;
        } elseif ($field === 'difficulty_level') {
            $display = $tour->difficulty_level_display_name ?? $value;
        } elseif (in_array($field, $cityFields, true)) {
            $city = City::find($value);
            $display = $city ? ($city->city ?? $city->name) : '—';
        } elseif (in_array($field, $csvFields, true)) {
            $display = implode(', ', $value);
        } elseif (in_array($field, $dateFields, true)) {
            $display = $value ? \Carbon\Carbon::parse($value)->format('d.m.Y') : '—';
        } elseif ($field === 'transportation_method') {
            $labels = ['air' => 'Uçak', 'road' => 'Karayolu', 'train' => 'Tren', 'ferry' => 'Feribot', 'other' => 'Diğer'];
            $display = $labels[$value] ?? $value;
        }
        if ($display === null || $display === '') {
            $display = '—';
        }

        return response()->json(['success' => true, 'message' => 'Güncellendi.', 'value' => $value, 'display_value' => $display]);
    }

    public function general(InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $tour->load(['transferPoints', 'product.categories']);

        $productType = \App\Models\Product\ProductType::where('slug', 'yurtdisi-turu')->first();
        $categories = ProductCategory::where('product_type_id', $productType->id)
            ->where('agency_id', Auth::user()->currentAgencyId())
            ->active()
            ->orderBy('sort_order')
            ->get();

        $cities = City::orderBy('city')->get();

        $cancellationPolicies = Definition::byAgency(Auth::user()->currentAgencyId())
            ->whereHas('definitionType', function ($query) {
                $query->where('name', 'cancellation_policy');
            })
            ->active()
            ->orderBy('name')
            ->get();

        $termsConditions = Definition::byAgency(Auth::user()->currentAgencyId())
            ->whereHas('definitionType', function ($query) {
                $query->where('name', 'terms_conditions');
            })
            ->active()
            ->orderBy('name')
            ->get();

        $inclusionsTemplates = Definition::byAgency(Auth::user()->currentAgencyId())
            ->whereHas('definitionType', function ($query) {
                $query->where('name', 'tour_inclusions');
            })
            ->active()
            ->orderBy('name')
            ->get();

        $exclusionsTemplates = Definition::byAgency(Auth::user()->currentAgencyId())
            ->whereHas('definitionType', function ($query) {
                $query->where('name', 'tour_exclusions');
            })
            ->active()
            ->orderBy('name')
            ->get();

        return view('agency.products.yurtdisi-turlari.general', compact('tour', 'categories', 'cities', 'cancellationPolicies', 'termsConditions', 'inclusionsTemplates', 'exclusionsTemplates'));
    }

    public function updateGeneral(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $request->merge([
            'flight_departure_time' => $request->flight_departure_time ?: null,
        ]);

        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'required|string',
            'short_description' => 'nullable|string|max:500',
            'places_to_visit' => 'nullable|string',
            'inclusions' => 'nullable|string',
            'exclusions' => 'nullable|string',
            'terms_conditions' => 'nullable|string',
            'tour_type' => 'required|in:domestic,international',
            'departure_city_id' => 'required|exists:cities,id',
            'arrival_city_id' => 'required|exists:cities,id',
            'days' => 'required|integer|min:1',
            'nights' => 'nullable|integer|min:0',
            'min_participants' => 'required|integer|min:1',
            'max_participants' => 'nullable|integer|min:1',
            'min_age' => 'nullable|integer|min:0',
            'max_age' => 'nullable|integer|min:1',
            'difficulty_level' => 'required|in:easy,moderate,challenging,extreme',
            'difficulty_description' => 'nullable|string',
            'categories' => 'nullable|array',
            'categories.*' => 'exists:product_categories,id',
            'transportation_method' => 'nullable|in:air,road,train,ferry,other',
            'departure_flight_number' => 'nullable|string|max:255',
            'flight_departure_time' => 'nullable|date_format:H:i',
            'has_transfer_points' => 'nullable|boolean',
            'transportation_notes' => 'nullable|string',
            'transfer_points' => 'nullable|array',
            'transfer_points.*.location_name' => 'required_with:transfer_points|string|max:255',
            'transfer_points.*.pickup_time' => 'required_with:transfer_points|date_format:H:i',
            'transfer_points.*.notes' => 'nullable|string',
            'transfer_points.*.sort_order' => 'nullable|integer',
        ]);

        DB::beginTransaction();
        try {
            $data = $request->except(['categories', 'transfer_points']);

            if ($request->name !== $tour->name) {
                $data['slug'] = InternationalTour::generateUniqueSlug($request->name, $tour->id);
            }

            $data['duration'] = $request->days;
            if (!$request->filled('nights')) {
                $data['nights'] = max(0, $request->days - 1);
            }

            $tour->update($data);

            if ($tour->product_id) {
                $productData = [
                    'name' => $request->name,
                    'description' => $request->description,
                ];

                if ($request->name !== $tour->getOriginal('name')) {
                    $productData['slug'] = \App\Models\Product\Product::generateUniqueSlug(
                        $request->name,
                        $tour->product_id
                    );
                }

                $tour->product()->update($productData);

                if ($request->has('categories')) {
                    $tour->product->categories()->sync($request->categories ?? []);
                }
            }

            // Boş dizi = tüm satırlar silinmiş demek; filled() ile elenirse silme DB'ye yansımaz.
            if ($request->boolean('has_transfer_points')) {
                $existingIds = $tour->transferPoints->pluck('id')->toArray();
                $updatedIds = [];

                foreach (($request->input('transfer_points') ?? []) as $pointData) {
                    if (isset($pointData['id']) && in_array($pointData['id'], $existingIds)) {
                        $tour->transferPoints()->where('id', $pointData['id'])->update([
                            'location_name' => $pointData['location_name'],
                            'pickup_time' => $pointData['pickup_time'],
                            'notes' => $pointData['notes'] ?? null,
                            'sort_order' => $pointData['sort_order'] ?? 0,
                        ]);
                        $updatedIds[] = $pointData['id'];
                    } else {
                        $newPoint = $tour->transferPoints()->create([
                            'location_name' => $pointData['location_name'],
                            'pickup_time' => $pointData['pickup_time'],
                            'notes' => $pointData['notes'] ?? null,
                            'sort_order' => $pointData['sort_order'] ?? 0,
                        ]);
                        $updatedIds[] = $newPoint->id;
                    }
                }

                $tour->transferPoints()->whereNotIn('id', $updatedIds)->delete();
            } else {
                $tour->transferPoints()->delete();
            }

            DB::commit();

            if ($request->expectsJson()) {
                return response()->json(['success' => true, 'message' => 'Tur bilgileri başarıyla güncellendi.']);
            }

            return back()->with('success', 'Tur bilgileri başarıyla güncellendi.');

        } catch (\Exception $e) {
            DB::rollback();
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => 'Güncelleme sırasında bir hata oluştu.'], 500);
            }
            return back()->withInput()->with('error', 'Güncelleme sırasında bir hata oluştu.');
        }
    }

    public function settings(InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $marketplaces = auth()->user()->agency->marketplaces()->where('is_active', true)->get();
        return view('agency.products.yurtdisi-turlari.settings', compact('tour', 'marketplaces'));
    }

    public function updateSettings(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $request->validate([
            'has_guide' => 'boolean',
            'child_friendly' => 'boolean',
            'infant_allowed' => 'boolean',
            'instant_booking' => 'boolean',
            'refundable' => 'boolean',
            'is_featured' => 'boolean',
            'is_bestseller' => 'boolean',
            'booking_deadline_hours' => 'required|integer|min:1',
            'cancellation_deadline_hours' => 'required|integer|min:1',
            'cancellation_policy' => 'nullable|string',
            'languages' => 'nullable|array',
            'requirements' => 'nullable|array',
        ]);

        $tour->update($request->all());

        if ($tour->product) {
            $tour->product->marketplaces()->sync($request->input('marketplaces', []));
        }

        if ($request->ajax() || $request->wantsJson()) {
            return response()->json([
                'success' => true,
                'message' => 'Tur ayarları başarıyla güncellendi.'
            ]);
        }

        return back()->with('success', 'Tur ayarları başarıyla güncellendi.');
    }

    public function edit(InternationalTour $yurtdisiTur)
    {
        return redirect()->route('agency.products.yurtdisi-turlari.general', $yurtdisiTur);
    }

    public function destroy(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('delete', $tour);

        if ($tour->tourDates()->where('status', 'in_progress')->exists()) {
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => 'Devam eden turları silemezsiniz.'], 422);
            }
            return back()->with('error', 'Devam eden turları silemezsiniz.');
        }

        DB::beginTransaction();
        try {
            $tour->categories()->detach();
            $tour->tourImages()->delete();
            $tour->itineraries()->delete();
            $tour->tourDates()->delete();

            $tour->delete();

            DB::commit();

            if ($request->expectsJson()) {
                return response()->json(['success' => true, 'message' => 'Tur başarıyla silindi.']);
            }

            return redirect()->route('agency.products.yurtdisi-turlari.index')
                ->with('success', 'Tur başarıyla silindi.');

        } catch (\Exception $e) {
            DB::rollback();
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => 'Tur silinirken bir hata oluştu.'], 500);
            }
            return back()->with('error', 'Tur silinirken bir hata oluştu.');
        }
    }

    public function toggleStatus(InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $tour->update(['is_active' => !$tour->is_active]);

        return response()->json([
            'success' => true,
            'is_active' => $tour->is_active,
            'message' => $tour->is_active ? 'Tur aktif edildi.' : 'Tur pasif edildi.'
        ]);
    }

    public function publish(InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $tour->update([
            'is_public' => !$tour->is_public,
            'published_at' => $tour->is_public ? null : now()
        ]);

        return response()->json([
            'success' => true,
            'is_public' => $tour->is_public,
            'message' => $tour->is_public ? 'Tur yayınlandı.' : 'Tur yayından kaldırıldı.'
        ]);
    }

    public function duplicate(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('view', $tour);

        DB::beginTransaction();
        try {
            $newTour = $tour->replicate([
                'code', 'slug', 'view_count', 'booking_count',
                'rating_average', 'rating_count', 'published_at'
            ]);

            $newTour->name = $tour->name . ' - Kopya';
            $newTour->slug = InternationalTour::generateUniqueSlug($newTour->name);
            $newTour->is_public = false;
            $newTour->published_at = null;

            $lastTour = InternationalTour::where('agency_id', auth()->user()->currentAgencyId())->latest()->first();
            if (isset($lastTour))
                $newTour->code = (int)$lastTour->code + 1;
            else
                $newTour->code = 1000;

            $newTour->save();

            // replicate() product_id'yi de kopyaladığı için kopya tur orijinalin ürününü paylaşır;
            // kategoriler zaten bağlı olduğundan attach() unique(product_id, category_id)'ye takılır.
            $newTour->categories()->syncWithoutDetaching($tour->categories->pluck('id')->all());

            DB::commit();

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => 'Tur başarıyla kopyalandı.',
                    'redirect' => route('agency.products.yurtdisi-turlari.index'),
                ]);
            }

            return redirect()->route('agency.products.yurtdisi-turlari.general', $newTour)
                ->with('success', 'Tur başarıyla kopyalandı.');

        } catch (\Exception $e) {
            DB::rollback();
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => 'Tur kopyalanırken bir hata oluştu.'], 500);
            }
            return back()->with('error', 'Tur kopyalanırken bir hata oluştu.');
        }
    }

    public function bulkDelete(Request $request)
    {
        $request->validate([
            'tours' => 'required|array',
            'tours.*' => 'exists:international_tours,id'
        ]);

        $tours = InternationalTour::byAgency(Auth::user()->currentAgencyId())
            ->whereIn('id', $request->tours)
            ->get();

        $deleted = 0;
        foreach ($tours as $tour) {
            if (!$tour->tourDates()->where('status', 'in_progress')->exists()) {
                $tour->delete();
                $deleted++;
            }
        }

        return response()->json([
            'success' => true,
            'message' => "{$deleted} tur başarıyla silindi."
        ]);
    }

    public function bulkStatus(Request $request)
    {
        $request->validate([
            'tours' => 'required|array',
            'tours.*' => 'exists:international_tours,id',
            'status' => 'required|in:active,inactive'
        ]);

        $isActive = $request->status === 'active';

        InternationalTour::byAgency(Auth::user()->currentAgencyId())
            ->whereIn('id', $request->tours)
            ->update(['is_active' => $isActive]);

        $status = $isActive ? 'aktif' : 'pasif';

        return response()->json([
            'success' => true,
            'message' => "Seçilen turlar {$status} edildi."
        ]);
    }

    public function getCategories()
    {
        $productType = \App\Models\Product\ProductType::where('slug', 'yurtdisi-turu')->first();
        $categories = ProductCategory::where('product_type_id', $productType->id)
            ->where('agency_id', Auth::user()->currentAgencyId())
            ->active()
            ->orderBy('name')
            ->get(['id', 'name', 'parent_id']);

        return response()->json($categories);
    }

    public function getCities()
    {
        $cities = City::orderBy('city')->get(['id', 'city']);

        return response()->json($cities);
    }

    public function search(Request $request)
    {
        $query = $request->get('q');

        $tours = InternationalTour::byAgency(Auth::user()->currentAgencyId())
            ->where('name', 'like', '%' . $query . '%')
            ->orWhere('code', 'like', '%' . $query . '%')
            ->limit(10)
            ->get(['id', 'name', 'code']);

        return response()->json($tours);
    }

    public function seo(InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        return view('agency.products.yurtdisi-turlari.seo', compact('tour'));
    }

    public function updateSeo(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $request->validate([
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
            'meta_keywords' => 'nullable|string',
            'tags' => 'nullable|string',
        ]);

        DB::beginTransaction();
        try {
            $data = $request->only(['meta_title', 'meta_description', 'meta_keywords']);

            if ($request->filled('tags')) {
                $data['tags'] = array_map('trim', explode(',', $request->tags));
            } else {
                $data['tags'] = null;
            }

            $tour->update($data);

            DB::commit();

            if ($request->expectsJson()) {
                return response()->json(['success' => true, 'message' => 'SEO bilgileri başarıyla güncellendi.']);
            }

            return redirect()->route('agency.products.yurtdisi-turlari.seo', $tour)
                ->with('success', 'SEO bilgileri başarıyla güncellendi.');

        } catch (\Exception $e) {
            DB::rollback();
            if ($request->expectsJson()) {
                return response()->json(['success' => false, 'message' => 'SEO güncellenemedi: ' . $e->getMessage()], 500);
            }
            return redirect()->back()
                ->with('error', 'SEO bilgileri güncellenirken bir hata oluştu: ' . $e->getMessage())
                ->withInput();
        }
    }

    /** AJAX — quick-view settings: kademeli ödeme planı aşamalarını kaydet (yalnızca payment_plan) */
    public function updatePaymentPlan(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $stages = $request->input('payment_plan', []);
        $clean = [];
        if (is_array($stages)) {
            foreach ($stages as $s) {
                if (!is_array($s) || ($s['percent'] ?? '') === '' || $s['percent'] === null) {
                    continue;
                }
                $clean[] = [
                    'label' => trim($s['label'] ?? ''),
                    'percent' => (float) $s['percent'],
                    'trigger' => in_array($s['trigger'] ?? '', ['at_booking', 'days_before_departure', 'on_departure']) ? $s['trigger'] : 'at_booking',
                    'offset_days' => isset($s['offset_days']) && $s['offset_days'] !== '' ? (int) $s['offset_days'] : 0,
                ];
            }
        }

        $tour->update(['payment_plan' => $clean]);

        return response()->json(['success' => true, 'message' => 'Ödeme planı güncellendi.']);
    }

    /** AJAX — kademeli fiyatlandırma anahtarı + sınıf kapasitelerini kaydet */
    public function updatePricingClasses(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $request->validate([
            'use_pricing_classes' => 'nullable|boolean',
            'class_capacities' => 'nullable|array',
            'class_capacities.*' => 'nullable|integer|min:0',
        ]);

        $caps = [];
        foreach ((array) $request->input('class_capacities', []) as $classId => $v) {
            $caps[(int) $classId] = max(0, (int) $v);
        }

        $tour->update([
            'use_pricing_classes' => $request->boolean('use_pricing_classes'),
            'class_capacities' => $caps,
        ]);

        return response()->json(['success' => true, 'message' => 'Sınıf ayarları kaydedildi.']);
    }

    /**
     * Transfer noktalarını blok olarak kaydet (inline otomatik kayıt).
     * updateGeneral'daki diff-upsert-delete mantığının bağımsız endpoint'i.
     */
    public function updateTransferPoints(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $request->validate([
            'has_transfer_points' => 'nullable|boolean',
            'transfer_points' => 'nullable|array',
            'transfer_points.*.location_name' => 'required_with:transfer_points|string|max:255',
            'transfer_points.*.pickup_time' => 'required_with:transfer_points|date_format:H:i',
            'transfer_points.*.notes' => 'nullable|string',
            'transfer_points.*.sort_order' => 'nullable|integer',
        ]);

        DB::beginTransaction();
        try {
            $tour->update(['has_transfer_points' => $request->boolean('has_transfer_points')]);

            // Boş dizi = tüm satırlar silinmiş demek; filled() ile elenirse silme DB'ye yansımaz.
            if ($request->boolean('has_transfer_points')) {
                $existingIds = $tour->transferPoints->pluck('id')->toArray();
                $updatedIds = [];

                foreach (($request->input('transfer_points') ?? []) as $pointData) {
                    if (isset($pointData['id']) && in_array($pointData['id'], $existingIds)) {
                        $tour->transferPoints()->where('id', $pointData['id'])->update([
                            'location_name' => $pointData['location_name'],
                            'pickup_time' => $pointData['pickup_time'],
                            'notes' => $pointData['notes'] ?? null,
                            'sort_order' => $pointData['sort_order'] ?? 0,
                        ]);
                        $updatedIds[] = $pointData['id'];
                    } else {
                        $newPoint = $tour->transferPoints()->create([
                            'location_name' => $pointData['location_name'],
                            'pickup_time' => $pointData['pickup_time'],
                            'notes' => $pointData['notes'] ?? null,
                            'sort_order' => $pointData['sort_order'] ?? 0,
                        ]);
                        $updatedIds[] = $newPoint->id;
                    }
                }

                $tour->transferPoints()->whereNotIn('id', $updatedIds)->delete();
            } else {
                $tour->transferPoints()->delete();
            }

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Transfer noktaları güncellendi.']);
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json(['success' => false, 'message' => 'Transfer noktaları güncellenemedi.'], 500);
        }
    }

    /**
     * Kategorileri blok olarak senkronla (inline otomatik kayıt).
     */
    public function updateCategories(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $request->validate([
            'categories' => 'nullable|array',
            'categories.*' => 'exists:product_categories,id',
        ]);

        if (!$tour->product_id) {
            return response()->json(['success' => false, 'message' => 'Ürün bulunamadı.'], 422);
        }

        $tour->product->categories()->sync($request->categories ?? []);
        return response()->json(['success' => true, 'message' => 'Kategoriler güncellendi.']);
    }

    /**
     * Taslağı tamamla / yayına al: is_draft=false + aktifleştir.
     */
    public function publishDraft(Request $request, InternationalTour $yurtdisiTur)
    {
        $tour = $yurtdisiTur;
        $this->authorize('update', $tour);

        $tour->update(['is_draft' => false, 'is_active' => true]);
        if ($tour->product_id) {
            $tour->product()->update(['is_active' => true]);
        }

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'message' => 'Tur taslaktan çıkarıldı ve yayına alındı.']);
        }
        return back()->with('success', 'Tur taslaktan çıkarıldı.');
    }

    /** Ajansın yurtdışı turlarındaki en büyük SAYISAL kodun bir fazlası (metin kodlar sayılmaz). */
    protected function nextCodeBase(int $agencyId): int
    {
        $max = (int) InternationalTour::withTrashed()->where('agency_id', $agencyId)
            ->pluck('code')
            ->filter(fn ($c) => ctype_digit((string) $c))
            ->map(fn ($c) => (int) $c)
            ->max();

        return max($max, 999) + 1;
    }

    /**
     * Taslak turların listesi (ayrı sayfa).
     */
    public function drafts(Request $request)
    {
        $query = InternationalTour::with(['categories', 'departureCity', 'arrivalCity'])
            ->byAgency(Auth::user()->currentAgencyId())
            ->where('is_draft', true);

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                    ->orWhere('code', 'like', '%' . $request->search . '%');
            });
        }

        $perPage = (int) $request->input('per_page', 24);
        $perPage = in_array($perPage, [24, 48, 96], true) ? $perPage : 24;

        $tours = $query->orderBy('created_at', 'desc')->paginate($perPage)->withQueryString();

        return view('agency.products.yurtdisi-turlari.drafts', compact('tours'));
    }

    /**
     * Boş bir Taslak tur + Product oluşturur ve quick-view URL'sini döner.
     * "Yeni" akışı: anında taslak, sonra drawer'da doldurulur.
     */
    public function quickCreate(Request $request)
    {
        $agencyId = Auth::user()->currentAgencyId();
        $firstCity = City::query()->value('id');

        DB::beginTransaction();
        try {
            // Kod: turun kendi sayısal aralığından taban al, ama BENZERSİZLİĞİ products'tan doğrula
            // (products.code global unique — üç tur tipi aynı kod havuzunu paylaşır).
            $code = \App\Models\Product\Product::generateUniqueCode($this->nextCodeBase($agencyId));

            $slug = InternationalTour::generateUniqueSlug('yeni-yurtdisi-turu-' . $code);

            $tour = InternationalTour::create([
                'agency_id' => $agencyId,
                'code' => $code,
                'name' => 'Yeni Yurt Dışı Turu',
                'slug' => $slug,
                'description' => '',
                'tour_type' => 'international',
                'departure_city_id' => $firstCity,
                'arrival_city_id' => $firstCity,
                'days' => 1,
                'nights' => 0,
                'duration' => 1,
                'min_participants' => 1,
                'is_active' => false,
                'is_public' => false,
                'is_bookable' => false,
                'is_draft' => true,
            ]);

            $yurtdisiTuruType = \App\Models\Product\ProductType::where('slug', 'yurtdisi-turu')->first();
            $product = \App\Models\Product\Product::create([
                'agency_id' => $agencyId,
                'product_type_id' => $yurtdisiTuruType?->id,
                'productable_type' => InternationalTour::class,
                'productable_id' => $tour->id,
                'code' => $code,
                'name' => $tour->name,
                'slug' => \App\Models\Product\Product::generateUniqueSlug($tour->name . '-' . $code),
                'description' => '',
                'is_active' => false,
                'is_bookable' => false,
                'created_by' => auth()->id(),
            ]);

            $tour->update(['product_id' => $product->id]);

            DB::commit();

            return response()->json([
                'success' => true,
                'quick_view_url' => route('agency.products.yurtdisi-turlari.quick-view', $tour),
            ]);
        } catch (\Exception $e) {
            DB::rollback();
            return response()->json(['success' => false, 'message' => 'Taslak oluşturulamadı: ' . $e->getMessage()], 500);
        }
    }
}
