<?php

namespace Database\Seeders;

use App\Models\Sale\Sale;
use App\Models\Customer\Customer;
use App\Models\Product\Product;
use App\Models\Product\ProductType;
use App\Models\Agency\Agency;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Illuminate\Support\Str;

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

          $customers = Customer::where('agency_id', $agency->id)->get();
          if ($customers->isEmpty())
               return;

          // Rastgele 5-10 satış oluştur
          $saleCount = rand(5, 10);

          for ($i = 0; $i < $saleCount; $i++) {
               $customer = $customers->random();

               // Rastgele bir ürün seç
               $product = Product::where('agency_id', $agency->id)->inRandomOrder()->first();
               if (!$product)
                    continue;

               $productType = ProductType::find($product->product_type_id);

               $date = Carbon::now()->addDays(rand(-30, 30));
               $adults = rand(1, 3);
               $children = rand(0, 2);

               $basePrice = (float) ($product->base_price ?? 1000);
               $subtotal = ($basePrice * $adults) + (($basePrice * 0.7) * $children);
               $discount = rand(0, 100);
               $total = $subtotal - $discount;
               $paid = rand(0, 1) ? $total : (rand(0, 1) ? $total / 2 : 0);

               // Rastgele bir başlık oluştur
               $titles = ['Yaz Tatili Planı', 'Balayı Paketi', 'Haftasonu Kaçamağı', 'Kültür Turu Kaydı', 'Aile Gezisi', 'Erken Rezervasyon Fırsatı'];
               $title = $titles[array_rand($titles)] . ' - ' . $customer->last_name;

               $sale = Sale::create([
                    'agency_id' => $agency->id,
                    'customer_id' => $customer->id,
                    'product_type_id' => $product->product_type_id,
                    'reservable_type' => $product->productable_type,
                    'reservable_id' => $product->productable_id,
                    'product_id' => $product->id,
                    'sale_code' => 'SAL-' . strtoupper(Str::random(6)) . '-' . rand(100, 999),
                    'title' => $title,
                    'start_date' => $date,
                    'end_date' => $date->copy()->addDays(rand(1, 5)),
                    'status' => $this->getRandomStatus(),
                    'payment_status' => $paid == $total ? 'paid' : ($paid > 0 ? 'partial' : 'unpaid'),
                    'adult_count' => $adults,
                    'child_count' => $children,
                    'infant_count' => 0,
                    'unit_price' => $basePrice,
                    'subtotal' => $subtotal,
                    'total_amount' => $total,
                    'paid_amount' => $paid,
                    'remaining_amount' => $total - $paid,
                    'currency' => 'TRY',
                    'created_at' => Carbon::now()->subDays(rand(1, 10)),
               ]);

               // ─── 1. SATIŞ KALEMLERİ OLUŞTUR ──────────────────────────────
               // Her satış için en az bir ana ürün kalemi ekleyelim
               $mainQty = $adults + $children;
               $mainTaxRate = 20.0;
               $mainSubtotal = $mainQty * $basePrice;
               $mainTaxAmount = $mainSubtotal * ($mainTaxRate / 100);
               $mainTotalPrice = $mainSubtotal + $mainTaxAmount;

               $sale->items()->create([
                    'product_id' => $product->id,
                    'product_type_id' => $product->product_type_id,
                    'name' => $product->name . ' (Ana Hizmet)',
                    'quantity' => $mainQty,
                    'unit_price' => $basePrice,
                    'tax_rate' => $mainTaxRate,
                    'tax_amount' => $mainTaxAmount,
                    'total_price' => $mainTotalPrice,
                    'currency' => 'TRY'
               ]);

               // Rastgele ek hizmetler ekleyelim (Opsiyonel)
               if (rand(0, 1)) {
                    $extras = [
                         ['name' => 'Havalimanı Transferi', 'price' => 1500],
                         ['name' => 'Ekstra Müze Kartı', 'price' => 500],
                         ['name' => 'Sigorta Paketi', 'price' => 750],
                         ['name' => 'Şehir Turu', 'price' => 1200]
                    ];
                    $extra = $extras[array_rand($extras)];
                    $extraQty = 1;
                    $extraTaxRate = 20.0;
                    $extraSubtotal = $extraQty * $extra['price'];
                    $extraTaxAmount = $extraSubtotal * ($extraTaxRate / 100);
                    $extraTotalPrice = $extraSubtotal + $extraTaxAmount;

                    $sale->items()->create([
                         'name' => $extra['name'],
                         'quantity' => $extraQty,
                         'unit_price' => $extra['price'],
                         'tax_rate' => $extraTaxRate,
                         'tax_amount' => $extraTaxAmount,
                         'total_price' => $extraTotalPrice,
                         'currency' => 'TRY'
                    ]);
               }

               // Toplam tutarı kalemlere göre güncelle
               $sale->calculateTotals();

               // ─── 2. SATIŞ AKTİVİTELERİ OLUŞTUR ────────────────────────────
               $performerId = \App\Models\User::byAgency($agency->id)->first()?->id;

               // İlk oluşturma aktivitesi
               $sale->activities()->create([
                    'agency_id' => $agency->id,
                    'performed_by' => $performerId,
                    'activity_type' => 'status_change',
                    'subject' => 'Satış Oluşturuldu',
                    'description' => 'Satış kaydı potansiyel olarak sisteme girildi.',
                    'created_at' => $sale->created_at
               ]);

               // Eğer durumu potansiyelden farklıysa bir geçiş logu daha ekleyelim
               if ($sale->status !== 'potential') {
                    $sale->activities()->create([
                         'agency_id' => $agency->id,
                         'performed_by' => $performerId,
                         'activity_type' => 'status_change',
                         'subject' => 'Durum Güncellendi',
                         'description' => "Satış aşaması '" . $sale->status_label . "' olarak güncellendi.",
                         'created_at' => $sale->created_at->addHours(rand(1, 24))
                    ]);
               }

               // ─── YOLCULARI İLİŞKİLENDİR ───
               $customerPassengers = \App\Models\CustomerPassenger::where('customer_id', $customer->id)->get();
               $totalNeeded = $adults + $children;

               if ($customerPassengers->count() < $totalNeeded) {
                    // Eğer müşterinin yeterli yolcusu yoksa, eksik kadar oluştur
                    $faker = \Faker\Factory::create('tr_TR');
                    for ($j = $customerPassengers->count(); $j < $totalNeeded; $j++) {
                         \App\Models\CustomerPassenger::create([
                              'customer_id' => $customer->id,
                              'first_name' => $faker->firstName,
                              'last_name' => $customer->last_name,
                              'gender' => $faker->randomElement(['male', 'female']),
                              'birth_date' => $faker->dateTimeBetween('-40 years', '-5 years')->format('Y-m-d'),
                              'relationship' => 'Diğer',
                         ]);
                    }
                    $customerPassengers = \App\Models\CustomerPassenger::where('customer_id', $customer->id)->get();
               }

               $pList = $customerPassengers->take($totalNeeded);
               foreach ($pList as $idx => $p) {
                    $sale->passengers()->attach($p->id, [
                         'room_number' => $i % 2 == 0 ? 'Oda ' . rand(101, 305) : null,
                         'seat_number' => rand(1, 45),
                         'special_request' => $idx == 0 ? 'Vejetaryen yemek' : null,
                    ]);
               }
          }

          $this->command->info($saleCount . ' adet Satış başarıyla eklendi!');
     }

     private function getRandomStatus()
     {
          $statuses = [
               'potential', 
               'offer_sent', 
               'revised', 
               'confirmed', 
               'in_progress', 
               'completed', 
               'cancelled', 
               'refunded'
          ];
          // CRM akışına uygun ağırlıklı rastgelelik
          $rand = rand(1, 100);
          if ($rand <= 20) return 'potential';
          if ($rand <= 45) return 'offer_sent';
          if ($rand <= 55) return 'revised';
          if ($rand <= 75) return 'confirmed';
          if ($rand <= 85) return 'in_progress';
          if ($rand <= 95) return 'completed';
          return 'cancelled';
     }
}
