<?php

namespace App\Models;

use App\Enums\PaymentProofStatus;
use App\Enums\SubscriptionGateway;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class SubscriptionPayment extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'tenant_id', 'subscription_id', 'plan_id', 'gateway', 'amount',
        'currency', 'status', 'period_months', 'covers_from', 'covers_until',
        'proof_path', 'proof_reference', 'gateway_txn_id',
    ];

    protected function casts(): array
    {
        return [
            'gateway' => SubscriptionGateway::class,
            'status' => PaymentProofStatus::class,
            'covers_from' => 'date',
            'covers_until' => 'date',
        ];
    }

    protected static function booted(): void
    {
        static::creating(fn (SubscriptionPayment $p) => $p->uuid ??= (string) Str::uuid());
    }

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    public function plan(): BelongsTo
    {
        return $this->belongsTo(Plan::class);
    }

    public function reviews(): HasMany
    {
        return $this->hasMany(PaymentProofReview::class)->latest('created_at');
    }

    public function amountFormatted(): string
    {
        return $this->currency === 'USD'
            ? '$'.number_format($this->amount / 100, 2)
            : number_format($this->amount).' IQD';
    }
}
