<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\Storage;


class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = ['role_id','name','email','email_verified_at','remember_token', 'notify_email'];
    protected $casts = ['email_verified_at' => 'datetime'];
    protected $guarded = ['id'];
    
    public function routeNotificationForMail($notification): string|array
    {
        $list = $this->notificationEmails();
        return count($list) ? $list : $this->email;
    }

    public function notificationEmails(): array
    {
        $raw = (string)($this->notify_email ?? '');
        if ($raw === '') return [];
        $parts = preg_split('/[,\s;]+/', $raw, -1, PREG_SPLIT_NO_EMPTY) ?: [];
        $clean = collect($parts)
            ->map(fn ($e) => mb_strtolower(trim($e)))
            ->filter(fn ($e) => filter_var($e, FILTER_VALIDATE_EMAIL))
            ->unique()
            ->values()
            ->all();

        return $clean;
    }

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

    public function itemRequests(): HasMany { return $this->hasMany(ItemRequest::class, 'requester_id'); }

    public function isAdmin(): bool
    {
        return strtoupper((string)($this->role->code ?? '')) === 'ADMIN';
    }

    public function roleCode(): string
    {
        return strtoupper((string)($this->role->code ?? ''));
    }

    public function isApprover(): bool
    {
        return in_array($this->roleCode(), ['APPROVER_1', 'APPROVER_2'], true);
    }


     public function companies(): BelongsToMany
    {
        return $this->belongsToMany(Company::class, 'company_user', 'user_id', 'company_id');
    }

    public function defaultCompanyId(): ?int
    {
        $sid = session('current_company_id');
        if ($sid) return (int)$sid;
        return $this->companies()->orderBy('companies.id')->value('companies.id');
    }

    public function allowedCompanyIds(): array
    {
        if ($this->isAdmin()) {
            return \App\Models\Company::pluck('id')->all();
        }
        return $this->companies()->pluck('companies.id')->all();
    }

    public function canCreateItemRequests(): bool
    {
        return $this->isAdmin() || !$this->isApprover();
    }

    protected $appends = ['signature_url'];

    public function getSignatureUrlAttribute()
    {
        if (!$this->id) return null;

        $png = "signatures/{$this->id}.png";
        $jpg = "signatures/{$this->id}.jpg";

        if (Storage::disk('public')->exists($png)) return Storage::url($png);
        if (Storage::disk('public')->exists($jpg)) return Storage::url($jpg);

        return null;
    }
}
