<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
     public function up(): void
     {
          Schema::create('customers', function (Blueprint $table) {
               $table->id();

               // ─── Temel İlişkiler ─────────────────────────────────────────
               $table->unsignedBigInteger('agency_id');                        // Hangi acentenin müşterisi
               $table->unsignedBigInteger('user_id')->nullable();              // Sisteme kayıtlı kullanıcı (varsa)

               // ─── Kişisel Bilgiler ─────────────────────────────────────────
               // Not: Şirket kartlarında (customer_type = corporate) ad/soyad kullanılmaz,
               // bunun yerine company_name alanı doldurulur. Bu yüzden nullable.
               $table->string('first_name')->nullable();
               $table->string('last_name')->nullable();
               $table->json('emails')->nullable();
               $table->string('phone', 20)->nullable();
               $table->string('phone_alt', 20)->nullable();                    // İkincil telefon
               $table->date('birth_date')->nullable();
               $table->enum('gender', ['male', 'female', 'other'])->nullable();
               $table->string('national_id', 20)->nullable();                  // TC Kimlik / Pasaport No
               $table->string('passport_number', 20)->nullable();
               $table->date('passport_expiry')->nullable();
               $table->string('nationality', 2)->nullable();                   // ISO 3166 ülke kodu

               // ─── Adres Bilgileri ──────────────────────────────────────────
               $table->text('address')->nullable();
               $table->string('city')->nullable();
               $table->string('district')->nullable();
               $table->string('country', 2)->default('TR');
               $table->string('postal_code', 10)->nullable();

               // ─── Müşteri Tipi & Durumu ────────────────────────────────────
               $table->enum('customer_type', ['individual', 'corporate'])->default('individual');
               $table->enum('status', ['active', 'inactive', 'blocked', 'potential'])->default('active');
               $table->boolean('priority')->default(false);                    // Öncelikli mi?

               // ─── Kurumsal Müşteri Bilgileri (customer_type = corporate) ───
               $table->string('company_name')->nullable();
               $table->string('company_type')->nullable();                     // agency, individual, partnership, limited, joint_stock, tour_operator, restaurant, airline, etc.
               $table->string('company_tax_number')->nullable();
               $table->string('company_tax_office')->nullable();
               $table->string('company_position')->nullable();                 // Şirketteki ünvanı

               // ─── Fatura Bilgileri ─────────────────────────────────────────
               $table->text('billing_address')->nullable();
               $table->string('billing_city')->nullable();
               $table->string('billing_district')->nullable();
               $table->string('billing_tax_number')->nullable();
               $table->string('billing_tax_office')->nullable();
               $table->string('billing_email')->nullable();

               // ─── İletişim Tercihleri ──────────────────────────────────────
               $table->string('preferred_contact_method')->nullable();         // email, phone, whatsapp, sms
               $table->boolean('email_marketing')->default(true);
               $table->boolean('sms_marketing')->default(true);

               // ─── Acente Atama ─────────────────────────────────────────────
               $table->unsignedBigInteger('assigned_agent_id')->nullable();    // Sorumlu satış temsilcisi

               // ─── Rezervasyon İstatistikleri ───────────────────────────────
               $table->date('first_booking_date')->nullable();
               $table->date('last_booking_date')->nullable();
               $table->unsignedInteger('total_bookings')->default(0);
               $table->decimal('total_spent', 12, 2)->default(0);
               $table->decimal('average_booking_value', 10, 2)->default(0);
               $table->decimal('lifetime_value', 12, 2)->default(0);

               // ─── Segmentasyon & Tercihler ─────────────────────────────────
               $table->string('customer_segment')->nullable();                 // regular, frequent, occasional, vip
               $table->json('tags')->nullable();                               // Serbest etiketler
               $table->json('interests')->nullable();                          // İlgi alanları (kültür, macera, deniz vs.)
               $table->json('preferred_destinations')->nullable();             // Tercih edilen destinasyonlar
               $table->json('special_requirements')->nullable();               // Engellilik, diyet, özel ihtiyaç vs.
               $table->text('internal_notes')->nullable();                     // Sadece acente for iç notlar

               // ─── Finansal Bilgiler ────────────────────────────────────────
               $table->decimal('credit_limit', 10, 2)->default(0);
               $table->decimal('current_balance', 10, 2)->default(0);
               $table->integer('payment_term_days')->default(0);               // Ödeme vadesi (gün)
               $table->decimal('default_discount_rate', 5, 2)->default(0);    // Varsayılan indirim oranı (%)
               $table->boolean('eligible_for_promotions')->default(true);

               // ─── Referans & Kaynak ────────────────────────────────────────
               $table->string('referral_source')->nullable();                  // website, social_media, phone, walk_in, referral
               $table->unsignedBigInteger('referred_by_customer_id')->nullable(); // Referans veren müşteri
               $table->unsignedInteger('referral_count')->default(0);          // Getirdiği yeni müşteri sayısı

               // ─── Belgeler ─────────────────────────────────────────────────
               $table->json('documents')->nullable();                          // {type, file, expiry} dizisi

               // ─── Sadakat Programı ─────────────────────────────────────────
               $table->unsignedInteger('loyalty_points')->default(0);
               $table->string('loyalty_tier')->nullable();                     // bronze, silver, gold, platinum

               // ─── Memnuniyet & Risk ────────────────────────────────────────
               $table->decimal('satisfaction_score', 3, 2)->nullable();        // 0.00 – 5.00
               $table->unsignedInteger('feedback_count')->default(0);
               $table->enum('payment_reliability', ['excellent', 'good', 'fair', 'poor'])->nullable();
               $table->unsignedInteger('cancellation_count')->default(0);
               $table->unsignedInteger('complaint_count')->default(0);

               // ─── Kara Liste ───────────────────────────────────────────────
               $table->boolean('blacklisted')->default(false);
               $table->text('blacklist_reason')->nullable();
               $table->timestamp('blacklisted_at')->nullable();
               $table->unsignedBigInteger('blacklisted_by')->nullable();

               // ─── Son İletişim ─────────────────────────────────────────────
               $table->timestamp('last_contact_date')->nullable();
               $table->string('last_contact_type')->nullable();                // call, email, meeting, whatsapp
               $table->unsignedBigInteger('last_contacted_by')->nullable();

               // ─── Audit ────────────────────────────────────────────────────
               $table->unsignedBigInteger('created_by')->nullable();
               $table->unsignedBigInteger('updated_by')->nullable();
               $table->timestamps();
               $table->softDeletes();

               // ─── Foreign Keys ─────────────────────────────────────────────
               $table->foreign('agency_id')->references('id')->on('agencies')->onDelete('cascade');
               $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
               $table->foreign('assigned_agent_id')->references('id')->on('users')->onDelete('set null');
               $table->foreign('referred_by_customer_id')->references('id')->on('customers')->onDelete('set null');
               $table->foreign('blacklisted_by')->references('id')->on('users')->onDelete('set null');
               $table->foreign('last_contacted_by')->references('id')->on('users')->onDelete('set null');
               $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
               $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');

               // ─── Indexes ──────────────────────────────────────────────────
               $table->index(['agency_id', 'status']);
               $table->index(['agency_id', 'customer_type']);
               $table->index(['agency_id', 'priority']);
               $table->index(['agency_id', 'customer_segment']);
               $table->index(['assigned_agent_id']);
               $table->index(['user_id']);
               // JSON sütunlar için doğrudan index bazı DB'lerde (MySQL 5.7 altı gibi) sorun olabilir, 
               // ancak Laravel'in json index desteği mevcuttur.
               $table->index(['emails']);
               $table->index(['phone']);
               $table->index(['loyalty_tier']);
               $table->index(['status', 'priority']);
               $table->index(['last_booking_date']);
               $table->index(['blacklisted']);
               $table->index(['created_at']);

               // ─── Full-text Search ─────────────────────────────────────────
               $table->fullText(['first_name', 'last_name', 'company_name']);

               // ─── Unique Constraints ───────────────────────────────────────
               // Birden fazla e-posta olduğu için basit unique constraint kaldırıldı. 
               // Tekillik kontrolü uygulama katmanında yapılmalıdır.
          });
     }

     public function down(): void
     {
          Schema::dropIfExists('customers');
     }
};
