<?php

namespace OfficeBrain\CustomBundle\PaymentBundle\Manager\Extended;

use OfficeBrain\Bundle\PaymentBundle\Manager\AbstractManager\PaymentAbstract;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use OfficeBrain\Bundle\PaymentBundle\Form\InvoiceType;
use Symfony\Component\HttpFoundation\JsonResponse;
use OfficeBrain\Bundle\PaymentBundle\Manager\Extended\OfflineExtended as BaseOfflineExtended;


class OfflineExtended extends BaseOfflineExtended {
	
	public function __construct($entityManager, $requestManager, $sessionManager, $productDetailServiceManager, $payumManager, $payumSecurityTokenFactoryManager, $routerManager, $payumSecurityHttpRequestVerifierManager, $thirdPartyManager, $commonLibraryManager, $orderManager, $serviceGroupRuleManager, $coreLibraryManager) {
		parent::__construct($entityManager, $requestManager, $sessionManager, $productDetailServiceManager, $payumManager, $payumSecurityTokenFactoryManager, $routerManager, $payumSecurityHttpRequestVerifierManager, $thirdPartyManager, $commonLibraryManager, $orderManager, $serviceGroupRuleManager, $coreLibraryManager);
	}
	public function __destruct() {
		parent::__destruct();
	}
	
	public function preparePayment($controllerObj, $isJsonFormat=false) {
		$this->type = new InvoiceType();
		$paymentName = 'invoice';
		$paymentMethod = $this->requestManager->get('payment_type');
		if($isJsonFormat === true){
			$this->form = $controllerObj->createForm($this->type, null, array('csrf_protection' => false));
		}else{
			$this->form = $controllerObj->createForm($this->type);
		}
		$this->form->handleRequest($this->requestManager);
		$price=array();
		$info=array();
		$data=array();
		$totalTaxShippingWise = 0;
		$totalShippingCharge = 0;
		$taxShippingWiseResult = array();
		$total=0;
		$setup=0;
		
		if ($this->form->isValid())
		{
			$formData = $this->form->getData();
			$productData =  $this->getProductData();
			foreach($productData as $index=>$data)
			{
				$totalTaxShippingWiseValue = 0;
				$details['product_name'][$index]=$data['product_name'];
				$details['product_api_code'][$index] =$data['sku_code'];
				$details['product_desc'][$index] =$data['product_name'];
				$details['quantity'][$index] =$data['total_qty'];
				$details['price'][$index] =$data['total_qty']*$data['unit_price'];
				//print_r($$data['charges']);exit;
				/* if(count($data['charges'])>0 && array_key_exists('setup',$data['charges'])){
					$details['setupfee'][$index] = $data['charges'][''];
				}else{
					$details['setupfee'][$index] = 0;
				} */
				
				// Get Charges of Split Shipping 
				if(array_key_exists('split',$data) && count($data['split'])>0 )
				{
					$splitShipCharge = 0;
					$split_temp = 0;
					foreach($data['split'] as $splitShippingCharge)
					{
						$splitShipCharge = $splitShipCharge + $splitShippingCharge['shipping_detail']['shipping_charge'];
						$split_temp++;
					}
				}
				else
				{
					$splitShipCharge = 0;
				}
				
				// Get Charges of Split Shipping
				if(array_key_exists('standard',$data) && count($data['standard'])>0 )
				{
					$standardShipCharge = 0;
					$standard_temp = 0;
					foreach($data['standard'] as $splitShippingCharge)
					{
						$standardShipCharge = $standardShipCharge + $splitShippingCharge['shipping_detail']['shipping_charge'];
					}
				}
				else
				{
					$standardShipCharge = 0;
				} 
				
				// Get Charges of Split Shipping product setup charges / PMS charges
				if(count($data['charges'])>0){
					$charges=0;
					foreach($data['charges'] as $productCharges)
					{   
						$charges = $charges + $productCharges['charges_amounts'];
					}
					
				}
				else{
					$charges = 0;
				}
				
				
				$taxShippingWise=0;
				if(count($data['split'])>0) {
					$shippingType=$data['shipping_type'];
					for($i=0;$i<count($data['split']);$i++) {
						$totalShippingCharge = $totalShippingCharge+$data['split'][$i]['shipping_detail']['shipping_charge'];
						$taxShippingWise=isset($data['split'][$i]['tax_shipping_wise']) ? number_format($data['split'][$i]['tax_shipping_wise'],3) : 0;
						$taxShippingWiseResult[$i]=number_format($taxShippingWise,3);
					}
				}
				$sub_total=$data['total_qty']*number_format($data['unit_price'],3);
				$sub_grand_total=$sub_total;				
				$vatValue = 0;
				if(isset($data['tax']))
				{
					$tax=$this->calculateTax($data['tax']);
					$vat[] =array();
					if($data['tax']['vat_unit']=="percentage"){
						$vat[]=number_format($sub_total*$tax,3, '.', '');
					}else{
						$vat[]=number_format(($tax),3);
					}
					$vatValue=array_sum($vat);
				}
				
				$totalTaxShippingWiseValue+=array_sum($taxShippingWiseResult)+$vatValue;
				$totalTaxShippingWise=$totalTaxShippingWise+$totalTaxShippingWiseValue;
				//$price[]=$data['total_qty']*$data['unit_price'];
				$total=$total+$sub_grand_total+ $standardShipCharge + $splitShipCharge+$totalTaxShippingWiseValue+$charges;//+$details['setupfee'][$index];

				$currency = $data['currency'];
			}
           

            $shippingId=0;
           if($formData['option']['billing_id']==0){
           $sessionBillingData = $this->sessionManager->get('order_guest_billing_address');
           $sessionShippingData = $this->sessionManager->get('order_guest_shipping_address');
           $userRepository=$this->entityManager->getRepository('OfficeBrainUserBundle:User');
           $userDetails=$userRepository->getGuestByEmail($sessionBillingData['guest_billing_address']['email']);
           if($userDetails!=NULL){
			$userDetails = $userDetails;
			}else{
	           $userDetails=$userRepository->AddGuestUserNew($sessionBillingData);
			} 
                     
           $guestBillingObj=$this->entityManager->getRepository('OfficeBrainUserBundle:ContactBook')->addNewGuestBillingAddress($sessionBillingData,$userDetails);
          $guestShippingObj= $this->entityManager->getRepository('OfficeBrainUserBundle:ContactBook')->addNewGuestShippingAddress($sessionShippingData,$userDetails);
            $billingId=$guestBillingObj->getId();
            $shippingId=$guestShippingObj->getId();
          }else{
          	$billingId=$formData['option']['billing_id'];

          }
			
			$tax_total= ($formData['option']['tax_amount']!=null) ?  $formData['option']['tax_amount'] : 0.00;
            $total=$total+$tax_total;
			$storage = $this->payumManager->getStorage('OfficeBrain\Bundle\PaymentBundle\Entity\PaymentDetails');
			$paymentDetails = $storage->create();
			$paymentDetails['productDetail'] = $details;
			$paymentDetails['currency_code']= $currency;
			$paymentDetails['amount'] = $total;
			$storage->update($paymentDetails);
		
			$this->sessionManager->set('paymentDetail',array('billing_id'=>$billingId,'customer_number'=>$formData['option']['customer_number'],'po_number'=>$formData['option']['number'],'transaction_id'=>$this->getInvId(),'amount'=>$total,'tax_total'=>$tax_total,'guest_shipping_id'=>$shippingId,'method'=>'invoice'));
			$this->response['status'] ="INVOICE"; 
		}else{
			$this->response['status']="NOTVALIDATE";
			$this->response['notValid']=$this->commonLibraryManager->prepareFormJsonError($this->form);
		}
		return $this->response;
	}
}
