<?php

namespace OfficeBrain\Bundle\ServiceGroupBundle\Manager\Extended;

use OfficeBrain\Bundle\ServiceGroupBundle\Manager\AbstractManager\ServiceGroupAbstract as ServiceGroupAbstract;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceGroup;
use OfficeBrain\Bundle\ServiceGroupBundle\Entity\ServiceGroupLanguage;

/**
 * @author OfficeBrain 4589 <info@officebrain.com>
 *
 * Description : Service Group Extended Class
 */
class ServiceGroupAdminExtended extends ServiceGroupAbstract
{
    protected $serviceGroupLanguageRepo;

    public function __construct($entityManager, $request, $session, $serviceContainer, $countries, $languages, $translator, $coreManager)
    {
        parent::__construct($entityManager, $request, $session, $serviceContainer, $countries, $languages, $translator, $coreManager);
        $this->serviceGroupLanguageRepo = $this->entityManager->getRepository('OfficeBrainServiceGroupBundle:ServiceGroupLanguage')
                                                ->setProjectSetting($this->projectSetting);
    }

    public function __destruct()
    {
        unset($this->serviceGroupLanguageRepo);
        parent::__destruct();
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Blank Service Group Object.
     *
     * @param 1 : No Parameter
     *
     * @return type : Service Group Object
     *
     * @throws Exception: Null
     */
    public function getBlankObject()
    {
        $serviceGroupObj = new ServiceGroup();
        $language = $this->languages;

        foreach ($language as $key => $value) {
            $langid = $value['id'];
            $serviceGroupLangObj = new ServiceGroupLanguage();
            $serviceGroupLangObj->setLanguageId($langid);
            $serviceGroupObj->getlanguageMapping()[] = $serviceGroupLangObj;
        }

        return $serviceGroupObj;
    }

    /**
     * @author Employee Id: 4589
     * Description : Set Service group.
     *
     * @param 1 : object $form
     * @param 2 : int    $id
     *
     * @return type : Messages
     *
     * @throws Exception: Null
     */
    public function setServiceGroup($form, $id = null)
    {
        $isEdit = false;
        if ($id && $id != null) {
            $serviceGroupOld = $this->getServiceGroupById($id);
            $isEdit = true;
        }

        $serviceGroup = $form->getData();

        $serviceGroup->setInstanceId($this->instanceId);
        $serviceGroup->setInstanceType($this->instanceType);

        $languageMapping = $serviceGroup->getLanguageMapping();

        $countryId = $serviceGroup->getCountryId();
        $existFlag = false;

        $loggedInUserId = 1;

        foreach ($languageMapping as $language) {
            $languageId = $language->getLanguageId();
            $groupName = $language->getGroupName();
            if ($groupName != '') {
                if (isset($serviceGroupOld)) {
                    foreach ($serviceGroupOld->getLanguageMapping() as $languageOld) {
                        if ($languageOld->getLanguageId() == $languageId && $groupName != $languageOld->getGroupName()) {
                            $groupNameExist = $this->serviceGroupLanguageRepo->getCountServiceGroupExist($groupName, $languageId, $countryId);
                            if ($groupNameExist != 0) {
                                $existFlag = true;
                                break;
                            }
                        }
                    }
                } else {
                    $groupNameExist = $this->serviceGroupLanguageRepo->getCountServiceGroupExist($groupName, $languageId, $countryId);
                    if ($groupNameExist != 0) {
                        $existFlag = true;
                        break;
                    }
                }

                if ($existFlag) {
                    break;
                }

                $language->setServiceGroup($serviceGroup);
            }
        }

        if ($languageMapping->isEmpty()) {
            // Clear persist objects if any
            $this->serviceGroupRepo->clear();

            $resultArray = array('error_message' => 'admin.service_group_management.service_group.group_name.not_blank');
        } elseif ($existFlag) {
            // Clear persist objects if any
            $this->serviceGroupRepo->clear();

            $resultArray = array('error_message' => 'admin.service_group_management.service_group.group_name.duplicate');
        } else {
            $serviceGroup = $this->serviceGroupRepo->addServiceGroup($serviceGroup, $loggedInUserId, $id);
            if (!$isEdit) {
                $make_copy_country = $this->request->request->get('make_copy_country');
                $make_copy_status = $this->request->request->get('make_copy_status');

                if ($make_copy_country) {
                    foreach ($make_copy_country as $countryId => $value) {
                        if (isset($make_copy_status[$countryId])) {
                            $this->makeCopyServiceGroup(clone $serviceGroup, $countryId, true);
                        } else {
                            $this->makeCopyServiceGroup(clone $serviceGroup, $countryId, false);
                        }
                    }
                }
            }

            // commit persist objects if any
            $this->serviceGroupRepo->commit();
            if ($isEdit) {
                $resultArray = array('success_message' => 'admin.service_group_management.service_group.edit_message');
            } else {
                $resultArray = array('success_message' => 'admin.service_group_management.service_group.add_message');
            }
        }

        return $resultArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Service group list.
     *
     * @param 1 : Search Query
     * @param 2 : Country Code
     * @param 3 : Language Code
     *
     * @return type : Service group list Array
     *
     * @throws Exception: Null
     */
    public function getServiceGroupList()
    {
        $serviceGroupArray = array();
        $serviceGroupResults = array();

        $param = $this->request->get('_route_params');
        $searchQuery = $this->request->get('search_query', '');

        $page = $param['page'];

        $countryId = $this->request->get('countryId', $this->countryId);

        $serviceGroupArray = $this->serviceGroupRepo->getServiceGroupList($countryId, null, $searchQuery);

        if (!empty($serviceGroupArray)) {
            $i = 0;
            foreach ($serviceGroupArray as $recordKey => $recordValue) {
                $serviceGroupResults[$i]['id'] = $recordValue['id'];
                $serviceGroupResults[$i]['culture'] = $this->culture;

                foreach ($recordValue['languageMapping'] as $lang) {
                    $serviceGroupResults[$i]['group_name'][$lang['languageId']] = $lang['groupName'];
                }
                $serviceGroupResults[$i]['language_mapping'] = $recordValue['languageMapping'];

                $serviceGroupResults[$i]['status'] = $recordValue['status'];
                $serviceGroupResults[$i]['isDefault'] = $recordValue['isDefault'];
                $serviceGroupResults[$i]['created_at'] = $recordValue['createdAt'];
                $serviceGroupResults[$i]['updated_at'] = $recordValue['updatedAt'];
                //$serviceGroupResults[$i]['deleted_at'] = $recordValue['deleted_at'];
                ++$i;
            }
        }

        $records_per_page = $this->projectSetting['configuration_rule']['promo_discount']['option']['service_group']['option']['no_of_record_per_page'];

        if (count($serviceGroupResults) > 0) {
            $data['product'] = $serviceGroupResults;
            $data['pagination'] = $this->paginatorService->paginate($serviceGroupResults, $page, $records_per_page, array(), count($serviceGroupResults));
        }

        $data['records_per_page'] = $records_per_page;
        $data['page'] = $page;
        $data['culture'] = $this->culture;
        $data['languageCode'] = $this->languageCode;
        $data['countryCode'] = $this->getCountryField($countryId, "id", "code");
        $data['search_query'] = $searchQuery;

        return $data;
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Service group list filter by countryId.
     *
     * @param 2 : Country Code
     *
     * @return type : Service group list Array
     *
     * @throws Exception: Null
     */
    public function getServiceGroupListFilter()
    {
        $countryId = $this->request->get('countryId', $this->countryId);

        $serviceGroupFilter = $this->serviceGroupRepo->getServiceGroupList($countryId, $this->languageId);

        $serviceGroupArray = array();
        foreach ($serviceGroupFilter as $serviceGroup) {
            $serviceGroupArray[$serviceGroup['languageMapping'][0]['id']] = $serviceGroup['languageMapping'][0]['groupName'];
        }

        return $serviceGroupArray;
    }

    /**
     * @author Employee Id: 4589
     * Description : Fetch Service group.
     *
     * @param 1 : Search Query
     *
     * @return type : Service group
     *
     * @throws Exception: Null
     */
    public function getFetchServiceGroup()
    {
        $searchQuery = $this->request->get('search_query', '');
        $serviceGroupResults = $this->getServiceGroupById();
        $data['items'] = $serviceGroupResults;
        $data['culture'] = $this->culture;
        $data['languageCode'] = $this->languageCode;
        $data['countryCode'] = $this->countryCode;
        $data['search_query'] = $searchQuery;

        return $data;
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Service group by Id.
     *
     * @param 1 : Service Group Id
     *
     * @return type : Service group
     *
     * @throws Exception: Null
     */
    public function getServiceGroupById($id = null)
    {
        $serviceGroupArray = array();
        $serviceGroupResults = array();

        if ($id) {
            return $this->serviceGroupRepo->find($id);
        } else {
            $id = $this->request->get('id');
        }

        $serviceGroupArray = $this->serviceGroupRepo->getServiceGroupById($id);

        if (!empty($serviceGroupArray)) {
            foreach ($serviceGroupArray as $recordKey => $recordValue) {
                //$countryCode = $this->getCountryField($recordValue['countryId'], 'id', 'code', $this->countries);
                //$languageCode = $this->getCountryField($recordValue['languageId'], 'id', 'code', $this->languages);

                    $serviceGroupResults['id'] = $recordValue['id'];
                foreach ($recordValue['languageMapping'] as $lang) {
                    $serviceGroupResults['group_name'][$lang['languageId']] = $lang['groupName'];
                }
                $serviceGroupResults['language_mapping'] = $recordValue['languageMapping'];
                $serviceGroupResults['status'] = $recordValue['status'];
                $serviceGroupResults[$i]['isDefault'] = $recordValue['isDefault'];
                $serviceGroupResults['created_at'] = $recordValue['createdAt'];
                $serviceGroupResults['updated_at'] = $recordValue['updatedAt'];
                $serviceGroupResults['country_id'] = $recordValue['countryId'];
                    //$serviceGroupResults['deleted_at'] = $recordValue['deletedAt'];
            }
        }

        return $serviceGroupResults;
    }

    /**
     * @author Employee Id: 4589
     * Description : Delete Service group.
     *
     * @param 1 : Service Group Id
     *
     * @return type : Service group
     *
     * @throws Exception: Null
     */
    public function deleteServiceGroup($id)
    {
        $serviceGroup = $this->serviceGroupRepo->find($id);
        if ($serviceGroup) {
            $serviceGroup = $this->serviceGroupRepo->deleteServiceGroup($serviceGroup);
        }

        return $serviceGroup;
    }

    /**
     * @author Employee Id: 4273
     * Description : Change Status Service Group
     *
     * @param 1 : service group Id
     *
     * @return type : service group
     *
     * @throws Exception: Null
     */
    public function changeRuleMasterStatus($id)
    {
        return $this->serviceGroupRepo->changeStatusServiceGroup($id);
    }

    /**
     * @author Employee Id: 4589
     * Description : Copy Service group.
     *
     * @param 1 : Service Group Id
     *
     * @return type : Boolean
     *
     * @throws Exception: Null
     */
    public function copyServiceGroup()
    {
        $id = $this->request->get('service_group_id');
        if ($id) {
            $serviceGroup = $this->serviceGroupRepo->find($id);
            if ($serviceGroup) {
                $make_copy_country = $this->request->request->get('make_copy_country');
                $make_copy_status = $this->request->request->get('make_copy_status');

                foreach ($make_copy_country as $countryId => $value) {
                    if (isset($make_copy_status[$countryId])) {
                        $this->makeCopyServiceGroup(clone $serviceGroup, $countryId, true);
                    } else {
                        $this->makeCopyServiceGroup(clone $serviceGroup, $countryId, false);
                    }
                }

                // commit persist objects if any
               $this->serviceGroupRepo->commit();
            }

            return true;
        }

        return false;
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Form Errors.
     *
     * @param 1 : No parameter
     *
     * @return type : Error list
     *
     * @throws Exception: Null
     */
    public function getFormErrors($form, $validator)
    {
        $errors = array();

        $serviceGroup = $form->getData()->getLanguageMapping();
        $sgErrors = $validator->validate($serviceGroup);

        foreach ($sgErrors as $error) {
            $errors[$error->getPropertyPath()] = $error->getMessage();
        }

        /*$countryId = $form->getData()->getCountryId();
        $countryCode = $this->getCountryField($countryId, 'id', 'code');

        foreach($serviceGroup->getLanguageMapping() as $language){
            if(!in_array($language->getLanguageId(), $this->countries[$countryCode]["language"])){
                unset($serviceGroup->getLanguageMapping()[$language->getLanguageId()]);
            }
        }

        $sglErrors = $validator->validate( $serviceGroup->getLanguageMapping() );

        foreach( $sglErrors as $error )
        {
            $field = str_replace("[","",$error->getPropertyPath());
            $field = str_replace("]","",$field);
            $field = str_replace(".","_",$field);
            $errors['languageMapping_'.$field] = $error->getMessage();
        }*/

        return $errors;
    }

    /**
     * @author Employee Id: 4589
     * Description : Fileter form data.
     *
     * @param 1 : No parameter
     *
     * @return type : form
     *
     * @throws Exception: Null
     */
    public function filterFormData($form)
    {
        $serviceGroup = $form->getData();

        $countryId = $serviceGroup->getCountryId();
        if ($countryId) {
            $countryCode = $this->getCountryField($countryId, 'id', 'code');

            foreach ($serviceGroup->getLanguageMapping() as $index => $language) {
                if (!in_array($language->getLanguageId(), $this->countries[$countryCode]['language'])) {
                    unset($serviceGroup->getLanguageMapping()[$index]);
                } else {
                    if ($language->getGroupName() == '') {
                        $form->get('languageMapping')[$index]->get('groupName')->addError(new \Symfony\Component\Form\FormError($this->translator->trans('service_group.group_name.not_blank')));
                    }
                }
            }
        }

        return $form;
    }

    /**
     * @author Employee Id: 4589
     * Description : Make Service Group Copy.
     *
     * @param 1 : Service Group
     * @param 1 : Country Id
     * @param 1 : Is Active
     *
     * @return type : Service group
     *
     * @throws Exception: Null
     */
    public function makeCopyServiceGroup($serviceGroup, $countryId, $isActive)
    {
        $serviceGroup->setId(null);

        if ($countryId) {
            $serviceGroup->setStatus($isActive);
            $serviceGroup->setCountryId($countryId);

            $countryCode = $this->getCountryField($countryId, 'id', 'code');

            $groupName = 'Copy of '.$serviceGroup->getLanguageMapping()->first()->getGroupName();

            foreach ($serviceGroup->getLanguageMapping() as $langMap) {
                $serviceGroup->removeLanguageMapping($langMap);
            }

            foreach ($this->countries[$countryCode]['language'] as $languageId) {
                $serviceGroupLanguageCopy = new ServiceGroupLanguage();
                $serviceGroupLanguageCopy->setLanguageId($languageId);
                $serviceGroupLanguageCopy->setGroupName($this->copyGroupName($groupName, $languageId, $countryId));
                $serviceGroupLanguageCopy->setServiceGroup($serviceGroup);
                $serviceGroup->addLanguageMapping($serviceGroupLanguageCopy);
            }

            $this->serviceGroupRepo->addServiceGroup($serviceGroup);
        }
    }

    /**
     * @author Employee Id: 4589
     * Description : Copy Group Name.
     *
     * @param 1 : Group Name
     * @param 1 : Language Id
     * @param 1 : Country Id
     *
     * @return type : group Name
     *
     * @throws Exception: Null
     */
    public function copyGroupName($groupName, $languageId, $countryId)
    {
        $groupNameExist = $this->serviceGroupLanguageRepo->getCountServiceGroupExist($groupName, $languageId, $countryId);
        if ($groupNameExist != 0) {
            $groupName = 'Copy of '.$groupName;

            return $this->copyGroupName($groupName, $languageId, $countryId);
        } else {
            return $groupName;
        }
    }

    /**
     * @author Employee Id: 4589
     * Description : Get Active Service group list.
     *
     * @param 1 : Null
     *
     * @return type : Service group list Array
     *
     * @throws Exception: Null
     */
    public function getList()
    {
        return $this->serviceGroupRepo->findAllActive($this->countryId, $this->languageId);
    }
}
