<?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 = [];

    // FUNGSI BOOT: Dijalankan otomatis tepat sebelum data baru disimpan ke database
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($ticket) {
            // 1. Buat Nomor Tiket Otomatis (Contoh: TKT-X8F9A2)
            if (empty($ticket->ticket_number)) {
                $ticket->ticket_number = 'TKT-' . strtoupper(Str::random(6));
            }

            // 2. Buat Token URL Rahasia (Panjang 32 karakter acak)
            if (empty($ticket->token)) {
                $ticket->token = Str::random(32);
            }
        });
    }

    // Relasi: Satu tiket punya BANYAK balasan obrolan
    public function replies()
    {
        return $this->hasMany(TicketReply::class);
    }

    // Relasi: Tiket ini milik siapa? (Bisa mereturn null jika Guest)
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
