<?php

namespace App\Domain\Financial\Models;

use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\BelongsToBranch;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PaymentProof extends Model
{
    use HasUuid, BelongsToAcademy, BelongsToBranch, Auditable;

    public const STATUSES = ['pending', 'under_review', 'approved', 'rejected', 'superseded'];

    protected $fillable = [
        'academy_id', 'branch_id', 'invoice_id', 'participant_id', 'submitted_by',
        'amount_claimed', 'amount_approved', 'method',
        'sender_reference', 'sender_phone', 'transferred_at',
        'proof_path', 'proof_mime', 'proof_size',
        'status', 'reviewed_by', 'reviewed_at',
        'second_reviewed_by', 'second_reviewed_at',
        'rejection_reason', 'review_notes', 'review_ip',
        'payment_id', 'metadata',
    ];

    protected function casts(): array
    {
        return [
            'amount_claimed' => 'integer',
            'amount_approved' => 'integer',
            'proof_size' => 'integer',
            'transferred_at' => 'datetime',
            'reviewed_at' => 'datetime',
            'second_reviewed_at' => 'datetime',
            'metadata' => 'array',
        ];
    }

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

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

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

    public function submitter(): BelongsTo
    {
        return $this->belongsTo(User::class, 'submitted_by');
    }

    public function reviewer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'reviewed_by');
    }

    public function isOpen(): bool
    {
        return in_array($this->status, ['pending', 'under_review'], true);
    }

    public function statusLabel(): string
    {
        return match ($this->status) {
            'pending' => 'في انتظار المراجعة',
            'under_review' => 'قيد المراجعة',
            'approved' => 'تم الاعتماد',
            'rejected' => 'مرفوض',
            'superseded' => 'مُستبدل',
            default => $this->status,
        };
    }

    /** Approving a proof is the moral equivalent of taking cash. */
    public function isFinancialAudit(): bool
    {
        return true;
    }
}
