<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Carbon\Carbon;
use App\Models\Agency\Agency;
use App\Models\Agency\Marketplace;
use App\Models\Definition\City;
use App\Models\InternationalTour\InternationalTour;
use App\Models\InternationalTour\InternationalTourDate;
use App\Models\Product\Product;
use App\Models\Product\ProductType;

class InternationalTourSeeder extends Seeder
{
    public function run(): void
    {
        $agency = Agency::first();
        if (!$agency)
            return;

        $productType = ProductType::where('code', 'yurtdisi-turu')
            ->orWhere('slug', 'yurtdisi-turu')
            ->first();

        if (!$productType)
            return;

        $istanbul = City::where('city', 'like', '%stanbul%')->first() ?? City::first();

        // ── Ana pazar: acentenin baz para birimli pazaryeri (yoksa oluştur) ──
        // Fiyatlar artık tarih kolonlarında değil, pazaryeri × sınıf matrisinde tutulur.
        $currencies = $agency->getActiveCurrencies();
        $baseCurrency = $currencies->firstWhere('is_base', true) ?? $currencies->first();

        $marketplace = Marketplace::firstOrCreate(
            ['agency_id' => $agency->id, 'slug' => 'turkiye'],
            [
                'name' => 'Türkiye',
                'default_currency_id' => $baseCurrency?->id,
                'is_active' => true,
            ]
        );

        $toursData = [
            [
                'code' => '2000',
                'name' => 'Roma & Floransa Turu (5 Gün 4 Gece)',
                'slug' => 'roma-floransa-turu-5-gun-4-gece',
                'description' => '<p>İtalya\'nın efsanevi şehirlerini keşfedin. Roma\'nın tarihi dokusu ve Floransa\'nın sanatsal zenginlikleriyle dolu bir yolculuk.</p>',
                'short_description' => '5 günlük İtalya kültür turu; Roma ve Floransa.',
                'days' => 5,
                'nights' => 4,
                'max_participants' => 25,
                'min_participants' => 10,
                'departure_city_id' => $istanbul->id,
                'arrival_city_id' => $istanbul->id,
                'tour_type' => 'international',
                'transportation_method' => 'air',
                'is_active' => true,
                'adult_price' => 18500.00,
                'child_price' => 13000.00,
                'infant_price' => 0,
                'currency' => 'TRY',
            ],
        ];

        foreach ($toursData as $data) {
            $tour = InternationalTour::updateOrCreate(
                ['slug' => $data['slug']],
                [
                    'agency_id' => $agency->id,
                    'code' => $data['code'],
                    'name' => $data['name'],
                    'slug' => $data['slug'],
                    'description' => $data['description'],
                    'short_description' => $data['short_description'],
                    'days' => $data['days'],
                    'nights' => $data['nights'],
                    'max_participants' => $data['max_participants'],
                    'min_participants' => $data['min_participants'],
                    'departure_city_id' => $data['departure_city_id'],
                    'arrival_city_id' => $data['arrival_city_id'],
                    'tour_type' => $data['tour_type'],
                    'transportation_method' => $data['transportation_method'],
                    'is_active' => $data['is_active'],
                    'duration' => $data['days'],
                ]
            );

            // Product kaydı
            $product = Product::updateOrCreate(
                ['productable_type' => InternationalTour::class, 'productable_id' => $tour->id],
                [
                    'agency_id' => $agency->id,
                    'product_type_id' => $productType->id,
                    'primary_marketplace_id' => $marketplace->id,
                    'code' => $data['code'],
                    'name' => $data['name'],
                    'slug' => Product::generateUniqueSlug($data['name']),
                    'description' => $data['description'],
                    'base_price' => $data['adult_price'],
                    'currency' => $data['currency'],
                    'is_active' => true,
                    'is_bookable' => true,
                ]
            );

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

            // Ürünü ana pazara bağla
            $product->marketplaces()->syncWithoutDetaching([$marketplace->id]);

            // Tur tarihleri ekle
            InternationalTourDate::where('international_tour_id', $tour->id)->forceDelete();
            $currentDate = Carbon::now()->addDays(10);

            for ($i = 0; $i < 3; $i++) {
                $startDate = $currentDate->copy()->addDays($i * 21);
                $endDate = $startDate->copy()->addDays($data['days'] - 1);

                $tourDate = InternationalTourDate::create([
                    'international_tour_id' => $tour->id,
                    'code' => 'ITD' . date('Ymd') . str_pad($i + 1, 4, '0', STR_PAD_LEFT),
                    'start_date' => $startDate->format('Y-m-d'),
                    'end_date' => $endDate->format('Y-m-d'),
                    'duration_days' => $data['days'],
                    'duration_nights' => $data['nights'],
                    'total_capacity' => $data['max_participants'],
                    'adult_capacity' => $data['max_participants'],
                    'child_capacity' => 5,
                    'infant_capacity' => 2,
                    'room_capacity' => 3,
                    'remaining_capacity' => $data['max_participants'],
                    'child_min_age' => 2,
                    'child_max_age' => 12,
                    'infant_min_age' => 0,
                    'infant_max_age' => 2,
                    'currency' => $data['currency'],
                    'season_type' => 'medium',
                    'min_participants' => 10,
                    'auto_confirm' => true,
                    'status' => 'booking_open',
                    'is_active' => true,
                    'is_bookable' => true,
                    'is_published' => true,
                    'is_confirmed' => true,
                    'guarantee_departure' => true,
                ]);

                // Pazaryeri fiyat matrisi satırı (ana pazar, sınıfsız) — fiyatın tek kaynağı
                $tourDate->marketplacePrices()->create([
                    'marketplace_id' => $marketplace->id,
                    'tour_class_id' => null,
                    'currency' => $data['currency'],
                    'exchange_rate' => $baseCurrency->exchange_rate ?? 1,
                    'adult_price' => $data['adult_price'],
                    'single_supplement' => 4000.00,
                    'child_price_1' => $data['child_price'],
                    'child_price_2' => $data['child_price'],
                    'infant_price' => $data['infant_price'],
                ]);
            }
        }

        $this->command->info('✅ Yurt dışı turları başarıyla eklendi!');
    }
}
