<?php

namespace App\Models;

use App\Traits\OrgRelated;
use Archilex\AdvancedTables\Concerns\HasViews;
use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Models\Contracts\HasTenants;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Collection;
use Spatie\Activitylog\Traits\CausesActivity;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements FilamentUser, HasTenants
{
    /** @use HasFactory<UserFactory> */
    use CausesActivity, HasFactory, HasRoles, HasViews, Notifiable, OrgRelated;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'phone',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    public function orgs(): BelongsToMany
    {
        return $this->belongsToMany(Org::class)->withPivot('department_id')->withTimestamps();
    }

    /**
     * Get the department for a specific organization.
     */
    public function getDepartmentInOrg(Org $org): ?Department
    {
        $pivot = $this->orgs()->where('org_id', $org->id)->first()?->pivot;

        return $pivot && $pivot->department_id
            ? Department::find($pivot->department_id)
            : null;
    }

    /**
     * Set the department for a user in a specific organization.
     */
    public function setDepartmentInOrg(Org $org, ?Department $department = null): void
    {
        $this->orgs()->updateExistingPivot($org->id, [
            'department_id' => $department?->id,
        ]);
    }

    public function getTenants(Panel $panel): Collection
    {
        return $this->orgs;
    }

    public function canAccessTenant(Model $org): bool
    {
        return $this->orgs()->whereKey($org)->exists();
    }

    public function canAccessPanel(Panel $panel): bool
    {
        return true;
    }

    /**
     * Get the performance cards assigned to this user.
     */
    public function assignedPerformanceCards(): BelongsToMany
    {
        return $this->belongsToMany(PerformanceCard::class, 'performance_card_user', 'user_id', 'performance_card_id');
    }

    /**
     * Get the association for this user in a specific organization.
     */
    public function getAssociationInOrg(Org $org): ?Association
    {
        return $this->associations()->where('user_association.org_id', $org->id)->first();
    }

    /**
     * Check if user has an association in a specific organization.
     */
    public function hasAssociationInOrg(Org $org): bool
    {
        return $this->associations()->where('user_association.org_id', $org->id)->exists();
    }

    /**
     * Set the association for a user in a specific organization.
     */
    public function setAssociationInOrg(Org $org, ?Association $association = null): void
    {
        // Remove existing association in this org
        $this->associations()->wherePivot('org_id', $org->id)->detach();

        // Add new association if provided
        if ($association) {
            $this->associations()->attach($association->id, ['org_id' => $org->id]);
        }
    }

    /**
     * Get all associations for this user across all organizations.
     */
    public function associations(): BelongsToMany
    {
        return $this->belongsToMany(Association::class, 'user_association')
            ->withPivot('org_id')
            ->withTimestamps();
    }

    public function setEmailAttribute($value)
    {
        $this->attributes['email'] = strtolower($value);
    }

    public function getEmailAttribute($value)
    {
        return strtolower($value);
    }
}
