<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Ticket extends Model
{
    protected $fillable = [
        'uid',
        'department_id',
        'order_id',
        'name',
        'subject',
        'status',
        'shamsi_created',
        'shamsi_updated',
    ];

    public function getRouteKeyName(): string
    {
        return 'name';
    }

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

    public function department(): BelongsTo
    {
        return $this->belongsTo(TicketDepartment::class, 'department_id');
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

    public function replies(): HasMany
    {
        return $this->hasMany(TicketReply::class)->oldest();
    }

    public function statusLabel(): string
    {
        return match ($this->status) {
            'opened'       => 'در انتظار پاسخ',
            'replied'      => 'پاسخ داده شده',
            'user_replied' => 'پاسخ توسط مشتری',
            'in_progress'  => 'در حال بررسی',
            'closed'       => 'بسته شده',
            default        => $this->status,
        };
    }

    public function statusColor(): string
    {
        return match ($this->status) {
            'opened'       => 'secondary',
            'replied'      => 'success',
            'user_replied' => 'info',
            'in_progress'  => 'warning',
            'closed'       => 'danger',
            default        => 'secondary',
        };
    }

    public function isClosed(): bool
    {
        return $this->status === 'closed';
    }

    // Shamsi datetime string, e.g. "1405/04/17 - 14:30"
    public static function shamsiNow(): string
    {
        return Order::toJalaliString(now()) . ' - ' . now()->format('H:i');
    }

    public static function generateName(): string
    {
        do {
            $name = 'BT-' . str_pad((string) random_int(0, 9999999), 7, '0', STR_PAD_LEFT);
        } while (static::where('name', $name)->exists());

        return $name;
    }
}
