<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use App\Models\TxnLog;

class Ticket extends Model
{
    use HasFactory;

    protected $fillable = [
        'event_id',
        'first_name',
        'last_name',
        'phone',
        'email',
        'school',
        'amount',
        'quantity',
        'total_amount',
        'reference',
        'payment_status',
        'mpesa_receipt_number',
        'payment_date',
        'ticket_type'
    ];

    protected $casts = [
        'payment_date' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function event()
    {
        return $this->belongsTo(Event::class);
    }

    public function txnLog()
    {
        return $this->hasOne(TxnLog::class, 'ticket_reference_number', 'reference');
    }

    // Generate a unique reference number
    public static function generateReference()
    {
        do {
            // Generate a longer, more unique reference with timestamp
            $timestamp = now()->format('ymdH'); // YYMMDDHHmmss
            $time = now()->format('dH'); // YYMMDDHHmmss
            $random = strtoupper(Str::random(5)); // 6 random characters
            $reference = 'PACE-TEENZ-FEST-' . $random . $time;
        } while (self::where('reference', $reference)->exists()); // Ensure uniqueness

        return $reference;
    }
    public function complimentaryCode()
    {
        return $this->belongsTo(ComplimentaryCode::class, 'complimentary_code', 'code');
    }

    // Relationship to the user who created the ticket
    public function creator()
    {
        return $this->belongsTo(\App\Models\User::class, 'created_by');
    }

    // Relationship to the user who last updated the ticket
    public function updater()
    {
        return $this->belongsTo(\App\Models\User::class, 'updated_by');
    }



}
