<?php

namespace App\Models\Supplier;

use App\Models\Agency\Agency;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Supplier extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'suppliers';

    protected $fillable = [
        'agency_id',
        'type',
        'supplier_type',
        'first_name',
        'last_name',
        'company_name',
        'company_tax_number',
        'company_tax_office',
        'billing_address',
        'billing_city',
        'billing_district',
        'billing_tax_number',
        'billing_tax_office',
        'billing_email',
        'emails',
        'phones',
        'phone',
        'address',
        'city',
        'district',
        'country',
        'postal_code',
        'notes',
        'status',
        'created_by',
        'updated_by',
    ];

    protected function casts(): array
    {
        return [
            'emails' => 'array',
            'phones' => 'array',
        ];
    }

    // Relationships
    public function agency()
    {
        return $this->belongsTo(Agency::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function priceLists()
    {
        return $this->hasMany(SupplierPriceList::class);
    }

    public function activities()
    {
        return $this->hasMany(SupplierActivity::class);
    }

    public function responsibles()
    {
        return $this->hasMany(SupplierResponsible::class, 'supplier_id');
    }

    public function factSheet()
    {
        return $this->hasOne(SupplierHotelFactSheet::class, 'supplier_id');
    }

    /** Bu tedarikçiye bağlı kaynaklar (kaynak yönetimi) */
    public function resources()
    {
        return $this->hasMany(\App\Models\Resource::class, 'supplier_id');
    }

    /** Çoklu hizmet alanı (tip) kayıtları — pivot. */
    public function serviceTypes()
    {
        return $this->hasMany(SupplierServiceType::class, 'supplier_id');
    }

    /** Tedarikçinin tüm tip kodları (pivot boşsa birincil tipe düşer). */
    public function getTypeCodesAttribute(): array
    {
        $codes = $this->relationLoaded('serviceTypes')
            ? $this->serviceTypes->pluck('supplier_type')->all()
            : $this->serviceTypes()->pluck('supplier_type')->all();

        if (empty($codes) && $this->supplier_type) {
            $codes = [$this->supplier_type];
        }

        return array_values(array_unique($codes));
    }

    /** Tip kodlarının Türkçe etiketleri. */
    public function getTypeLabelsAttribute(): array
    {
        $map = self::supplierTypes();

        return array_map(fn ($c) => $map[$c] ?? ucfirst($c), $this->type_codes);
    }

    /**
     * Tipleri senkronla: geçerli kodlar pivota yazılır; birincil `supplier_type`
     * ilk seçilen olur (geriye uyum — index filtresi/rozet bunu kullanır).
     */
    public function syncTypes(array $codes): void
    {
        $valid = array_values(array_unique(array_filter($codes, fn ($c) => isset(self::supplierTypes()[$c]))));

        if (empty($valid)) {
            return; // en az bir tip korunur
        }

        // Birincil tip = ilk seçilen (yoksa mevcut korunur)
        if ($this->supplier_type !== $valid[0]) {
            $this->supplier_type = $valid[0];
            $this->saveQuietly();
        }

        $this->serviceTypes()->whereNotIn('supplier_type', $valid)->delete();
        $existing = $this->serviceTypes()->pluck('supplier_type')->all();
        foreach (array_diff($valid, $existing) as $code) {
            $this->serviceTypes()->create(['supplier_type' => $code]);
        }
    }

    // Accessors & Mutators
    public function getResponsiblePersonNameAttribute()
    {
        return $this->responsibles->first()?->full_name;
    }

    public function getResponsiblePersonFirstNameAttribute()
    {
        return $this->responsibles->first()?->first_name;
    }

    public function getResponsiblePersonLastNameAttribute()
    {
        return $this->responsibles->first()?->last_name;
    }

    public function getResponsiblePersonGenderAttribute()
    {
        return $this->responsibles->first()?->gender;
    }

    public function getResponsiblePersonPhoneAttribute()
    {
        return $this->responsibles->first()?->phone;
    }

    public function getResponsiblePersonEmailAttribute()
    {
        return $this->responsibles->first()?->email;
    }

    public function getFullNameAttribute(): string
    {
        if ($this->type === 'corporate') {
            return $this->company_name ?? '';
        }
        return trim(($this->first_name ?? '') . ' ' . ($this->last_name ?? ''));
    }

    public function getInitialsAttribute(): string
    {
        if ($this->type === 'corporate') {
            return mb_strtoupper(mb_substr($this->company_name ?? '', 0, 2, 'UTF-8'), 'UTF-8');
        }
        $first = mb_substr($this->first_name ?? '', 0, 1, 'UTF-8');
        $last = mb_substr($this->last_name ?? '', 0, 1, 'UTF-8');
        return mb_strtoupper($first . $last, 'UTF-8');
    }

    public function getStatusLabelAttribute(): string
    {
        return [
            'active' => 'Aktif',
            'inactive' => 'Pasif',
            'blocked' => 'Engellenmiş',
            'potential' => 'Potansiyel',
        ][$this->status] ?? ucfirst($this->status);
    }

    public static function supplierTypes(): array
    {
        return [
            'hotel' => 'Otel',
            'transportation' => 'Taşıma Firması',
            'restaurant' => 'Restoran / Lokanta / Mekan',
            'insurance' => 'Sigorta Şirketi',
            'visa' => 'Vize Danışmanı',
            'airline' => 'Havayolu Firması',
        ];
    }

    public function getSupplierTypeLabelAttribute(): string
    {
        return self::supplierTypes()[$this->supplier_type] ?? ucfirst($this->supplier_type);
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeByAgency($query, int $agencyId)
    {
        return $query->where('agency_id', $agencyId);
    }

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (Supplier $supplier) {
            if (auth()->check()) {
                $supplier->created_by = auth()->id();
            }
        });

        static::updating(function (Supplier $supplier) {
            if (auth()->check()) {
                $supplier->updated_by = auth()->id();
            }
        });
    }
}
