<?php

namespace Mamad\Order\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Mamad\Cart\Repository\CartRepository;
use Mamad\Club\Services\ClubService;
use Mamad\Marketing\Services\AffiliateService;
use Mamad\Order\Models\Order;
use Mamad\Product\Service\ProductService;
use Mamad\Shop\Service\ShopService;
use Mamad\Transaction\Models\Transaction;
use Mamad\Transaction\Repository\TransactionRepository;
use Mamad\Wallet\Services\WalletService;

class transaction_add_order_listener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {

        if($event->transaction->transactionAble instanceof Order ){
            TransactionRepository::updateStatus($event->transaction,Transaction::$PROCESSING);
            TransactionRepository::update_transactionAble_Status($event->transaction->transactionable,Transaction::$PROCESSING);
            ClubService::increase($event->transaction->price,"product");
            $this->order_codes($event);
        } elseif($event->transaction instanceof Order){
            $this->order_codes($event);
        }
    }

    public function order_codes($event){
        $total_price=ShopService::get_order_total_price(false);
        $wallet_decreased=(integer) WalletService::decreasing_wallet_amount($total_price,false);
        $club_decreased=(integer) ClubService::decreasing_club_amount($total_price,false);
        $cart=CartRepository::get_cart();
        if($cart) {
            $cart_products = ProductService::get_cart_products($cart);
            $affiliate_price=AffiliateService::calculate_affiliate_percent($cart_products);
            AffiliateService::affiliate_update_amount($affiliate_price);
            ProductService::if_product_in_stock_decrease_stock_number($cart_products, $cart);
        }
        session()->forget("cart");
        if($user_cart=auth()->user()->cart()){
            $user_cart->delete();
        }


        if($wallet_decreased){
            WalletService::clear_using_wallet($wallet_decreased);
        }
        if($club_decreased){
            ClubService::clear_using_club($club_decreased);
        }
    }
}
