<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AccountCreditDeposit extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'whmcs_client_id',
        'amount',
        'currency',
        'payable_amount',
        'payable_currency',
        'conversion_rate',
        'currency_snapshot',
        'basket_id',
        'transaction_id',
        'order_date',
        'signature',
        'mode',
        'gateway',
        'status',
        'callback_amount',
        'merchant_amount',
        'callback_currency',
        'payfast_error_code',
        'payfast_error_message',
        'validation_hash',
        'callback_payload',
        'callback_received_at',
        'verified_at',
        'whmcs_synced_at',
        'sync_attempts',
        'next_retry_at',
        'last_error',
        'whmcs_balance_after',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'payable_amount' => 'decimal:2',
        'conversion_rate' => 'decimal:8',
        'currency_snapshot' => 'array',
        'callback_amount' => 'decimal:2',
        'merchant_amount' => 'decimal:2',
        'callback_payload' => 'array',
        'order_date' => 'datetime',
        'callback_received_at' => 'datetime',
        'verified_at' => 'datetime',
        'whmcs_synced_at' => 'datetime',
        'next_retry_at' => 'datetime',
        'sync_attempts' => 'integer',
        'whmcs_balance_after' => 'decimal:2',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // PayFastService verifies both invoice payments and credit deposits through
    // one callback verifier. These aliases expose the locked checkout amount.
    public function getExpectedAmountAttribute(): mixed
    {
        return $this->payable_amount;
    }

    public function getExpectedCurrencyAttribute(): string
    {
        return strtoupper((string) $this->payable_currency);
    }
}
