<?php

namespace App\Models;

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

class EventRegistration extends Model
{
    use HasFactory;

    protected $table = 'event_registration';

    protected $fillable = [
        'reg_id',
        'name',
        'parent',
        'email',
        'phone',
        'eventid',
        'amount',
        'datepaid',
        'datecreated',
        'txnid',
        'paymentmode',
        'status',
    ];

    protected $casts = [
        'datepaid' => 'datetime',
        'datecreated' => 'datetime',
        'amount' => 'decimal:2',
    ];

    /**
     * Get the event this registration belongs to
     */
    public function event()
    {
        return $this->belongsTo(Event::class, 'eventid', 'Id');
    }

    /**
     * Scope: Get successful registrations only
     */
    public function scopeSuccessful($query)
    {
        return $query->where('status', 'success');
    }

    /**
     * Scope: Get pending registrations
     */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    /**
     * Scope: Get failed registrations
     */
    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    /**
     * Check if registration is paid
     */
    public function isPaid(): bool
    {
        return $this->status === 'success' && 
               ($this->paymentmode === 'FREE' || !is_null($this->txnid));
    }

    /**
     * Mark registration as paid
     */
    public function markAsPaid($txnid = null, $paymentMode = 'PAYU'): void
    {
        $this->update([
            'status' => 'success',
            'txnid' => $txnid,
            'paymentmode' => $paymentMode,
            'datepaid' => now(),
        ]);
    }

    /**
     * Mark registration as failed
     */
    public function markAsFailed($txnid = null): void
    {
        $this->update([
            'status' => 'failed',
            'txnid' => $txnid,
        ]);
    }

    /**
     * Get registration status badge
     */
    public function getStatusBadge(): string
    {
        $badges = [
            'pending' => '<span class="badge badge-warning">Pending</span>',
            'success' => '<span class="badge badge-success">Successful</span>',
            'failed' => '<span class="badge badge-danger">Failed</span>',
        ];

        return $badges[$this->status] ?? '<span class="badge badge-secondary">Unknown</span>';
    }
}
