<?php

namespace OfficeBrain\Bundle\CouponBundle\Manager\Extended;

use OfficeBrain\Bundle\CouponBundle\Form\CouponimportType;
use OfficeBrain\Bundle\CouponBundle\Entity\Coupon;
use OfficeBrain\Bundle\CouponBundle\Entity\CouponLanguage;
use OfficeBrain\Bundle\CouponBundle\Manager\AbstractManager\CouponAbstract as CouponAbstract;
use OfficeBrain\Bundle\SearchBundle\Form\Type\ProductSearchType;
use OfficeBrain\Bundle\SearchBundle\Form\Data\ProductSearchData;
use OfficeBrain\Bundle\SearchBundle\Helper\SearchHelper;

/**
 * @author OfficeBrain 4835 <info@officebrain.com>
 * Description: Business Logic of Coupon Management
 */
class CouponExtended extends CouponAbstract
{
    public function __construct($container, $entityManager, $requestParameters, $country, $language, $emailService, $paginatorService, $formManager, $translatorManager)
    {
        parent:: __construct($container, $entityManager, $requestParameters, $country, $language, $emailService, $paginatorService, $formManager, $translatorManager);
    }

    public function setCouponFields($productTagMaster)
    {
        $productTagMaster->setInstanceId($this->request->get('project_setting')['instance_id']);
        $productTagMaster->setInstanceType($this->request->get('project_setting')['instance_type']);

        return $this->couponRepository->setData($productTagMaster);
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for add Coupon
     *
     * @param1 : form
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function addCoupon($form)
    {
        $formData = $form->getData();
        //echo "<pre>";print_r($formData);die;
        $makeCopyStatus = $this->request->get('makecopy_status');
        $makeCopyCountry = $this->request->get('makecopy_country');
        $couponcode = $formData->getCouponCode();
        $countryId = $formData->getCountryId();
        $prifix = $formData->getCouponPrifix();
        $isautogenerate = $formData->getIsAutogenerate();
        if (isset($isautogenerate) && $isautogenerate == '') {
            $mrgcode = $prifix.$couponcode;
        } else {
            $mrgcode = $couponcode;
        }
        $isexsist = $this->manualCoupon($mrgcode);

        $errorData = $this->customError($form, $isexsist, 'add');
        if (count($errorData) == 0) {
            $this->setCouponFields($formData);
            $couponcode = $formData->setCouponCode($mrgcode);
            $formData->setUsageCount(0);
            $formData->setStatus('A');
            $formData->setIsCsv('N');
            /* Create History */
            $formData->setCreatedAt(new \DateTime());
            $formData->setCreatedUid($this->userId);
            /* Create History */

            /* Language */
            foreach ($formData->getlanguageMapping() as $key => $value) {
                $value->setCountryId($countryId);
                $value->setCouponId($formData);
            }
            $couponObj = $this->couponRepository->setData($formData);

            $this->productMapping($couponObj, 'product');
            $this->productMapping($couponObj, 'exproduct');
            $this->categoryMapping($couponObj, 'category');
            if (count($makeCopyCountry) > 0) {
                foreach ($makeCopyCountry as $countryId) {
                    if (isset($makeCopyStatus[$countryId])) {
                        $this->makeCopyCoupon(clone $couponObj, $countryId, 'A');
                    } else {
                        $this->makeCopyCoupon(clone $couponObj, $countryId, 'D');
                    }
                }
            }
            
            //send email to user
            $userEmail=$formData->getUserEmail();
            if($userEmail != ''){
                $emailParams = array(
                    'couponcode '=>$mrgcode,
                    'amount'=>$formData->getCouponAmount(),
                    'expiry_date'=>$formData->getEndDate()
                );
                $this->sendEmail($emailParams,$userEmail);
            }
               
            $this->couponRepository->commit();
        }

        return $errorData;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for add Coupon
     *
     * @param1 : array
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function processAddForm($errorData)
    {
        $form = $this->getForm();
        $form->handleRequest($this->request);
        $isMultiplecouponFlag = $form->get('isMultiplecoupon')->getData();
        $isGenerateCsv = $form->get('isGenerateCsv')->getData();
        $form = $this->filterFormData($form);

        $this->responseArray = array();

        if ($form->isValid()) {
            if ($isMultiplecouponFlag == '') {
                $errorData = $this->addCoupon($form);
            } else {
                $getData = $this->smartaddCoupon($form);
                if (count($getData[0]) == 0 && $isGenerateCsv != '') {
                    $this->adminCsv($getData[1], $form->getData()->getCountryId());
                    exit;
                }
                $errorData = $getData[0];
            }
            if (count($errorData) == 0) {
                return self::STATUS_SUCCESS;
            }
        }

        $this->responseArray ['id'] = 0;
        $this->responseArray ['form'] = $form->createView();
        $this->responseArray ['mode'] = 'add';
        $this->responseArray ['errorData'] = $errorData;
        $this->responseArray ['selcatlist'] = '';
        $this->responseArray ['catList'] = $this->catList[$this->localization[0]];

        return $this->responseArray;
    }
    
    
    /**
     * @author Employee Id: 4835
     * Description: generate csv
     *
     * @param : ids for get  individual records.
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function adminCsv($ids, $countryId)
    {
        $this->responseArray = $this->processCsv($ids, $countryId);
        $filename = 'export_'.date('Y_m_d_His').'.csv';
        $response = $this->container->get('templating')->renderResponse('OfficeBrainCouponBundle:Admin:couponCsv.html.twig', $this->responseArray);

        return $this->csvDownload($response, $filename);
    }
    
    
    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for edit Coupon
     *
     * @param1 : id
     *
     * @return: data
     *
     * @throws Exception : Null

     */
    public function generateEditForm($id)
    {
        $form = $this->geteditform($id);
        $productData = $this->displayselectedproduct($id);
        $productMapping = $this->productRepository->getproductFromCoupon($id);
        $categoryMapping = $this->categoryRepository->getcategoryFromCoupon($id);
        $categoryArray = array();

        foreach ($categoryMapping as $key => $value) {
            $categoryArray[$value['categoryId']] = $value['categoryId'];
        }

        $this->responseArray ['form'] = $form->createView();
        $this->responseArray ['id'] = $id;
        $this->responseArray ['mode'] = 'edit';
        $this->responseArray ['selcatlist'] = $categoryArray;
        $this->responseArray ['productMapping'] = $productMapping;
        $this->responseArray ['productData'] = $productData[0];
        $this->responseArray ['exproductData'] = $productData[1];
        $this->responseArray ['catList'] = $this->catList[$this->localization[0]];
        $this->responseArray ['errorData'] = array();

        return $this->responseArray;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for edit Coupon
     *
     * @param1 : id
     *
     * @return: array
     *
     * @throws Exception : Null
     */
    public function processEditForm($id)
    {
        $request = $this->request;
        $errorData = array();
        $productMapping = $this->productRepository->getproductFromCoupon($id);
        $categoryMapping = $this->categoryRepository->getcategoryFromCoupon($id);
        $categoryArray = array();

        foreach ($categoryMapping as $key => $value) {
            $categoryArray[$value['categoryId']] = $value['categoryId'];
        }
        $form = $this->geteditform($id);
        $productData = $this->displayselectedproduct($id);
        $form->handleRequest($request);
        $form = $this->filterFormData($form);

        if ($form->isValid()) {
            $errorData = $this->editCoupon($form);
            if (count($errorData) == 0) {
                return self::STATUS_SUCCESS;
            }
        }

        $this->responseArray = array();
        $this->responseArray ['id'] = $id;
        $this->responseArray ['productMapping'] = $productMapping;
        $this->responseArray ['form'] = $form->createView();
        $this->responseArray ['mode'] = 'edit';
        $this->responseArray ['exproductData'] = $productData[1];
        $this->responseArray ['errorData'] = $errorData;
        $this->responseArray ['productData'] = $productData[0];
        $this->responseArray ['selcatlist'] = $categoryArray;
        $this->responseArray ['catList'] = $this->catList[$this->localization[0]];

        return $this->responseArray;
    }

  
    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for edit Coupon
     *
     * @param1 : form
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function editCoupon($form)
    {
        $formData = $form->getData();
        $errorData = $this->customError($form, '', 'edit');
        if (count($errorData) == 0) {
            $couponId = $this->couponRepository->setData($formData);
            $couponObj = $this->entityManager->getRepository('OfficeBrainCouponBundle:Coupon')->find($couponId);
            /* Edit History */
            $couponObj->setUpdatedAt(new \DateTime());
            $couponObj->setUpdatedUid($this->userId);
            /* Edit History */
            $this->productMapping($formData, 'product', $couponId);
            $this->productMapping($formData, 'exproduct', $couponId);
            $this->categoryMapping($formData, 'category', $couponId);

            $this->couponRepository->commit();
        }

        return $errorData;
    }
    
      /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for add Coupon
     *
     * @param1 : form
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function smartaddCoupon($form)
    {
        $isMakeActive = $form->get('isMakeActive')->getData();
        $isGenerateCsv = $form->get('isGenerateCsv')->getData();
        $formData = $form->getData();
        $totalcoupon = $form->get('couponTotal')->getData();
        $couponcode = $formData->getCouponCode();
        $prifix = $formData->getCouponPrifix();
        $countryId = $formData->getCountryId();
        $errorData = $this->customError($form, '', 'add');

        $csvData = array();
        if (count($errorData) == 0 && $totalcoupon > 0) {
            for ($i = 1; $i <= $totalcoupon; ++$i) {
                $couponcode = $this->generateCoupon($prifix);
                $couponcode = $formData->setCouponCode($couponcode);
                $formData->setUsageCount(0);

                if ($isMakeActive == '') {
                    $formData->setStatus('A');    /* A -Active */
                } else {
                    $formData->setStatus('D');    /* D -Disable */
                }

                if ($isGenerateCsv != '') {
                    $formData->setIsCsv('Y');
                } else {
                    $formData->setIsCsv('N');
                }
                $this->setCouponFields($formData);

                /* Create History */
                $formData->setCreatedAt(new \DateTime());
                $formData->setCreatedUid($this->userId);
                /* Create History */

                /* Language */
                foreach ($formData->getlanguageMapping() as $key => $value) {
                    $value->setCountryId($countryId);
                    $value->setCouponId($formData);
                }
                $couponObj = $this->couponRepository->setsmartData($formData);
                array_push($csvData, $couponObj->getId());
                $this->productMapping($couponObj, 'product');

                $this->productMapping($couponObj, 'exproduct');
                $this->categoryMapping($couponObj, 'category');
                $this->couponRepository->smartcommit();
            }
        }

        return array($errorData, $csvData);
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for import Coupon  data to database
     *
     * @param1 : form
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function importaddCoupondata($form)
    {
        $formData = $form->getData();
        $categories = $form->get('category')->getData();
        $products = $form->get('product')->getData();
        $exproducts = $form->get('exproduct')->getData();
        $couponcode = $formData->getCouponCode();
        $countryId = $formData->getCountryId();
        $status = $formData->getStatus();

        $this->setCouponFields($formData);
        if ($couponcode == '') {
            $couponcode = $this->generateCoupon();
        }
        $couponcode = $formData->setCouponCode($couponcode);
        $formData->setUsageCount(0);
        $formData->setStatus($status);
        $formData->setIsCsv('N');
            /* Create History */
            $formData->setCreatedAt(new \DateTime());
        $formData->setCreatedUid($this->userId);
            /* Create History */

        $couponObj = $this->couponRepository->setData($formData);
        //$couponObj->getId();die;
        /* Language */

        foreach ($this->country as $key => $value) {
            if ($value['id'] == $countryId) {
                foreach ($value['language'] as $langid) {
                    $couponLanguage = new CouponLanguage();
                    $couponLanguage->setCountryId($countryId);
                    $couponLanguage->setLanguageId($langid);
                    $couponLanguage->setCouponId($couponObj);
                    $formData->addLanguageMapping($couponLanguage);
                }
            }
        }
        $this->categoryimportMapping($couponObj, $categories);
        $this->productimportMapping($couponObj, $products, 'product');
        $this->productimportMapping($couponObj, $exproducts, 'exproduct');
        
        //send email to user
            $userEmail=$formData->getUserEmail();
            if($userEmail != ''){
                $emailParams = array(
                    'couponcode '=>$couponcode,
                    'amount'=>$formData->getCouponAmount(),
                    'expiry_date'=>$formData->getEndDate()
                );
                $this->sendEmail($emailParams,$userEmail);
            }
        $this->couponRepository->commit();

        return;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for import Coupon  data to database
     *
     * @param1 : form
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function importeditCoupondata($form)
    {
        $formData = $form->getData();
        $couponId = $formData->getId();
        $categories = $form->get('category')->getData();
        $products = $form->get('product')->getData();
        $exproducts = $form->get('exproduct')->getData();

        $couponObj = $this->entityManager->getRepository('OfficeBrainCouponBundle:Coupon')->find($couponId);
        $couponObj->setUpdatedAt(new \DateTime());
        $couponObj->setUpdatedUid($this->userId);

        $this->couponRepository->setData($couponObj);

        $this->categoryimportMapping($couponObj, $categories);
        $this->productimportMapping($couponObj, $products, 'product');
        $this->productimportMapping($couponObj, $exproducts, 'exproduct');

        $this->couponRepository->commit();

        return;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for listing of Coupon
     *
     * @param1 : discountType array
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function listCoupon($discountType)
    {
        $this->pageParameters($discountType);
        $couponList = $this->couponRepository->findCouponList($this->responseArray['countryId'], $this->responseArray['couponType'], $this->responseArray['searchQuery']);

        if (count($couponList)) {
            $paginator = $this->paginatorManager;
            $this->responseArray ['pagination'] = $paginator->paginate($couponList, $this->responseArray['page'], $this->responseArray['records_per_page'], array(), count($couponList));
            unset($couponList);
        }
        $this->responseArray ['languages'] = $this->language;
        return $this->responseArray;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: get all parameters which need for listing
     *
     * @param1 : discountType array
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function pageParameters($discountType)
    {
        $this->responseArray = array();
        $country =$this->request->get('country');
        $this->responseArray['page'] =  $this->request->get('page');
        $this->responseArray['records_per_page'] = $this->recordsPerPage;
        $this->responseArray['discount_type'] = $discountType;
        $this->responseArray['couponType'] = $this->request->get('coupon_type');
        $this->responseArray['countryId'] = $this->country[$country]['id'];
        $this->responseArray['singlecountry'] = $country;
        $this->responseArray['searchQuery'] = $this->request->get('search_query');

    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for remove coupon
     *
     * @param: id
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function removeCoupon($id)
    {
        $couponObj = $this->entityManager->getRepository('OfficeBrainCouponBundle:Coupon')->find($id);
        $couponObj->setDeletedAt(new \DateTime());
        $couponObj->setDeletedUid($this->userId);
        $this->couponRepository->setData($couponObj);
		$this->couponRepository->commit();
        return true;
    }

    public function historyCoupon()
    {
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: custom errors for some fields which dependent to another.
     *
     * @param1 : form
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function customError($form, $isexsist = null, $mode)
    {
        $formData = $form->getData();
        $coupontype = $formData->getCouponType();
        $startDate = $formData->getStartDate();
        $endDate = $formData->getEndDate();
        $selproductids = '';
        $errordata = array();

        if ($mode != 'import') {
            if (count($this->request->get('product')) > 0) {
                $selproductids = implode(',', $this->request->get('product'));
            }
            $productsel = ($selproductids == '') ? $this->request->get('productids') : $selproductids;

            if (($coupontype == 'fixed_product' || $coupontype == 'percent_product') && ($productsel == '')) {
                $errordata['productError'] = $this->translator->trans('admin.productsel');
            }
        }

        if ($isexsist > 0) {
            $errordata['errors_couponCode'] = $this->translator->trans('admin.duplicate');
        }
        if ($mode == 'add') {
            $isMakeActive = $form->get('isMakeActive')->getData();
            $couponTotal = $form->get('couponTotal')->getData();
            if ($isMakeActive != '' && $couponTotal == '') {
                $errordata['errors_generateCoupon'] = $this->translator->trans('admin.generate_coupon');
            }
        }

        if ($startDate != '' && $endDate != '') {
            if ($startDate > $endDate) {
                $errordata['errors_date'] = $this->translator->trans('admin.valid.datepair');
            }
        }

        return $errordata;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: custom errors for some fields which dependent to another.
     *
     * @param1 : form
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function customimportError($form)
    {
        $formData = $form->getData();
        $coupontype = $formData->getCouponType();
        $couponamount = $formData->getCouponAmount();
        $startDate = $formData->getStartDate();
        $endDate = $formData->getEndDate();
        $couponCode = trim($formData->getcouponCode());
        $standardLength = $this->couponConfigParameter['option']['couponcode_length'];
        $selproductids = '';

        if ($couponCode != '' && ($standardLength != strlen($couponCode))) {
            $form->get('couponCode')->addError(new \Symfony\Component\Form\FormError($this->translator->trans('admin.length_coupon')));
        }

        if ($startDate != '' && $endDate != '') {
            if ($startDate > $endDate) {
                $form->get('endDate')->addError(new \Symfony\Component\Form\FormError($this->translator->trans('admin.valid.datepair')));
            }
        }

        if (($coupontype == 'percent' || $coupontype == 'percent_product') && $couponamount > 100) {
            $form->get('couponAmount')->addError(new \Symfony\Component\Form\FormError($this->translator->trans('admin.valid_percentage')));
        }

        return $form;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description:  make copy coupons for another countries.
     *
     * @param1 : form
     * @param2 : country
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function makeCopyCoupon($formData, $countryId, $isActive)
    {
        $formData->setId(null);
        if ($countryId) {
            $this->setCouponFields($formData);
            $couponcode = $this->generateCoupon();

            $formData->setCouponCode($couponcode);
            $formData->setUsageCount(0);
            $formData->setStatus($isActive);
            $formData->setIsCsv('N');

            /* Create History */
            $formData->setCreatedAt(new \DateTime());
            $formData->setCreatedUid('1');
            /* Create History */

            $formData->setCountryId($countryId);

            $countryCode = $this->getCountryField($countryId, 'id', 'code');
            $coupontitle = $formData->getLanguageMapping()->first()->getCouponTitle();
            $couponDescription = $formData->getLanguageMapping()->first()->getCouponDescription();
            foreach ($formData->getLanguageMapping() as $langMap) {
                $formData->removeLanguageMapping($langMap);
            }

            foreach ($this->country[$countryCode]['language'] as $languageId) {
                $CouponLanguageCopy = new CouponLanguage();
                $CouponLanguageCopy->setLanguageId($languageId);
                $CouponLanguageCopy->setCountryId($countryId);
                $CouponLanguageCopy->setCouponTitle($coupontitle);
                $CouponLanguageCopy->setCouponDescription($couponDescription);
                $CouponLanguageCopy->setCouponId($formData);
                $formData->addLanguageMapping($CouponLanguageCopy);
            }
            $this->couponRepository->setData($formData);
        }
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: Copy of Coupon
     *
     * @param1 : NULL
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function copycoupons()
    {
        $id = $this->request->get('coupon_id');

        if ($id) {
            $couponObj = $this->couponRepository->find($id);

            if ($couponObj) {
                if ($this->request->get('makecopy_status') != '') {
                    $makeCopyStatus = $this->request->get('makecopy_status');
                } else {
                    $makeCopyStatus = array();
                }
                $makeCopyCountry = $this->request->get('makecopy_country');

                if (count($makeCopyCountry) > 0) {
                    foreach ($makeCopyCountry as $countryId) {
                        if (in_array($countryId, $makeCopyStatus)) {
                            $this->makeCopyCoupon(clone $couponObj, $countryId, 'A');
                        } else {
                            $this->makeCopyCoupon(clone $couponObj, $countryId, 'D');
                        }
                    }

                    // commit persist objects if any
                  return  $this->couponRepository->commit();
                } else {
                    return self::STATUS_ERROR;
                }
            }
        }
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description:  provess for csv.
     *
     * @param1 : ids
     * @param2 : country
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function processCsv($ids, $countryId)
    {
        $resultData = $this->couponRepository->findCouponCsv($ids);
        $header = $this->container->getParameter('csvFields');

       //--add coupon title in csv header
        foreach ($this->country as $key => $value) {
            //$countryCounter=0;
             if ($value['id'] == $countryId) {
                 foreach ($value['language'] as $id => $name) {
                     $countryName = $value['name'];

            //$header['couponTitle-'.$countryCounter]='Coupon Title-'.$this->language[$id]['name'];
            //$countryCounter++;
                 }
             }
        }

        $this->responseArray = array();
        $this->responseArray['countryName'] = $countryName;
        $this->responseArray['resultData'] = $resultData;
        $this->responseArray['csvheader'] = $header;

        return $this->responseArray;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description:  upload csv
     *
     * @param1 : csvpath
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function uploadcsv($csv_path)
    {
        $uploadFilePath = $csv_path;
        $header = $this->container->getParameter('csvFields');

        if (!IS_DIR($uploadFilePath)) {
            mkdir($uploadFilePath, 0777, true);
            chmod($uploadFilePath, 755);
        }
        $maxSizeUploadFromIni = intval(ini_get('upload_max_filesize'));
        $maxSizeUpload = ($maxSizeUploadFromIni > 5) ? 5 : $maxSizeUploadFromIni;
        $allwedMimeType = array('application/csv', 'text/csv');

        foreach ($_FILES as $file) {
            $this->responseArray = array();

            $this->responseArray['importError'] = '';
            if ($file['name'] == '') {
                $this->responseArray['importError'] = $this->translator->trans('admin.valid_csv');
            } elseif (!in_array($file['type'], $allwedMimeType)) {
                $this->responseArray['importError'] = $this->translator->trans('admin.valid_csv');
            } else {
                $logoFile = time().'_'.$file['name'];

                if (move_uploaded_file($file['tmp_name'], $uploadFilePath.$logoFile)) {
                    chmod($uploadFilePath.$logoFile, 0775);

                    $file = fopen($uploadFilePath.$logoFile, 'r');
                    $csvImportArray = array();

                    while (!feof($file)) {
                        $csvImportArray[] = fgetcsv($file);
                    }

                    fclose($file);
                    $this->responseArray['newImportArray'] = array();

                /*foreach($csvImportArray[0] as $key => $value)
                    {
                         if(preg_match("/^Coupon Title/",$value))
                         {
                              unset($csvImportArray[0][$key]);
                         }
                    }*/

                $csvImportArray[0] = array_map('trim', $csvImportArray[0]);
                    $headervalueArray = array_map('trim', array_values($header));
                    $diffresult = array_diff($headervalueArray, $csvImportArray[0]);
                //echo "<pre>";print_r($diffresult);die;
                if (count($diffresult) > 0) {
                  $this->responseArray['importError'] = $this->translator->trans('admin.csv.validfile');
                  return $this->responseArray;
                }
                
                    if (count($csvImportArray) > 2) {
                        $newImportArray = array();

                        for ($i = 1; $i < count($csvImportArray); ++$i) {
                            if (count($csvImportArray[$i]) > 1) {
                                $newImportArray[$i] = $this->headerRawMapping($csvImportArray[0], $csvImportArray[$i]);
                            }
                        }

                        $this->responseArray['newImportArray'] = $newImportArray;

                        $this->responseArray['sucessMsg'] = $this->translator->trans('admin.csv.sucess');
                    } else {
                        $this->responseArray['importError'] = $this->translator->trans('admin.csv.validfile');
                    }

                    @unlink($uploadFilePath.$logoFile);
                }
            }
        }

        return $this->responseArray;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description:  mapping of header and raw
     *
     * @param1 : header
     * @param2 : raws
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function headerRawMapping($header, $content)
    {
        $header = $this->container->getParameter('csvFields');
        $mapArray = array();
        $header = array_map('trim', $header);
        $content = array_map('trim', $content);
        $counter = 0;
        foreach ($header as  $key => $value) {
            if ($key == 'isFreeShipping' || $key == 'isBeforeTax' || $key == 'isSaleItem') {
                $mapArray[$key] = ($content[$counter] == 'Yes') ? true : false;
            } elseif ($key == 'countryId') {
                $countryId = 0;
                foreach ($this->country as $id => $field) {
                    if ($field['name'] == trim($content[$counter])) {
                        $countryId = $field['id'];
                        break;
                    }
                }
                $mapArray[$key] = $countryId;
            } elseif ($key == 'status') {
                $mapArray[$key] = (trim($content[$counter]) === 'Deactive') ? 'D' : 'A';
            } else {
                $mapArray[$key] = $content[$counter];
            }
            ++$counter;
        }

        return $mapArray;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description:  sample csv file download
     *
     * @param1 : response
     * @param2 : filename
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function csvDownload($response, $filename)
    {
        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'text/csv');
        $response->headers->set('Content-Description', 'Submissions Export');
        $response->headers->set('Content-Disposition', 'attachment; filename='.$filename);
        $response->headers->set('Content-Transfer-Encoding', 'binary');
        $response->headers->set('Pragma', 'no-cache');
        $response->headers->set('Expires', '0');

        //$response->prepare();
        $response->sendHeaders();
        $response->sendContent();
        //echo $filename;
        return $response;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: get object from coupon code
     *
     * @param1 : couponcode
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function getFromCoupocode($couponcode)
    {
        return $couponObj = $this->couponRepository->findFromCouponCode($couponcode);
    }

    /**
     * @author Employee Id: 4835
     * Description :process form for import csv.
     *
     * @param1 : NULL
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function processimport()
    {
        $request = $this->request;
        $errorData = $this->uploadcsv($this->csvPath);
        
        $this->responseArray = $errorData;
        $unsavedRaw = 0;
        $totalRaw = 0;
        $errorImportData = array();

        if (isset($errorData['newImportArray']) && count($errorData['newImportArray']) > 0) {
            $notImportedRaw = array();

            foreach ($errorData['newImportArray'] as $key => $newImportArray) {
                $couponMaster = '';
                if (isset($newImportArray['couponCode']) && ($newImportArray['couponCode'] != '')) {
                    $couponMaster = $this->getFromCoupocode($newImportArray['couponCode']);
                }
                if ($couponMaster != null or $couponMaster != '') {
                    $couponObj = $couponMaster;
                    $couponTypeObj = new CouponimportType($this->container, 'edit');
                    $flag = 'edit';
                } else {
                    $couponObj = new Coupon();
                    $couponTypeObj = new CouponimportType($this->container, 'add');
                    $flag = 'add';
                }

                $form = $this->formManager->create($couponTypeObj, $couponObj);
                $form->bind($newImportArray);
                $form = $this->customimportError($form);

                if ($form->isValid()) {
                    if ($flag == 'add') {
                        $errorImportData = $this->importaddCoupondata($form);
                    }
                    {
                      $errorImportData = $this->importeditCoupondata($form);
                    }
                } else {
                    echo $form->getErrorsAsString().'<br/>';
                    $notImportedRaw[$key] = $form->getErrorsAsString();
                    ++$unsavedRaw;
                }

                ++$totalRaw;

                $msg = '';
                if ($unsavedRaw > 0) {
                    $msg = $unsavedRaw.'/'.$totalRaw.$this->translator->trans('admin.valid.recordnotsave');
                }

                $this->responseArray['errorImportMsg'] = $msg;
            }
           $this->responseArray['unsavedRaw'] = $unsavedRaw;  
        }

       
        //echo "<pre>";print_r($this->responseArray);die;
        return $this->responseArray;
    }

    /**
     * @author Employee Id: 4835
     *
     * @param : searchParam for searching specific records.
     * Description: get product array from solr
     *
     * @param1 : searchparameters
     * @return: data
     *
     * @throws Exception : Null
     */
    public function getProduct($searchParam = null)
    {
        $productSearchForm = new ProductSearchType();
        $searchHelper = new SearchHelper($this->request,$this->container);

        // $this->request = $this->getRequest ();
        $getFacet = $this->request->get('facet', 'no');
        $language = 'en';

        if ($language == 'fr') {
            $language = '3';
        } else {
            $language = '1';
        }

        $mainFilter = $this->request->get('main_filter', 'keyword');
        $search = $searchParam; // $this->request->get("product_search");
        $finalRequest = array(
            $mainFilter => $search,
        );
        $productSearch = new ProductSearchData($this->entityManager, $language);
        $form = $this->formManager->create($productSearchForm, $productSearch, array(
            'csrf_protection' => false,
        ));
        $form->bind($finalRequest);

        if ($form->isValid()) {
            $productSearchData = $form->getData();
            //$productDetailArray = $this->container->get('office_brain_search_manager')->searchResult($productSearchData, $getFacet, $searchHelper);
            $productDetailArray = $this->container->get('office_brain_search_manager')->searchResult($productSearchData, false);

            return $productDetailArray['search_result_array'] ['data'];
        }
    }

    /**
     * @author Employee Id: 4835
     * Description: get array for display selected products in edit page
     *
     * @param : id for get  individual record.
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function displayselectedproduct($id)
    {
        $couponProductObj = $this->productRepository->getproductFromCoupon($id);
        $productidArray = array();
        $exproductidArray = array();

        foreach ($couponProductObj as $product) {
            $sku = $product->getProductSku();
            $productid = $product->getProductId();
            $isAllowed = $product->getIsAllowed();
            $productData = $this->getProduct($sku);
            //echo "<pre>";print_r($productData);die;
            if (count($productData) > 0) {
                if ($isAllowed == 'Y') {
                    $comproduct = $productid.'|'.$sku;
                    $productidArray[$comproduct] = $productData[0]['title'];
                } else {
                    $comproduct = $productid.'|'.$sku;
                    $exproductidArray[$comproduct] = $productData[0]['title'];
                }
            }
        }

        return array($productidArray, $exproductidArray);
    }

    
     /**
     * @author Employee Id: 4835
     * Description: get Details of specific coupon
     *     
     * @param : ids for get  individual records.
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function viewCouoponDetails($id){
       return $couponObj=$this->couponRepository->findCouponView($id);
        
    }
}
