<?php

namespace App\Classes\Modules\Bookings\Services;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class CalculatesBookingCurrencyAverageRate
{
    /** @var CalculatesBookingPayableAmount */
    private $calculatesBookingPayableAmount;

    /**
     * CalculatesBookingCurrencyAverageRate constructor.
     * @param CalculatesBookingPayableAmount $calculatesBookingPayableAmount
     */
    public function __construct(CalculatesBookingPayableAmount $calculatesBookingPayableAmount)
    {
        $this->calculatesBookingPayableAmount = $calculatesBookingPayableAmount;
    }


    public function execute(Booking $booking, $type, bool $generateEInvoiceRefund = false){

        $transaction = $booking->transactions()
        ->where('type', TransactionType::PAYMENT)
        ->latest()->get()[0];

        $voucherRedemption = $transaction->voucherRedemption;

        $discount = 0;

        if ($voucherRedemption) {
            $discount = $voucherRedemption->value;
        }

    	if ($type == TransactionType::PAYMENT) {

            $totalPayment = $booking->fix_currency_id === 1 ? $booking->transactions()->payments()->complete()->sum('original_amount') :
                $booking->transactions()->payments()->complete()->selectRaw('sum(amount - service_charge - tax) as sub_total')->get()->sum('sub_total');

            if($totalPayment === 0 || $generateEInvoiceRefund){
                $totalPayment = $booking->fix_currency_id === 1 ? $booking->transactions()->payments()->where('status', ApprovalStatus::REFUNDED)->sum('original_amount') :
                $booking->transactions()->payments()->where('status', ApprovalStatus::REFUNDED)->selectRaw('sum(amount - service_charge - tax) as sub_total')->get()->sum('sub_total');
            }

    	    return $this->calculatesBookingPayableAmount->execute($booking, $booking->fix_currency_id, $generateEInvoiceRefund) / ($totalPayment + $discount);

        }
        else if ($type == TransactionType::BILL) {
        	return $booking->bills->sum('original_amount') / $booking->bills->sum('amount');
        }
    }

}
