<?php

namespace App\Models;

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

class Balance extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'id',
        'user_id',
        'discount_id',
        'discount_amount',
        'merchant_ref',
        'reference',
        'amount',
        'fee_merchant',
        'fee_customer',
        'total_fee',
        'amount_received',
        'payment_method',
        'payment_name',
        'pay_code',
        'pay_url',
        'checkout_url',
        'currency',
        'status',
        'is_closed_payment',
        'paid_at',
        'note',
        'amount_topup',
    ];

    protected static function boot()
    {
        parent::boot();

        static::saved(function ($balance) {
            static::updateDiscountQuota($balance);
        });

        static::deleting(function ($balance) {
            static::updateDiscountQuota($balance);
        });
    }

    protected static function updateDiscountQuota($balance)
    {
        if ($balance->discount_id) {
            $discount = Discount::find($balance->discount_id);
            if ($discount) {
                $total_used = Balance::where('discount_id', $balance->discount_id)
                    ->whereIn('status', ['PAID', 'UNPAID'])
                    ->count();
                if ($discount->quota_used != $total_used) {
                    $discount->quota_used = $total_used;
                    $discount->save();
                }
            }
        }
    }
}
