<?php

namespace App\Models;

use App\Models\Agency\Agency;
use App\Models\Customer\Customer;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasFactory, Notifiable, HasRoles, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'email',
        'password',
        'phone',
        'national_id',
        'avatar',
        'birth_date',
        'gender',
        'address',
        'city',
        'country',
        'postal_code',
        'language',
        'timezone',
        'preferences',
        'is_active',
        'is_verified',
        'email_notifications',
        'sms_notifications',
        'created_by',
        'updated_by',
    ];

    /**
     * The attributes that should be hidden for serialization.
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_secret',
        'two_factor_recovery_codes',
    ];

    /**
     * Get the attributes that should be cast.
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'birth_date' => 'date',
            'hired_at' => 'date',
            'last_login_at' => 'datetime',
            'password_changed_at' => 'datetime',
            'preferences' => 'array',
            'two_factor_recovery_codes' => 'array',
            'is_active' => 'boolean',
            'is_verified' => 'boolean',
            'email_notifications' => 'boolean',
            'sms_notifications' => 'boolean',
            'two_factor_enabled' => 'boolean',
        ];
    }

    /**
     * Get the user's full name.
     */
    public function getFullNameAttribute(): string
    {
        return "{$this->first_name} {$this->last_name}";
    }

    /**
     * Get the user's initials.
     */
    public function getInitialsAttribute(): string
    {
        $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');
    }

    /**
     * Check if user belongs to an agency.
     */
    public function hasAgency(): bool
    {
        return $this->agencyStaff()->exists();
    }

    /**
     * Check if user belongs to a specific agency.
     */
    public function belongsToAgency(int $agencyId): bool
    {
        return $this->agencyStaff()->where('agency_id', $agencyId)->exists();
    }

    /**
     * Get the current active agency ID from Spatie Team context.
     */
    public function currentAgencyId(): ?int
    {
        return getPermissionsTeamId();
    }

    /**
     * Get the current active agency.
     */
    public function getAgencyAttribute(): ?Agency
    {
        $agencyId = $this->currentAgencyId();
        return $agencyId ? Agency::find($agencyId) : null;
    }

    /**
     * Get the current active agency ID (alias for currentAgencyId).
     */
    public function getAgencyIdAttribute(): ?int
    {
        return $this->currentAgencyId();
    }

    /**
     * Check if user is super admin.
     */
    public function isSuperAdmin(): bool
    {
        return $this->hasRole('super-admin');
    }

    /**
     * Check if user is agency owner in any agency.
     */
    public function isAgencyOwner(?int $agencyId = null): bool
    {
        if ($agencyId) {
            return $this->agencyStaff()->where('agency_id', $agencyId)->where('is_agency_owner', true)->exists();
        }
        return $this->agencyStaff()->where('is_agency_owner', true)->exists();
    }

    /**
     * Get the employment records (staff) for this user.
     */
    public function agencyStaff()
    {
        return $this->hasMany(\App\Models\Agency\AgencyStaff::class);
    }

    /**
     * Get the agencies the user belongs to.
     */
    public function agencies()
    {
        return $this->hasManyThrough(Agency::class, \App\Models\Agency\AgencyStaff::class, 'user_id', 'id', 'id', 'agency_id');
    }

    /**
     * Bu kullanıcıya bağlı müşteri profili (user sisteme kayıtlı bir müşteriyse).
     */
    public function customerProfile()
    {
        return $this->hasOne(Customer::class, 'user_id');
    }

    /**
     * Bu kullanıcıya (sales agent) atanmış müşteriler.
     */
    public function assignedCustomers()
    {
        return $this->hasMany(Customer::class, 'assigned_agent_id');
    }

    /**
     * Get the user who created this user.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the user who last updated this user.
     */
    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * Scope to filter active users.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to filter verified users.
     */
    public function scopeVerified($query)
    {
        return $query->where('is_verified', true);
    }

    /**
     * Scope to filter agency owners (not direct anymore, but keep for compatibility if needed or remove)
     */
    public function scopeAgencyOwners($query)
    {
        return $query->whereHas('agencyStaff', function($q) {
            $q->where('is_agency_owner', true);
        });
    }

    /**
     * Scope to filter users by agency.
     */
    public function scopeByAgency($query, $agencyId)
    {
        return $query->whereHas('agencyStaff', function ($q) use ($agencyId) {
            $q->where('agency_id', $agencyId);
        });
    }

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

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

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