<?php

namespace App\Models;

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

class MexcoCredit extends Model
{
    protected $table = 'mexco_credits';

    protected $fillable = [
        'organisation_id',
        'amount_cents',
        'source',
        'notes',
        'expires_at',
    ];

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

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

    public function isAvailable(): bool
    {
        if ($this->amount_cents <= 0) {
            return false;
        }

        if ($this->expires_at && now()->gt($this->expires_at)) {
            return false;
        }

        return true;
    }

    public function formattedAmount(): string
    {
        return 'MYR '.number_format($this->amount_cents / 100, 2);
    }
}
