<?php

namespace OfficeBrain\CustomBundle\ServiceGroupBundle\Manager\Extended;

use OfficeBrain\CustomBundle\ServiceGroupBundle\Manager\AbstractManager\PromoCouponAbstract as PromoCouponAbstract;
use OfficeBrain\CustomBundle\ServiceGroupBundle\Entity\PromoCoupon;
use OfficeBrain\CustomBundle\ServiceGroupBundle\Entity\RedeemCoupon;

class PromoCouponExtended extends PromoCouponAbstract
{
	protected $promoCoupon;

    public function __construct($entityManager, $request, $paginatorManager, $countries, $languages, $couponUsersManager)
    {
        parent::__construct($entityManager, $request, $paginatorManager, $countries, $languages, $couponUsersManager);
    }

    public function __destruct()
    {
        parent::__destruct();
    }

    /**
     * @author Employee Id: 5497
     * Description : get all promo coupon
     *
     * @return object
     * */
    public function getPromoCouponList()
    {
        $data = array();

        $promoCoupon = $this->promoCouponRepository->getList();
        if (count($promoCoupon) > 0) {
            $data['pagination'] = $this->paginatorManager->paginate($promoCoupon, $this->request->get('page'), $this->recordsPerPage, array(), count($promoCoupon));
        }

        $data['records_per_page'] = $this->recordsPerPage;
        $data['page'] = $this->request->get('page');

        return $data;
    }

    public function getPromoCouponByCouponName()
    {
        $data = array();

        $promoCoupon = $this->promoCouponRepository->findByCouponName($this->request->get('coupon_name'));
        
        if (empty($promoCoupon)) {
            $data['error'] = "CODE_NOT_FOUND";
        } 
        else {
            $data = $promoCoupon[0];
            
            if ($this->projectSetting['user_id'] == $data['createdUid']) {
            	$data['inline_edit'] = false; //Set false temporarily to turn of inline editing as this functionality yet to be done.
            }
        }
        
        return $data;
    }
    

    /**
     * @author Employee Id: 5497
     * Description : Filter form data
     *
     * @return object
     * */
    public function filterFormData($form, $translator)
    {
    	$promoCoupon = $form->getData();
    	 
    	$data = array();
    	$countryId = $promoCoupon->getCountryId();
    	if ($countryId) {
    		$countryCode = $this->getCountryField($countryId, 'id', 'code');
    
    		foreach ($promoCoupon->getLanguageMapping() as $key => $language) {
    			if (!in_array($language->getLanguageId(), $this->countries[$countryCode]['language'])) {
    				unset($promoCoupon->getLanguageMapping()[$key]);
    			} else {
    				if ($language->getPageTitle() == '') {
    					$form->get('languageMapping')[$key]->get('pageTitle')->addError(new \Symfony\Component\Form\FormError($translator->trans('service_group.admin.form.page.label.required')));
    				}
    			}
    		}
    	}
    
    	return $form;
    }

    /**
     * @author Employee Id: 5497
     * Description : Save coupon data to database
     *
     * @return object
     * */
    public function setPromoCoupon($promoCoupon, $mode='')
    {
        $promoCouponId = $promoCoupon->getId();
        $couponName = $promoCoupon->getCouponName();
        
        $cnt = $this->promoCouponRepository->findCountByCouponName($couponName);
                 
        if (($cnt > 0) && $mode!="edit") { // duplicate coupon name
           return 'ERROR_COUPON_NAME_ALREADY_EXISTS';
        }
        
        if ($promoCouponId == '') {
        	$promoCoupon->setCreatedUid($this->projectSetting['user_id']);
        	$promoCoupon->setCreatedAt(new \DateTime());
        }
             
        $promoCoupon = $this->promoCouponRepository->set($promoCoupon);

        return $promoCoupon;
    }


    /**
     * @author Employee Id: 5497
     * Description : Find coupon name of object
     *
     * @return object
     * */
    public function getPromoCouponById($id = 0)
    {
    	if ($id == 0) {
    		$id = $this->request->get('id');
    	}

        return $this->promoCouponRepository->getPromoCouponById($id);
    }

    /**
     * @author Employee Id: 5497
     * Description : Update coupon name data to database
     *
     * @return object
     * */
    public function updatePromoCoupon($promoCoupon)
    {
    	$promoCoupon->setUpdatedUid($this->projectSetting['user_id']);
    	$promoCoupon->setUpdatedAt(new \DateTime());
    	
        return $this->setPromoCoupon($promoCoupon, "edit");
    }


    /**
     * @author Employee Id: 5497
     * Description : Soft delete of coupon name
     *
     * @return object
     * */
    public function deletePromoCoupon()
    {
        $pageObj = $this->promoCouponRepository->getPromoCouponById($this->request->get('id'));

        if (is_object($pageObj)) {
            $pageObj->setDeletedAt(new \DateTime());
            $pageObj->setDeletedUid($this->projectSetting['user_id']);

            return $this->promoCouponRepository->set($pageObj);
        }
    }


    public function searchPromoCoupon()
    {
        $data = array();
        $option = $this->request->get('option');
        $keyword = $this->request->get('keyword');
        
        if($option == 'coupon_type') {
        	$keyword = str_replace(" ","_",strtolower($keyword));
        }

        $promoCoupon = $this->promoCouponRepository->findByOption($option, $keyword);

        if (count($promoCoupon) > 0) {
            $data['pagination'] = $this->paginatorManager->paginate($promoCoupon, $this->request->get('page'), $this->recordsPerPage, array(), count($promoCoupon));
        }

        $data['records_per_page'] = $this->recordsPerPage;
        $data['page'] = $this->request->get('page');

        return $data;
    }
    
    /**
     * @author Employee Id: 5497
     * Description : Change coupon Status
     *
     * @return object
     * */
    public function changeStatus()
    {
    	return $this->promoCouponRepository->changeStatus($this->request->get('id'));
    }
    
    /**
     * @author Employee Id: 5497
     * Description : for site-search
     *
     * */
    public function siteSearch($request)
    {
    	$siteSearch['page']  =  $request->query->get('page', 1);
    	$siteSearch['search'] = $request->get('search','');
    	
    	return $siteSearch;
    }
    
    /**
     * @author Employee Id: 5497
     * Description : list of site-search
     *
     * */
    public function getSiteSearchList($request)
    {

    	$siteSearchList = $this->promoCouponRepository->getSiteSearchList($request->get('search'));
    	
    	$siteSearchListArray['totalCount'] = count($siteSearchList);
    	
    	$siteSearchListArray['pagination'] =  $this->paginatorManager->paginate($siteSearchList, $request->get('page', '1'), $this->recordsPerPage, array(), count($siteSearchList));
    	
    	unset($siteSearchList);
    	
    	return $siteSearchListArray;
    }
    
    public function getCouponByCouponCode($code)
    { 
    	$data = array();

    	$promoCoupon = $this->promoCouponRepository->findByCouponName($code);

    	if (empty($promoCoupon)) {
    		$data['error'] = "CODE_NOT_FOUND";
    	}
    	else {
    		$data = $promoCoupon[0];
    	}

    	return $data;
    }
    
    public function validateCouponCode($code = '', $redeemCoupon = true)
    {
    	$return = '';
    	
    	if ($code == '') {
    		$code = $this->request->get('coupon_code');
    	}

    	$this->promoCoupon = $this->promoCouponRepository->findByCouponName($code);
  
    	if (count($this->promoCoupon) > 0) {
    		if (!(strtotime($this->promoCoupon->getStartDate()->format('Y-m-d H:i:s')) <= strtotime(date('Y-m-d')) && strtotime($this->promoCoupon->getEndDate()->format('Y-m-d H:i:s')) >= strtotime(date('Y-m-d')))) {
    			$return = 'EXPIRED_PROMO_CODE';
    		}
    		
    		$getCouponUsers = $this->couponUsersManager->getUserCouponRedeemStatus($this->promoCoupon->getId());
    		if(count($getCouponUsers) > 0) {
    			$return = 'EXIST_PROMO_CODE';
    		}
    	} 
    	else {
    		$return = 'INVALID_PROMO_CODE';
    	}
    	
    	if ($return == '') {
    		if ($redeemCoupon == true) {
    			$this->redeemCouponCode();
    		}

    		$return = 'VALID_PROMO_CODE';
		}

    	return $return;
	}

	public function redeemCouponCode()
	{
		$this->couponUsersManager->isCouponRedeem($this->promoCoupon->getId());
	}
	
	public function removeCouponCode($code = '') {
		if ($code == '') {
			$code = $this->request->get('coupon_code');
		}
		$validateMessage = $this->validateCouponCode();

		if ($validateMessage == 'VALID_PROMO_CODE') {
			$this->couponUsersManager->removeRedeemCoupon($this->promoCoupon->getId());
			$this->deleteRedeemCoupon($this->promoCoupon->getId());
		}
	}
	
	public function setRedeemCoupon($redeemCouponData)
	{
		$redeemCoupon = $this->redeemCouponRepository->findByPreAddToCartId($redeemCouponData['pre_add_to_cart_id']);
		
		if (count($redeemCoupon) == 0) {
			$redeemCoupon = new RedeemCoupon();
			
			$redeemCoupon->setCreatedAt(new \DateTime());
		}

		if (isset($redeemCouponData['order_id'])) {
			$redeemCoupon->setOrderId($redeemCouponData['order_id']);
		}
		if (isset($redeemCouponData['order_item_line_id'])) {
			$redeemCoupon->setOrderItemLineId($redeemCouponData['order_item_line_id']);
		}
		if (isset($redeemCouponData['pre_add_to_cart_id'])) {
			$redeemCoupon->setPreAddToCartId($redeemCouponData['pre_add_to_cart_id']);
		}
		if (isset($redeemCouponData['unit_price'])) {
			$redeemCoupon->setUnitPrice($redeemCouponData['unit_price']);
		}
		if (isset($redeemCouponData['discount_unit_price'])) {
			$redeemCoupon->setDiscountUnitPrice($redeemCouponData['discount_unit_price']);
		}
		if (isset($redeemCouponData['item_qty_total'])) {
			$redeemCoupon->setItemQtyTotal($redeemCouponData['item_qty_total']);
		}
		if (isset($redeemCouponData['discount_amount'])) {
			$redeemCoupon->setDiscountAmount($redeemCouponData['discount_amount']);
		}
		if (isset($redeemCouponData['coupon_id'])) {
			$redeemCoupon->setCouponId($redeemCouponData['coupon_id']);
		}
		if (isset($redeemCouponData['user_id'])) {
			$redeemCoupon->setUserId($redeemCouponData['user_id']);
		}

		$this->redeemCouponRepository->set($redeemCoupon);
	}
	
	/**
	 * @author Employee Id: 5497
	 * Description : delete reddem coupon
	 *
	 * @return object
	 * */
	public function deleteRedeemCoupon($couponId)
	{
		$allCoupon = $this->redeemCouponRepository->findByCouponId($couponId);
		 
		foreach($allCoupon as $redeemCoupon) {
			$this->redeemCouponRepository->remove($redeemCoupon);
		}
	}
	
	public function getUnitPriceByCouponCode($getCouponUsers, $productApiData, $totalQty, $unitPrice, $orderType = '') {
		$productArray = array();

		if ($orderType == 'decoration') {
			$orderType = 'decorative';
		}

		foreach ($productApiData['pricing'] as $ptype=>$priceAll) {
			if ($orderType == $ptype) {

				switch ($getCouponUsers->getPromoCouponId()->getCouponType()) {
					case 'eqp':
						return $this->getEqpDiscountPrice($productApiData['pricing'][$ptype]);
						break;
				
					case 'eqp_discount_percent':
						return $this->getEqpDiscountPrice($productApiData['pricing'][$ptype],$getCouponUsers->getPromoCouponId()->getDiscount(),'percent');
						break;
					
					case 'eqp_discount_flat':
						return $this->getEqpDiscountPrice($productApiData['pricing'][$ptype],$getCouponUsers->getPromoCouponId()->getDiscount(),'flat');
						break;
		
					case 'next_column':
						return $this->getNextColumnPrice($productApiData['pricing'][$ptype],$unitPrice);
						break;
						
					case 'discount_flat':
						return $this->getDiscountPrice($unitPrice,$getCouponUsers->getPromoCouponId()->getDiscount(),'flat');
						break;
		
					case 'discount_percent':
						return $this->getDiscountPrice($unitPrice,$getCouponUsers->getPromoCouponId()->getDiscount(),'percent');
						break;
		
					default:
						return '0.00';
						break;
				}
			}
		}
	}
	
	/**
	 * @author Employee Id: 5497
	 * Description : calculate eqp andeqp_less price matrix
	 * @return object
	 * */
	public function getEqpDiscountPrice($productDataWithType, $eqpDiscount = 0,$discountType = '')
	{
		$endPriceArray = end($productDataWithType);
		if($endPriceArray['rate']) {
			if($eqpDiscount != 0) {
				if($discountType == 'flat') {
					$endPriceArray['rate'] = $this->currencyFilter($endPriceArray['rate']-$eqpDiscount);
				}
				elseif($discountType == 'percent') {
					$endPriceArray['rate'] = $this->currencyFilter($endPriceArray['rate'] - (($endPriceArray['rate']*$eqpDiscount)/100));
				}
			}
		}

		if ($endPriceArray['rate'] < 0) {
			$endPriceArray['rate'] = '0.00';
		}
		
		return $endPriceArray['rate'];
	}
	
	
	/**
	 *
	 * @author Employee Id: 5497
	 *         Description : calculate column and next_column price matrix
	 * @return object
	 *
	 */
	public function getNextColumnPrice($productDataWithType,$unitPrice)
	{
		$basicPrice = $unitPrice;
		foreach ($productDataWithType as $key => $valPr) {
			if($valPr['rate'] == $unitPrice) {
				if((count($productDataWithType) - 1) != $key) {
					$basicPrice = $productDataWithType[$key + 1]['rate'];
				}
			}
		}

		if ($basicPrice < 0) {
			$basicPrice = '0.00';
		}

		return $basicPrice;
	}
	
	
	/**
	 * @author Employee Id: 5497
	 * Description : calculate eqp andeqp_less price matrix
	 * @return object
	 * */
	public function getDiscountPrice($unitPrice, $discount = 0,$discountType = '')
	{
		if($discountType == 'flat') {
			$unitPrice = $this->currencyFilter($unitPrice-$discount);
		}
		elseif($discountType == 'percent') {
			$unitPrice = $this->currencyFilter($unitPrice - (($unitPrice*$discount)/100));
		}

		if ($unitPrice < 0) {
			$unitPrice = '0.00';
		}

		return $unitPrice;
	}
	
	/**
	 * @author Employee Id: 5497
	 * Description : currency Filter
	 * @return object
	 * */
	public function currencyFilter($number)
	{
		if(is_numeric($number)) {
			return number_format($number, $decimal = 3, '.', '');
		}
	
		return $number;
	}
	
	/**
	 * @author Employee Id: 5069
	 * Description : couponCode
	 * @return object
	 * */
	public function getCounpCodeByOrder($orderId)
	{
		return $this->redeemCouponRepository->getCouponCodeByOrder($orderId);
	}
	
	public function updatePriceByCountry($productDetailArray, $culture)
	{
		$country_code = explode('_', $culture);
		$productArray = array();
		 
		if (isset($productDetailArray['product_id'])) {
			$productArray[] = $productDetailArray;
		} elseif (isset($productDetailArray['products'])) {
			$productArray = (array)$productDetailArray['products'];
		} else {
			$productArray = (array)$productDetailArray;
		}
		 
		foreach ($productArray as $main_index=>$productDetail) {
			if (isset($country_code[1]) && isset($productArray[$main_index]['variation_pricing_for_other_country'][$country_code[1]])) {
				$productArray[$main_index]['variation_pricing'] = $productArray[$main_index]['variation_pricing_for_other_country'][$country_code[1]];
			}
			if (isset($country_code[1]) && isset($productArray[$main_index]['pricing_for_other_country'][$country_code[1]])) {
				$productArray[$main_index]['pricing'] = $productArray[$main_index]['pricing_for_other_country'][$country_code[1]];
				
				$priceType = 'decorative';
				$index = 0;
				
				if (isset($productArray[$main_index]['pricing'][$priceType][$index])) {
					$productArray[$main_index]['unit_price'] = $productArray[$main_index]['pricing'][$priceType][$index]['rate'];
					$productArray[$main_index]['regular_price'] = $productArray[$main_index]['pricing'][$priceType][$index]['rate'];
					$productArray[$main_index]['minimum_quantity'] = $productArray[$main_index]['pricing'][$priceType][$index]['from'];
					$productArray[$main_index]['minimum_quantity_range'] = $productArray[$main_index]['pricing'][$priceType][$index]['from']. "-" . $productArray[$main_index]['pricing'][$priceType][$index]['to'];
					$productArray[$main_index]['min_price'] = $productArray[$main_index]['pricing'][$priceType][count($productArray[$main_index]['pricing'][$priceType])-1]['rate'];
					$productArray[$main_index]['code'] = $productArray[$main_index]['pricing'][$priceType][count($productArray[$main_index]['pricing'][$priceType])-1]['code'];
				}
			}
		}
		 
		if (isset($productDetailArray['product_id'])) {
			$productDetailArray = reset($productArray);
		} elseif (isset($productDetailArray['products'])) {
			$productDetailArray['products'] = $productArray;
		} else {
			$productDetailArray = $productArray;
		}
	
		unset($country_code);
		unset($productArray);
	
		return $productDetailArray;
	}
	
	public function getOrderLineDiscountDetail($redeemCoupon) {
		$return  = array();

		foreach ($redeemCoupon as $coupon) {
			$return[$coupon->getOrderItemLineId()] = $coupon;
		}

		return $return;
	}
}
