<?php

namespace App\Models;

use App\Models\Concerns\BelongsToOwner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class Payment extends Model
{
    use BelongsToOwner;

    public const STATUS_PENDING = 'pending';

    public const STATUS_PAID = 'paid';

    public const STATUS_FAILED = 'failed';

    public const METHOD_CASH = 'cash';

    public const METHOD_MOMO = 'momo';

    public const METHOD_CARD = 'card';

    public const METHOD_OTHER = 'other';

    public const METHOD_GATEWAY = 'gateway';

    protected $table = 'care_payments';

    protected $fillable = [
        'uuid', 'owner_ref', 'bill_id', 'amount_minor', 'method',
        'status', 'gateway_provider', 'reference', 'paid_at', 'recorded_by', 'notes',
    ];

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

    protected static function booted(): void
    {
        static::creating(function (Payment $payment) {
            if (! $payment->uuid) {
                $payment->uuid = (string) Str::uuid();
            }
            if (! $payment->status) {
                $payment->status = self::STATUS_PAID;
            }
        });
    }

    public function getRouteKeyName(): string
    {
        return 'uuid';
    }

    public function bill(): BelongsTo
    {
        return $this->belongsTo(Bill::class, 'bill_id');
    }

    public function isPending(): bool
    {
        return $this->status === self::STATUS_PENDING;
    }

    public function isPaid(): bool
    {
        return $this->status === self::STATUS_PAID;
    }
}
