<?php

namespace App\Models;

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

class Ticket extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    protected static function booted(): void
    {
        static::creating(function ($ticket) {
            $ticket_id_prefix = setting('ticket_system.ticket_id_prefix', 'RIX');

            do {
                $reference_id = $ticket_id_prefix . '-' . Str::upper(Str::random(10));
            } while (self::where('reference_id', $reference_id)->exists());

            $ticket->reference_id = $reference_id;
        });

        static::deleting(function ($ticket) {
            $ticket->messages()->delete();
        });
    }

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

    public function category()
    {
        return $this->belongsTo(TicketCategory::class);
    }

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

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