<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Helpers\FilterHelper;

class Ticket extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'tickets';
    protected $guarded = [];
    protected $appends = [
        "staff_fullname",
        "created_at_obj",
        "message_html",
        "staffs"
    ];

    public function staff()
    {
        return $this->belongsTo(
            Staff::class,
        );
    }

    public function messages()
    {
        return $this->hasMany(
            TicketMessage::class,
        );
    }

    public function invitations()
    {
        return $this->hasMany(
            TicketInvite::class,
        );
    }

    public function for()
    {
        $r = null;
        if ($this->attached_to == "staff") {
            $r = Staff::find($this->attached_to_id);
        }

        if ($this->attached_to == "user") {
            $r = User::find($this->attached_to_id);
        }

        if ($this->attached_to == "rider") {
            $r = Rider::find($this->attached_to_id);
        }

        return $r;
    }

    public function getStaffsAttribute()
    {
        return $this->messages->pluck("staff_id");
    }

    public function getStaffFullnameAttribute()
    {
        return $this->staff->fullname ?? "";
    }

    public function getMessageHtmlAttribute()
    {
        return nl2br(htmlentities($this->message, ENT_QUOTES, 'UTF-8'));
    }

    protected function getCreatedAtObjAttribute()
    {
        return  FilterHelper::dateObj($this->created_at);
    }

    public function scopeFilter($query, $filters)
    {
        $query->when($filters['filter'] ?? null, function ($query, $filter) {

            if ($filter == 'pending') {
                $query->where('status', 'pending');
            }
            if ($filter == 'open') {
                $query->where('status', 'open');
            }

            // if ($filter == 'closed') {
            //     $query->where('status', 'closed');
            // }

            if ($filter == 'resolved') {
                $query->where('status', 'resolved');
            }

            if ($filter == 'unresolved') {
                $query->where('status', 'unresolved');
            }
        });
    }
}
