<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: LanguageController.php, v 1.0 2011/06/14 20:52:11
//
class LanguageController extends Controller {
    //LISTING ALL LANGUAGES
    public function indexAction() {
        $ObjLanguages = new LanguageModel();
        //Set as Default
        if (isset($_POST["languageDefault"])) {
            $languageID = $_POST["languageDefault"];
            if ($languageID > 0) {
                $ObjLanguages->changeDefaultLanguage($languageID);
                $this->setMessage("language.msgLanguageDefaultSave", "success");
            }
            $this->setRedirect("language/index/");
        }
        $this->ObjView->assign("rsLanguages", $ObjLanguages->listLanguages());
        $this->ObjView->assign('affiliateExist', __AFFILIATE_MODULE);
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('language/edit/'));
        $this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('language/destroy/'));
        $this->ObjView->display('Language.tpl');
    }
    //DELETING A LANGUAGE
    public function destroyAction() {
        $ObjLanguages      = new LanguageModel();
        $languageIDs       = $this->ObjView->languageIDs;
        $languageID        = $this->getRequestValue("id");
        $rsLanguages       = $ObjLanguages->changeLanguageStatus($languageID);
        $contentlanguageID = $languageIDs['Content'];
        //	$defultLanguageID	= $languageIDs['Default'];
        //	$ObjUser   			= new UserModel();
        //	$ObjUser->userlanguageStatus($defultLanguageID,$languageID);
        $ObjLanguages->resetThisLanguagePreferences($languageID, $languageIDs['Default']);
        if ($contentlanguageID = $languageID) {
            $ObjLanguages->setContentLanguageID($languageIDs['Default']);
        }
        if ($languageID == 1) {
            $this->setMessage("language.msgLanguageEnglishDelete", 3);
        } else {
            $this->setMessage("language.msgLanguageDelete", 3);
            $this->setRedirect("language/index/");
        }
    }
    //DELETING A LANGUAGE
    public function ajaxResetAction() {
        $ObjFilter    = new Filter();
        $ObjLanguages = new LanguageModel();
        $languageID   = $_REQUEST['ajax_request'][0];
        $type         = $this->getRequestValue("type");
        if ($type == 'content') {
            $ObjLanguages->setContentLanguageID($languageID);
        } else {
            $ObjCookie = $ObjFilter->getCookieInstance();
            $ObjCookie->setCookie($ObjLanguages->getSection() . '_CurrentLanguageID', $languageID);
        }
    }
    //DOWNLOAD SAMPLE TEMPLATE
    public function ajaxDownloadAction() {
        $this->ObjCommon->askPrivilege('language/index/');
        $ObjLanguages = new LanguageModel();
        $file         = $this->getRequestValue("file");
        $languageID   = $this->getRequestValue("id");
        $rsLanguage   = $ObjLanguages->getLanguageDetails($languageID);
        header("Content-type: text/xml");
        header("Content-Disposition:attachment; filename=" . $file . "_" . $rsLanguage['LanguageLCIDstring'] . ".xml");
        if ($file == 'frontend') {
            readfile(__CORE_PUBLIC_COMMON_FRONTEND_PATH . "/languages/" . $rsLanguage['LanguageLCIDstring'] . ".xml");
        } else if ($file == 'business') {
            readfile(__CORE_PUBLIC_BUSINESS_PATH . "/languages/" . $rsLanguage['LanguageLCIDstring'] . ".xml");
        } else if ($file == 'affiliate') {
            readfile(__CORE_PUBLIC_AFFILIATE_PATH . "/languages/" . $rsLanguage['LanguageLCIDstring'] . ".xml");
        } else {
            readfile(__CORE_PUBLIC_MANAGE_PATH . "/languages/" . $rsLanguage['LanguageLCIDstring'] . ".xml");
        }
    }
    //INSERTING A LANGUAGE
    public function addAction() {
        $ObjLanguages     = new LanguageModel();
		$ObjBrand         = new BrandModel();	
        $languageIDs      = $this->ObjView->languageIDs;
        $defultLanguageID = $languageIDs['Default'];
        if ($this->ObjForm->isValid('formLanguagesAdd', 'submit')) {
            if ($ObjLanguages->isLanguageCodeExixts($_POST['LanguageLCIDstring'], 0)) {
                $this->setMessage("language.msgLanguageCodeExists", "message_error");
            } else {
                $ObjLanguages->saveLanguageDetails($_POST);
                //reset frontend language listing cache variable
                $objCache = new Cache(CACHE_DRIVER);
                $objCache->delete('f_lng_list');
                //EXTND MAIL FUNCTIONALITY
                $settings['campaign'] = $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
                if ($settings['campaign'] == 'campaign_monitor') {
                    $this->createCustomFieldAndSegment($_POST['LanguageLCIDstring']);
                }
                //END EXTD MAIL                           
                echo '<script type="text/javascript">parent.location.reload();parent.$.colorbox.close();</script>';
                $this->setMessage("language.msgLanguageSave", "success");
                exit;
            }
        }
		$brandParams         = array(
            'languageIDs' => $languageIDs
        ); 
		$listBrands  = $ObjBrand->listBrand($brandParams); 
		$brandID    = $listBrands[0]['brandID'];
		$listBrand  = array();
		foreach ($listBrands as $key => $brands) {
			if($key==0)
			$listBrand[] = $brands;
		}
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign('brandID', $brandID);
        //$this->ObjView->assign("languageID",$languageID);
        $this->ObjView->assign('defaultLngID', $defultLanguageID);
        $this->ObjView->assign('affiliateExist', __AFFILIATE_MODULE);
        $this->ObjView->display('LanguageAdd.tpl');
    }
    //INSERTING A LANGUAGE
    public function editAction() {
        $ObjLanguages      = new LanguageModel();
		$ObjBrand          = new BrandModel();		
        $ObjImage          = new ImageModel();
        $languageIDs       = $this->ObjView->languageIDs;
        $defultLanguageID  = $languageIDs['Default'];
        $languageID        = $this->getRequestValue("id");
        $contentlanguageID = $languageIDs['Content'];
		
		$brandParams       = array(
            'languageIDs' => $languageIDs
        ); 
		$listBrand         = $ObjBrand->listBrand($brandParams);  
		$brandID     	   = $this->getRequestValue('brandID');
		$brandID 		   = (!empty($brandID )) ? $brandID : $listBrand[0]['brandID'];
		
        if ($languageID) {
            $rsLanguage = $ObjLanguages->getLanguageDetails($languageID,$brandID);
			//echo "<pre>";print_r($rsLanguage);exit;
            $this->ObjView->assignValues($rsLanguage);
        }
        if ($this->ObjForm->isValid('formLanguagesAdd', 'submit')) {
            if ($ObjLanguages->isLanguageCodeExixts($_POST['LanguageLCIDstring'], $languageID)) {
                $this->setMessage("language.msgLanguageCodeExists", "message_error");
            } else {
                if ($defultLanguageID == $languageID && $_POST['languageStatus'] == 'Inactive' && $languageID != '') {
                    $this->setMessage("language.msgDefaultLanguageInactive", "message_info");
                } else {
                    /*unlink old image*/
                    if (!empty($_POST["languageImage_temp"])) {
                        $imagePath = __UPLOADS_FOLDER . 'languages/' . trim($rsLanguage['languageImage']);
                        $ObjImage->unlinkImage($imagePath);
                    }
                    /*unlink old image*/
					/*unlink old image*/
                    if (!empty($_POST["languageLogo_temp"])) {
                        $imagePath = __UPLOADS_FOLDER . 'languages/logo/' . trim($rsLanguage['languageLogo']);
                        $ObjImage->unlinkImage($imagePath);
                    }
                    /*unlink old image*/
                    $ObjLanguages->saveLanguageDetails($_POST, $languageID);
                    //reset frontend language listing cache variable
                    $objCache = new Cache(CACHE_DRIVER);
                    $objCache->delete('f_lng_list');
                    //EXTND MAIL FUNCTIONALITY
                    /*if(!$languageID)
                    {
                    $settings['campaign']	= $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
                    if($settings['campaign']=='campaign_monitor')
                    {
                    $this->createCustomFieldAndSegment($_POST['LanguageLCIDstring']);
                    }
                    } */
                    //END EXTD MAIL
                    if ($languageID && $_POST['languageStatus'] == "Inactive") {
                        $ObjLanguages->resetThisLanguagePreferences($languageID, $languageIDs['Default']);
                        if ($contentlanguageID = $languageID) {
                            $ObjLanguages->setContentLanguageID($languageIDs['Default']);
                        }
                    }
                    echo '<script type="text/javascript">parent.location.reload();parent.$.colorbox.close();</script>';
                    if ($languageID)
                        $this->setMessage("language.msgLanguageUpdate", "success");
                    /* else
                    $this->setMessage("language.msgLanguageSave","success"); */
                    exit;
                }
            }
        }
		$this->ObjView->assign('brandID', $brandID);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign("languageID", $languageID);
        $this->ObjView->assign('defaultLngID', $defultLanguageID);
        $this->ObjView->assign('affiliateExist', __AFFILIATE_MODULE);
        $this->ObjView->display('LanguageAdd.tpl');
    }
    public function createCustomFieldAndSegment($languageLcidKey, $oldLcidKey = '') {
        $languageIDs                 = $this->ObjView->languageIDs;
        $ObjCity                     = new CityModel();
        //EXTND MAIL FUNCTIONALITY
        $_POST['LanguageLCIDstring'] = $languageLcidKey;
        $campaignApiKey              = $this->getSettingValue('third_paty_mail_settings', 'campaign_api_key');
        $campaignApiKey              = $this->encryptDecrypt("decrypt", $campaignApiKey);
        if ($campaignApiKey) {
            $settings['user_name']     = $this->getSettingValue('third_paty_mail_settings', 'campaign_user_name');
            $settings['user_name']     = $this->encryptDecrypt("decrypt", $settings['user_name']);
            $settings['password']      = $this->getSettingValue('third_paty_mail_settings', 'campaign_password');
            $settings['password']      = $this->encryptDecrypt("decrypt", $settings['password']);
            $settings['campaign']      = $this->getSettingValue('third_paty_mail_settings', 'campaign_name');
            $settings['api_key']       = $campaignApiKey;
            $settings['api_client_id'] = $this->getSettingValue('third_paty_mail_settings', 'campaign_client_id');
            $settings['api_client_id'] = $this->encryptDecrypt("decrypt", $settings['api_client_id']);
            try {
                $ObjCampaign = new Campaign($settings);
                if ($settings['campaign'] == 'campaign_monitor') {
                    $rescityDetails = $ObjCity->getAllCityDetails($languageIDs, 'Active');
                    foreach ($rescityDetails as $city) {
                        if ($city['cityCampaignListID'] != '') {
                            $results = $ObjCampaign->get_custom_fields($city['cityCampaignListID']);
                            $results = $results->response;
                            foreach ($results as $result) {
                                if ($result->FieldName == 'Language') {
                                    $key = $result->Key;
                                }
                            }
                            if ($key) {
                                $option[0]          = $_POST['LanguageLCIDstring'];
                                $results            = $ObjCampaign->update_field_options($city['cityCampaignListID'], $key, $option);
                                $productTypeKeysArr = array(
                                    'product_product'
                                );
                                for ($i = 0; $i < count($productTypeKeysArr); $i++) {
                                    $segment_details['Title'] = $productTypeKeysArr[$i][0] . "-" . $_POST['LanguageLCIDstring'];
                                    $segment_details['Rules'] = array(
                                        array(
                                            'Subject' => '[ProductType]',
                                            'Clauses' => array(
                                                'EQUALS ' . $productTypeKeysArr[$i][0]
                                            )
                                        ),
                                        array(
                                            'Subject' => '[Language]',
                                            'Clauses' => array(
                                                'EQUALS ' . $_POST['LanguageLCIDstring']
                                            )
                                        )
                                    );
                                    $ObjCampaign->createSegments($city['cityCampaignListID'], $segment_details);
                                }
                            }
                        }
                    }
                    //For NewsLetter
                    if ($key) {
                        $option[0]                = $_POST['LanguageLCIDstring'];
                        $campaignListID           = $this->getSettingValue('third_paty_mail_settings', 'campaign_newsletter_list_id');
                        $results                  = $ObjCampaign->update_field_options($campaignListID, $key, $option);
                        $segment_details['Title'] = $_POST['LanguageLCIDstring'];
                        $segment_details['Rules'] = array(
                            array(
                                'Subject' => '[Language]',
                                'Clauses' => array(
                                    'EQUALS ' . $_POST['LanguageLCIDstring']
                                )
                            )
                        );
                        $ObjCampaign->createSegments($campaignListID, $segment_details);
                    }
                } else if ($settings['campaign'] == 'mail_chimp') {
                    $rescityDetails = $ObjCity->getAllCityDetails($languageIDs, 'Active');
                    //For newsletter 
                    $campaignListID = $this->getSettingValue('third_paty_mail_settings', 'campaign_newsletter_list_id');
                    if ($oldLcidKey != $languageLcidKey && $oldLcidKey != '') {
                        //$res=$ObjCampaign->listInterestGroupUpdate($campaignListID, $oldLcidKey, $languageLcidKey);
                        $res = $ObjCampaign->listInterestGroupingAdd($campaignListID, 'Language', 'checkboxes', $languageLcidKey);
                    } else {
                        $res = $ObjCampaign->listInterestGroupingAdd($campaignListID, 'Language', 'checkboxes', $languageLcidKey);
                    }
                }
            }
            catch (Exception $e) {
                $msg     = $e->getMessage();
                $message = "Error : " . $msg;
                echo $message;
                $this->setMessage($message, 'error');
                exit;
            }
        }
        //END EXTD MAIL	
    }
}