<?php

namespace OfficeBrain\Bundle\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;

class OfflineExtended extends PaymentAbstract {
	
	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'];
				/* 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_amount'];
					}
				}
				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;//+$details['setupfee'][$index];
				$currency = $data['currency'];
			}
			if(isset($formData['option']['billing_id'])) {
				$contactbook = $this->entityManager->getRepository('OfficeBrainUserBundle:ContactBook')->getContactBookById($formData['option']['billing_id']);
				//print_r(\Doctrine\Common\Util\Debug::dump($contactbook));
				$cityName = $this->entityManager->getRepository("OfficeBrainCoreBundle:City")->getCityNameById($contactbook->getCityId());
				$stateName = $this->entityManager->getRepository("OfficeBrainCoreBundle:State")->getStateNameById($contactbook->getStateId());
				$countryName = $this->entityManager->getRepository("OfficeBrainCoreBundle:Country")->getCountryCodeById($contactbook->getCountryId());
			}
			$tax_total=number_format($formData['option']['tax_amount'],2);
            $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'=>$formData['option']['billing_id'],'po_number'=>$formData['option']['number'],'transaction_id'=>$this->getInvId(),'amount'=>$total,'tax_total'=>$tax_total,'method'=>'invoice'));
			$this->response['status'] ="INVOICE"; 
		}else{
			$this->response['status']="NOTVALIDATE";
			$this->response['notValid']=$this->commonLibraryManager->prepareFormJsonError($this->form);
		}
		return $this->response;
	}
	
	public function loadPaymentForm($controllerObj) {
		//$paymentMethod = $this->requestManager->get('payment_type');
		$paymentMethod = 'invoice';
		$this->type = new InvoiceType();
		$this->form = $controllerObj->createForm($this->type);
		$this->response['form']=$this->form->createView();
		$this->response['payment_type']=$paymentMethod;
		return $this->response;
	}
	
	public function getInvId(){
		return 'INV'.md5 ('::' . time () );
	}
	
	public function calculateTaxFilter($array) {
    	if($array['vat_unit']=="percentage"){
    		return (float) $array['vat']/100; 
    	}else{
    		return $array['vat'];
    	}
    }
}