<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Enums\StaffRole;

class Staff extends Authenticatable
{
    use HasFactory, Notifiable, SoftDeletes;

    protected $table = 'staffs';
    protected $guarded = [];

    protected $casts = [
        'role' => StaffRole::class,
    ];

    protected $appends = [
        "fullname",
        "avatar_url"
    ];

    protected function fullname(): Attribute
    {
        return Attribute::make(
            get: fn() => $this->firstname . " " . $this->lastname,
        );
    }

    protected function init_tickets()
    {
        return $this->hasMany(
            Ticket::class,
        );
    }

    public function tickets()
    {
        return Ticket::where("staff_id", $this->id)->orWhere(function ($query) {
            $query->where("attached_to", "staff")
                ->where("attached_to_id", $this->id);
        });
    }

    protected function avatarUrl(): Attribute
    {
        if ($this->avatar) {
            return Attribute::make(
                get: fn() => $this->avatar['url'],
            );
        } else {
            return Attribute::make(
                get: fn() => asset("/static/avatar.jpg"),
            );
        }
    }

    public function scopeFilter($query, $filters)
    {
        // $query->when($filters['search'] ?? null, function ($query, $search) {
        //     if ($search == 'active') {
        //         $query->where('is_active', 1);
        //     } else {
        //         $query->where(function ($query) use ($search) {
        //             // $query
        //             //     ->where('fullname', 'like', '%' . $search . '%')
        //             //     ->orWhere('email', 'like', '%' . $search . '%')
        //             //     ->orWhere('gender', 'like', '%' . $search . '%')
        //             //     ->orWhere('full_address', 'like', '%' . $search . '%');
        //         });
        //     }
        // });
    }
}
