<?php

namespace App\Observers;

use App\Models\PaymentManagement\Payment;
use App\Models\PaymentManagement\PaymentMethod;
use App\Models\PaymentManagement\PaymentReference;

class PaymentObserver{


    /**
     * @param Payment $payment
     * @return void
     */
    public function creating(Payment $payment){
         $attributes = $payment->attributesToArray();
         $payment_method_id = $attributes['payment_method_id'] ?? null;
        if (!isset($attributes['remaining_amount'])){
            $payment->setAttribute("remaining_amount",$payment->paid_amount);
        }
        if (!isset($attributes['internal_reference'])){
            $payment->setAttribute("internal_reference",PaymentReference::new("IR")->reference ?? "");
        }
        if (filled($payment_method_id)){
            $method = PaymentMethod::find($payment_method_id);

            if (!isset($attributes['provider_reference']) and $method->code == PaymentMethod::CASH){
                $payment->setAttribute("provider_reference",PaymentReference::new("CS",5)->reference ?? "");
            }
        }
        if (!isset($attributes['expired_at'])){
            $payment->setAttribute("expired_at", now()->addMonths("1"));
        }
    }

    /**
     * @param Payment $payment
     * @return void
     */
    public function updating(Payment $payment){
        $changes =  $payment->getChanges();

        if (!isset($changes['expired_at'])){
            $payment->setAttribute("expired_at", now()->addMonths(1));
        }
    }

    /**
     * @param Payment $payment
     * @return Payment
     */
    public function created(Payment $payment){

        return $payment;

    }

    /**
     * @param Payment $payment
     * @return Payment
     */
    public function updated(Payment $payment){

        return $payment;

    }
}
