<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Ticket extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'subject',
        'body',
        'status',
        'admin_replied_at',
        'admin_last_reply_text',
        'priority',
    ];

    protected $casts = [
        'admin_replied_at' => 'datetime',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function getStatusColorAttribute(): string
    {
        return match ($this->status) {
            'open' => 'green',
            'pending' => 'yellow',
            'closed' => 'gray',
            default => 'gray'
        };
    }

    public function getStatusTextAttribute(): string
    {
        return match ($this->status) {
            'open' => 'باز',
            'pending' => 'در انتظار پاسخ',
            'closed' => 'بسته شده',
            default => $this->status
        };
    }

    public function getPriorityColorAttribute(): string
    {
        return match ($this->priority) {
            'high' => 'red',
            'medium' => 'yellow',
            'low' => 'green',
            default => 'gray'
        };
    }

    public function getPriorityTextAttribute(): string
    {
        return match ($this->priority) {
            'high' => 'بالا',
            'medium' => 'متوسط',
            'low' => 'پایین',
            default => $this->priority
        };
    }

    public function scopeOpen($query)
    {
        return $query->where('status', 'open');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function isUnread(): bool
    {
        return $this->status === 'open' && !$this->admin_replied_at;
    }
}
