<?php

namespace App\Models;

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

class MexcoCheckoutOrder extends Model
{
    public const STATUS_DRAFT = 'draft';

    public const STATUS_PENDING_PAYMENT = 'pending_payment';

    public const STATUS_PAID = 'paid';

    public const STATUS_EXPIRED = 'expired';

    public const STATUS_CANCELLED = 'cancelled';

    protected $table = 'mexco_checkout_orders';

    protected $fillable = [
        'reference_no',
        'organisation_id',
        'organisation_user_id',
        'plan_id',
        'event_id',
        'event_license_id',
        'invoice_id',
        'status',
        'event_draft',
        'addon_ids',
        'promo_code',
        'subtotal_cents',
        'discount_cents',
        'tax_cents',
        'total_cents',
        'currency',
        'expires_at',
        'completed_at',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'event_draft' => 'array',
            'addon_ids' => 'array',
            'expires_at' => 'datetime',
            'completed_at' => 'datetime',
            'metadata' => 'array',
        ];
    }

    public function organisation(): BelongsTo
    {
        return $this->belongsTo(MexcoOrganisation::class, 'organisation_id');
    }

    public function organisationUser(): BelongsTo
    {
        return $this->belongsTo(MexcoOrganisationUser::class, 'organisation_user_id');
    }

    public function plan(): BelongsTo
    {
        return $this->belongsTo(MexcoPlan::class, 'plan_id');
    }

    public function event(): BelongsTo
    {
        return $this->belongsTo(MeetupEvent::class, 'event_id');
    }

    public function license(): BelongsTo
    {
        return $this->belongsTo(MexcoEventLicense::class, 'event_license_id');
    }

    public function invoice(): BelongsTo
    {
        return $this->belongsTo(MexcoInvoice::class, 'invoice_id');
    }

    public static function statuses(): array
    {
        return [
            self::STATUS_DRAFT => 'Draft',
            self::STATUS_PENDING_PAYMENT => 'Pending payment',
            self::STATUS_PAID => 'Paid',
            self::STATUS_EXPIRED => 'Expired',
            self::STATUS_CANCELLED => 'Cancelled',
        ];
    }

    public function statusLabel(): string
    {
        return self::statuses()[$this->status] ?? ucfirst(str_replace('_', ' ', $this->status));
    }

    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }
}
