<?php

namespace OfficeBrain\Bundle\CouponBundle\Manager\AbstractManager;

use OfficeBrain\Bundle\CouponBundle\Form\CouponType;
use OfficeBrain\Bundle\CouponBundle\Entity\Coupon;
use OfficeBrain\Bundle\CouponBundle\Entity\CouponLanguage;
use OfficeBrain\Bundle\CouponBundle\Entity\CouponProductMapping;
use OfficeBrain\Bundle\CouponBundle\Entity\CouponCategoryMapping;

abstract class CouponAbstract
{
    const STATUS_ERROR = 'error';
    const STATUS_SUCCESS = 'success';
    const STATUS_ERROR_MESSAGE = 'error_message';
    const STATUS_SUCCESS_MESSAGE = 'success_message';

    protected $couponRepository;
    protected $couponlangRepository;
    protected $productRepository;
    protected $categoryRepository;
    protected $entityManager;
    protected $session;
    protected $request;
    protected $projectSetting;
    protected $instanceId;
    protected $instanceType;
    protected $userId;
    protected $cultureId;
    protected $cultureCode;
    protected $configurationRule;
    protected $createdUid;
    protected $upatedUid;
    protected $sessionProductId;
    protected $sessionInstanceKey;
    protected $emailService;
    protected $recordsPerPage;
    protected $paginatorManager;
    protected $formManager;
    protected $translatorManager;

    public function __construct($container, $entityManager, $requestParameters, $country, $language, $emailService, $paginatorService, $formManager, $translatorManager)
    {
        $this->request = $requestParameters;
        $this->entityManager = $entityManager;
        $this->paginatorManager = $paginatorService;
        $this->country = $country;
        $this->language = $language;
        $this->container = $container;
        $this->projectSetting = $this->request->get('project_setting');
        $this->instanceId = $this->projectSetting['instance_id'];
        $this->instanceType = $this->projectSetting['instance_type'];
        $this->userId = $this->projectSetting['user_id'];
        $this->cultureId = $this->projectSetting['culture_id'];
        $this->cultureCode = $this->projectSetting['culture_code'];
        $this->couponRepository = $this->entityManager->getRepository('OfficeBrainCouponBundle:Coupon');
        $this->couponlangRepository = $this->entityManager->getRepository('OfficeBrainCouponBundle:CouponLanguage');
        $this->productRepository = $this->entityManager->getRepository('OfficeBrainCouponBundle:CouponProductMapping');
        $this->categoryRepository = $this->entityManager->getRepository('OfficeBrainCouponBundle:CouponCategoryMapping');
        $this->couponConfigParameter = $this->projectSetting['configuration_rule']['promo_discount']['option']['coupon'];
        $this->csvPath = $this->container->getParameter('coupon.csv_path');
        $this->translator = $translatorManager;
        $this->prodctCategory = $this->container->get('officebrain_category_api_manager');
        $this->localization = $this->container->getParameter('localization_to_fetch');
        $this->catList = $this->prodctCategory->getList($this->localization[0]);
        $this->couponRepository->setProjectSetting($this->projectSetting);
        $this->emailService = $emailService;
        $this->recordsPerPage = $this->couponConfigParameter['option']['record_per_page']['status'];
        $this->formManager = $formManager;
    }

    public function addCoupon($form)
    {
    }

    public function viewCoupon()
    {
    }

    public function removeCoupon($id)
    {
    }

    public function historyCoupon()
    {
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description:  for generate form.
     *
     * @param : NULL
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function getForm()
    {
        $couponObj = new Coupon();
        $language = $this->language;
        foreach ($language as $key => $value) {
            $langid = $value['id'];
            $couponLang = new CouponLanguage();
            $couponLang->setLanguageId($langid);
            $couponObj->getlanguageMapping()[] = $couponLang;
        }
        $couponTypeObj = new CouponType($this->container, 'add');

        return $this->formManager->create($couponTypeObj, $couponObj);
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description:  for generate edit form.
     *
     * @param : NULL
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function geteditForm($id)
    {
        $couponMaster = $this->couponRepository->find($id);
        $form = $this->formManager->create(new CouponType($this->container, 'edit'), $couponMaster);

        return $form;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for check rendom couponcode exisist or not in database
     * @return: array
     */
    public function generateCoupon($prfix = null)
    {
        $standardlength = $this->couponConfigParameter['option']['couponcode_length'];
        $prilen = ($prfix == '') ? 0 : strlen($prfix);
        $length = $standardlength - $prilen;
        $randomcode = $this->randomPrefix($length);
        $mrgecode = $prfix.$randomcode;

        $isExist = $this->entityManager->getRepository('OfficeBrainCouponBundle:Coupon')->chkCodeExsitorNot($mrgecode);
        if ($isExist == 0) {
            return $mrgecode;
        } else {
            $this->generateCoupon($prfix);
        }
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for check custom couponcode exisist or not in database
     *
     * @param : NULL
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function manualCoupon($mrgcode)
    {
        $isExist = $this->entityManager->getRepository('OfficeBrainCouponBundle:Coupon')->chkCodeExsitorNot($mrgcode);

        return $isExist;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: generate  random coupon
     *
     * @param: length for coupon code
     *
     * @return: couponcode
     *
     * @throws Exception : Null
     */
    public function randomPrefix($length)
    {
        $random = '';

        srand((double) microtime() * 1000000);

        $data = 'AbcDE123IJKLMN67QRSTUVWXYZ';
        $data .= 'aBCdefghijklmn123opq45rs67tuv89wxyz';
        $data .= '0FGH45OP89';

        for ($i = 0; $i < $length; ++$i ) {
            $random .= substr($data, (rand() % (strlen($data))), 1);
        }

        return $random;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * @param: productids for save/update in table
     *
     * Description: for product mapping
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function productMapping($formData, $type, $couponId = null)
    {
        $countryId = $formData->getCountryId();
        if ($type == 'product') {
            $productids = $this->request->get('productids');
        } else {
            $productids = $this->request->get('ex_productids');
        }
        if ($productids != '') {
            $productArray = explode(',', $productids);
            $isAllowed = ($type == 'product') ? 'Y' : 'N';

            if ($couponId != null) {
                $couponObj = $this->productRepository->getproductFromCoupon($couponId, $isAllowed);
                $productidArray = array();
                foreach ($couponObj as $coupon) {
                    $productMappingId = $coupon->getId();
                    array_push($productidArray, $productMappingId);
                }
                $this->productRepository->removeData($productidArray);
            }
            foreach ($productArray as $key) {
                $keyArray = explode('|', $key);
                $productMapppingObj = new CouponProductMapping();
                $productMapppingObj->setProductId($keyArray[0]);
                $productMapppingObj->setProductSku($keyArray[1]);
                $productMapppingObj->setCouponId($formData);
                $productMapppingObj->setIsAllowed($isAllowed);
                $productMapppingObj->setCountryId($countryId);
                $this->productRepository->setData($productMapppingObj);
            }
        }
        return;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * @param: productids for save/update in table
     *
     * Description: for import product mapping for save/update in database
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function productimportMapping($couponObj, $products, $type)
    {
        if ($products != '') {
            $productArray = explode('|', $products);
            $countryId = $couponObj->getCountryId();
            $couponId = $couponObj->getId();

            if ($type == 'product') {
                $productids = $this->request->get('productids');
            } else {
                $productids = $this->request->get('ex_productids');
            }
            $isAllowed = ($type == 'product') ? 'Y' : 'N';
            if ($couponId != null) {
                $couponImportObj = $this->productRepository->getproductFromCoupon($couponId, $isAllowed);
                $productidArray = array();
                foreach ($couponImportObj as $coupon) {
                    $productMappingId = $coupon->getId();
                    array_push($productidArray, $productMappingId);
                }

                $this->productRepository->removeData($productidArray);
            }
            foreach ($productArray as $key) {
                if (trim($key) != '') {
                    $productData = $this->getProduct($key);
                    if (count($productData) > 0) {
                        $productMapppingObj = new CouponProductMapping();
                        //$productMapppingObj->setProductId($keyArray[0]);
                        $productMapppingObj->setProductSku($key);
                        $productMapppingObj->setCouponId($couponObj);
                        $productMapppingObj->setIsAllowed($isAllowed);
                        $productMapppingObj->setCountryId($countryId);
                        $this->productRepository->setData($productMapppingObj);
                    }
                }
            }
        }

        return;
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for product mapping
     *
     * @param: categoryids for save/update in table
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function categoryMapping($formData, $type, $couponId = null)
    {
        $categoryids = $this->request->get('categoryids');
        if($categoryids == ''){
            $categoryArray=$this->request->get('category');
            
        }else{
         $categoryArray = explode(',', $categoryids);   
        }
        $countryId = $formData->getCountryId();
        if ($couponId != null) {
            $CategoryObj = $this->categoryRepository->getcategoriesFromCouponId($couponId);
            $couponidArray = array();
            foreach ($CategoryObj as $category) {
                $categoryMappingId = $category->getId();
                array_push($couponidArray, $categoryMappingId);
            }

            $this->categoryRepository->removeData($couponidArray);
        }
        if(count($categoryArray) > 0){
        foreach ($categoryArray as $key) {
            $categoryMapppingObj = new CouponCategoryMapping();
            $categoryMapppingObj->setCategoryId($key);
            $categoryMapppingObj->setCouponId($formData);
            $categoryMapppingObj->setCountryId($countryId);
            $this->categoryRepository->setData($categoryMapppingObj);
        }
        }
    }

    /**
     * @author OfficeBrain 4835 <info@officebrain.com>
     * Description: for product mapping
     *
     * @param: import categoryids for save/update in table
     *
     * @return: data
     *
     * @throws Exception : Null
     */
    public function categoryimportMapping($couponObj, $category)
    {
        $categoryids = $category;
        if ($categoryids != '') {
            $categoryArray = explode('|', $categoryids);
            $countryId = $couponObj->getCountryId();
            $couponId = $couponObj->getId();
            if ($couponId != null) {
                $CategoryObj = $this->categoryRepository->getcategoriesFromCouponId($couponId);
                $couponidArray = array();
                foreach ($CategoryObj as $category) {
                    $categoryMappingId = $category->getId();
                    array_push($couponidArray, $categoryMappingId);
                }

                $this->categoryRepository->removeData($couponidArray);
            }
            if (count($categoryArray) > 0) {
                foreach ($categoryArray as $key) {
                    if (trim($key) != '') {
                        $categoryMapppingObj = new CouponCategoryMapping();
                        $categoryMapppingObj->setCategoryId($key);
                        $categoryMapppingObj->setCouponId($couponObj);
                        $categoryMapppingObj->setCountryId($countryId);
                        $this->categoryRepository->setData($categoryMapppingObj);
                    }
                }
            }
        }

        return;
    }

    /**
     * @author Employee Id: 4835
     * Description :get configuration parameters
     *
     * @param: null
     *
     * @return: data
     *
     * @throws Exception : Null
     * */
    public function getConfigParameters()
    {
        return $this->request->get('project_setting');
    }

    /**
     * @author Employee Id: 4835
     * Description : filter form data
     *
     * @return: data
     *
     * @throws Exception : Null
     * */
    public function filterFormData($form)
    {
        $coupon = $form->getData();
        $data = array();
        $countryId = $coupon->getCountryId();
        if ($countryId) {
            $countryCode = $this->getCountryField($countryId, 'id', 'code');

            foreach ($coupon->getLanguageMapping() as $key => $language) {
                if (!in_array($language->getLanguageId(), $this->country[$countryCode]['language'])) {
                    unset($coupon->getLanguageMapping()[$key]);
                } else {
                    if ($language->getcouponTitle() == '') {
                        $form->get('languageMapping')[$key]->get('couponTitle')->addError(new \Symfony\Component\Form\FormError($this->translator->trans('admin.blank_coupon_title')));
                    }
                }
            }
        }

        return $form;
    }

    /**
     * @author Employee Id: 4835
     * Description : get country filed
     *
     * @param 1 : string $culture
     * @param 2 : string $searchField
     * @param 3 : string $returnField
     * @param 4 : array  $countries
     *
     * @return: data
     *
     * @throws Exception : Null
     * */
    public function getCountryField($culture, $searchField, $returnField)
    {
        $countries = $this->country;
        foreach ($countries as $key => $country) {
            if ($culture == $country[$searchField]) {
                if ($returnField != 'code') {
                    return $country[$returnField];
                } else {
                    return $key;
                }
            }
        }
    }

    /**
     * @author Employee Id: 4835
     * Description : get locale from country array
     *
     * @param 1 : string $culture
     * @param 2 : string $searchField
     * @param 3 : string $returnField
     * @param 4 : array  $countries
     *
     * @return: data
     *
     * @throws Exception : Null
     * */
    public function getlocaleFromCountryId($countryId)
    {
        $countries = $this->country;
        if (count($countries) > 0) {
            foreach ($countries as $key => $country) {
                if ($country['id'] == $countryId) {
                    $localeArray = array($country['short_name'], $country['language']);
                    break;
                }
            }
            $localization = array();
            foreach ($localeArray[1] as $key => $value) {
                $local = $key.'_'.$localeArray[0];
                array_push($localization, $local);
                break;
            }

            return $localization;
        }
    }
    
    /**
     * @author Employee Id: 4835
     * Description : send mail to user
     *
     * @param 1 : array $emailParams
     * @param 2 : string $userEmail
  
     * @return: data
     *
     * @throws Exception : Null
     * */
    public function sendEmail($emailParams,$userEmail){
        
         return  $this->emailService->sendMail("coupon_approval_email",$userEmail, $emailParams);
     }
    
}
