<?php

namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;

use App\Classes\Modules\Transactions\Standards\Rules\CanCreateTransaction;
use App\Classes\Modules\Transactions\Standards\Rules\CanCreateTransactionDetail;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionDetailObject;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Transactions\Services\CreatesTransactionDetail;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Http\Resources\TransactionResource;
use App\Http\Resources\TransactionDetailResource;

use App\Classes\Modules\Currencies\Services\FetchesCurrency;
use App\Classes\Modules\Currencies\Services\RateCalculatesCurrency;

use App\Classes\Modules\Companies\Services\FetchesCompany;

use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CreateTransactionLogic extends AbstractControllerLogic
{


    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Created Transaction',
            'message' => 'You have successfully created a transaction'
        ];
    }

    
    /** @var GeneratesTransactionBillNumber */
    private $generatesTransactionBillNo;

    /** @var CanCreateTransaction */
    private $canCreateTransaction;
    
    private $fetchesCurrency;
   
    private $rateCalculatesCurrency;
    
    private $fetchesCompany;

    private $createsTransaction;
    
    private $canCreateTransactionDetail;
    
    private $createsTransactionDetail;

    /**
     * CreateWalletLogic constructor.
     * @param GeneratesTransactionBillNumber $generatesTransactionBillNo
     * @param CanCreateTransaction $canCreateTransaction
     * @param FetchesCurrency $fetchesCurrency
     * @param RateCalculatesCurrency $rateCalculatesCurrency
     * @param FetchesCompany $fetchesCompany
     * @param CreatesTransaction $createsTransaction
     * @param CanCreateTransactionDetail $canCreateTransactionDetail
     * @param CreatesTransactionDetail $createsTransactionDetail
     */
    public function __construct(
        GeneratesTransactionBillNumber $generatesTransactionBillNo, CanCreateTransaction $canCreateTransaction,
        FetchesCurrency $fetchesCurrency, RateCalculatesCurrency $rateCalculatesCurrency, FetchesCompany $fetchesCompany,
        CreatesTransaction $createsTransaction,
        CanCreateTransactionDetail $canCreateTransactionDetail, CreatesTransactionDetail $createsTransactionDetail
    ){
        $this->generatesTransactionBillNo = $generatesTransactionBillNo;
        $this->canCreateTransaction = $canCreateTransaction;
        $this->fetchesCurrency = $fetchesCurrency;
        $this->rateCalculatesCurrency = $rateCalculatesCurrency;
        $this->fetchesCompany = $fetchesCompany;
        $this->createsTransaction =$createsTransaction;
        $this->canCreateTransactionDetail =$canCreateTransactionDetail;
        $this->createsTransactionDetail = $createsTransactionDetail;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        try {

            DB::beginTransaction();
            $json_array = json_decode($request->getContent(), true);
            $company =  $this->fetchesCompany->execute(['id' => $json_array['company_id']]);
            
            $conversion_currency = $this->fetchesCurrency->execute(['id' => $json_array['currency_id']]);
            $convertable_currency = $this->fetchesCurrency->execute(['id' => 1]);//MYR
            $convert_amount = $this->rateCalculatesCurrency->execute($conversion_currency, $convertable_currency, $json_array['amount']);
            $convert_rate = $this->rateCalculatesCurrency->execute_rate($conversion_currency, $convertable_currency);
            /*
            int $bill_no,string $trans_type1,string $trans_type2,
        float $amount, int $currency_id, int $original_amount,
        int $original_currency_id, float $currency_rate,
        string $dt_transaction,int $status,int $booking_id,
        int $company_id
              */      
            $object = new TransactionObject(
                $this->generatesTransactionBillNo->execute(),$json_array['trans_type1'],$json_array['trans_type2'],
                number_format( (float) $convert_amount, 5, '.', ''), 1 , number_format( (float) $json_array['amount'], 5, '.', ''),
                $json_array['currency_id'],number_format( (float) $convert_rate, 5, '.', ''),
                $json_array['dt_transaction'],1,$request->route('id'),
                $company->id
            );
            
            $this->canCreateTransaction->passes($object);

            $transaction = $this->createsTransaction->execute($object);
            
            $transaction_array = new TransactionResource($transaction);
            $transaction_detail_array = array();
            foreach ($json_array['transaction_detail'] as $key => $value) {
                
                $object_detail = new TransactionDetailObject(
                    $json_array['trans_type1'],$json_array['trans_type2'],
                    $transaction->id,$value['product_code'],$value['product_name'],
                    (int)$value['qty'],number_format( (float) $convert_amount, 5, '.', ''), number_format( (float) $json_array['amount'], 5, '.', '')
                );
                $this->canCreateTransactionDetail->passes($object_detail);
                $transaction_detail = $this->createsTransactionDetail->execute($object_detail);
                //array_push($stack, "apple", "raspberry");
                $transaction_detail_resource= new TransactionDetailResource($transaction_detail);
                $transaction_detail_array[]= $transaction_detail_resource->toArray($request);
                 
            }
            
            //$transaction_array['transaction_detail']= $transaction_detail_array;
            //print_r($transaction_detail_array);
            //dd($transaction_detail_array);
            DB::commit();

            return $this->resourceResponse($transaction_array);
            //return $this->resourceResponse($json_array);

        } catch (\Exception $exception) {
            throw new ErrorException($exception->getMessage(), $exception->getCode());
        }

    }
}