<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Concerns\HasAuditColumns;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    /** @use HasFactory<UserFactory> */
    use HasFactory;
    use HasApiTokens;
    use Notifiable;
    use HasRoles;
    use SoftDeletes;
    use HasAuditColumns;

    /** Canonical role name for the all-powerful account. */
    public const SUPER_ADMIN = 'Super Admin';

    protected $fillable = [
        'name',
        'email',
        'password',
        'branch_id',
        'employee_code',
        'phone',
        'designation',
        'avatar',
        'is_active',
        'last_login_at',
        'last_login_ip',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'last_login_at' => 'datetime',
            'password' => 'hashed',
            'is_active' => 'boolean',
        ];
    }

    /* ---------------------------------------------------------------------
     | Relationships
     * ------------------------------------------------------------------- */

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    /** Additional branches this user may access (beyond the primary one). */
    public function branches(): BelongsToMany
    {
        return $this->belongsToMany(Branch::class, 'branch_user');
    }

    /** The family this user is the parent-portal login for (if any). */
    public function family(): HasOne
    {
        return $this->hasOne(Family::class, 'user_id');
    }

    public function isParent(): bool
    {
        return $this->hasRole('Parent');
    }

    /** The student record this user is the portal login for (if any). */
    public function student(): HasOne
    {
        return $this->hasOne(Student::class, 'user_id');
    }

    public function isStudent(): bool
    {
        return $this->hasRole('Student');
    }

    /* ---------------------------------------------------------------------
     | Branch access helpers
     * ------------------------------------------------------------------- */

    public function isSuperAdmin(): bool
    {
        return $this->hasRole(self::SUPER_ADMIN);
    }

    /**
     * All branch ids this user is allowed to operate within
     * (primary branch + any explicitly granted via the pivot).
     */
    public function accessibleBranchIds(): array
    {
        if ($this->isSuperAdmin()) {
            return Branch::query()->pluck('id')->all();
        }

        return collect([$this->branch_id])
            ->merge($this->branches()->pluck('branches.id'))
            ->filter()
            ->unique()
            ->values()
            ->all();
    }

    public function canAccessBranch(int $branchId): bool
    {
        return $this->isSuperAdmin() || in_array($branchId, $this->accessibleBranchIds(), true);
    }

    /* ---------------------------------------------------------------------
     | Presentation
     * ------------------------------------------------------------------- */

    public function getInitialsAttribute(): string
    {
        return collect(explode(' ', $this->name))
            ->take(2)
            ->map(fn ($w) => mb_strtoupper(mb_substr($w, 0, 1)))
            ->implode('');
    }

    public function getRoleLabelAttribute(): string
    {
        return $this->getRoleNames()->first() ?? 'User';
    }
}
