<?php

namespace App\Observers;

use App\Exceptions\InsuffisantFundsException;
use App\Models\OrderManagement\Order;
use App\Models\SettingManagement\Status;
use App\Models\UserManagement\Admin;
use App\Models\UserManagement\User;
use App\Notifications\Backend\User\ReturnRequestOrderNotification;
use function Yajra\DataTables\Html\data;


class OrderObserver{

    /** Se produit quand la commande est en cours de creation
     * @param Order $order
     * @return Order
     */
    public function creating(Order $order){
        $attributes = $order->getAttributes();

        $period = $attributes['period'] ?? null;
        if (!isset($attributes['status_code'])){
            $order->setAttribute("status_code",Status::UNPROCESSED);
        }
        if (blank($period)){
            $order->setAttribute("period",getSettingsOf("current_orders_period") ?? date('Y-m'));
        }
        if (!isset($attributes['ref_id'])){
            $order->setAttribute("ref_id",Order::newId());
        }
        return $order;
    }


    /** Se produit quand la commande a été crée
     * @param Order $order
     * @return Order
     */
    public function created(Order $order){
        return $order;
    }


    /**
     * @param Order $order
     * @throws InsuffisantFundsException
     * @throws \Throwable
     */
    public function updated(Order $order){

        $changes = $order->getChanges();


        //si le statut de la commande a été modifié
        if (isset($changes['status_code'])){
            $order_status = $order->status_code;

           // si "rejétée"
            if (in_array($order_status,Order::getStatusesRollbackStock())){
                //rejete chaque produit commandé [App\Models\OrderProduct]
                $order->items()
                       ->noRejected()
                       ->get()
                       ->map->update(['rejected' => true]);
            }
            if ($order_status == Status::REFUNDED_REQUEST){

                try {
                    Admin::get()->map->notify(new ReturnRequestOrderNotification($order));
                }catch (\Exception $e){}
            }

            if ($order_status == Status::PAID){
                $payer = $order->customer; // App\Models\User

                $paymentsUsages = $order->paymentUsages()->used()->get(); // App\Models\PaymentManagement\PaymentUsage

                if (blank($paymentsUsages)){
                    //consomme les paiements disponibles du client
                    // lèvera une exception si solde insuffusant
                    $order->consumePayments($payer,$order->total);
                }
            }

            $refundedStatuses = [Status::CANCELED,Status::REFUNDED_ORDER];
            if (in_array($order_status,$refundedStatuses)){
                //les paiements utilisés pour cette commande
               $usages = $order->paymentUsages()->used()->get(); // App\Models\PaymentManagement\PaymentUsage

               if (filled($usages)){
                   foreach ($usages as $usage) {
                       // retourne le montant utilisé
                       $amountUsed = $usage->amount_used;
                       $payment = $usage->payment; // App\Models\Payment
                     //  $remaining_amount_before = $payment->remaining_amount;

                       $payment->increment('remaining_amount',$amountUsed); //incrémente le reste

                      // $remaining_amount_after = $payment->remaining_amount;

                       $usage->update([ 'deleted' => true ]); // place la ligne a deleted=true

                       $payment->update(["visible" => true]);
                   }
               }

            }
        }
    }
}
