<?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: SubscriberController.php, v 1.0 2011/06/14 20:52:11
//
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class SubscriberController extends Controller {
    //MANAGE SUBSCRIBERS
    public function indexAction() {
        $ObjUsers           = new UserModel();
        $cityOptions        = array();
        $link               = 'subscriber/index/';
        $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
        $languageIDs        = $this->ObjView->languageIDs;
        $datefrom           = '';
        $dateto             = '';
        //Status change
        if (isset($_POST['status_update'])) {
            $status          = $_POST['subscStatus'];
            $resUpdateStatus = $ObjUsers->unSubscribeUser();
            if ($status == 'Unsubscribed') {
                $_POST['emailID'] = $_POST['unSubscEmailID'];
                $ObjUsers->unsubscribeNewsletter();
            }
            // CHECK THIRD PARTY MAIL INTEGRATIONS
            if ($this->getSettingValue('third_paty_mail_settings', 'campaign_name') != '') {
                $this->updateThirdPartyMail($emailIDs, $status);
            }
            if ($resUpdateStatus) {
                $this->setMessage($this->getLanguageValue('msgStatus'), 'success');
                $this->setRedirect();
            }
        }
        //Search
        if (!empty($_POST['submit_search'])) {
            $date = $_POST['date'];
            if ($date) {
                $searchDates = explode(' - ', $date);
                $datefrom    = $searchDates[0];
                if (isset($searchDates[1])) {
                    $dateto = $searchDates[1];
                }
            }
            $link .= (($datefrom != "") ? "datefrom/" . $this->urlDate($datefrom, 'set', $settingsDateFormat) . "/" : "");
            $link .= (($dateto != "") ? "dateto/" . $this->urlDate($dateto, 'set', $settingsDateFormat) . "/" : "");
            if (trim($_POST['emailID']) != '') {
                $link .= 'emailid/' . $this->encodeUrlString(trim($_POST['emailID'])) . '/';
            }
            $link .= 'status/' . $_POST['status'] . '/';
            $this->setRedirect($link);
        } else {
            $search   = array();
            $emailID  = $this->decodeUrlString($this->getRequestValue('emailid'));
            $dateFrom = $this->urlDate($this->getRequestValue('datefrom'), 'get', $settingsDateFormat);
            $dateTo   = $this->urlDate($this->getRequestValue('dateto'), 'get', $settingsDateFormat);
            $status   = ($this->getRequestValue('status') != '') ? $this->getRequestValue('status') : 'Subscribed';
            /*assigning from and to values for search*/
            if ($dateFrom && $dateTo == '') {
                $this->ObjView->assign('fromDate', $dateFrom);
            } else if ($dateFrom && $dateTo) {
                $this->ObjView->assign('fromDate', $dateFrom . ' - ' . $dateTo);
            } else {
                $this->ObjView->assign('fromDate', '');
            }
            /*assigning from and to values for search*/
            if ($dateFrom != '') {
                $search['dateFrom'] = $this->convertDateForSQL($dateFrom, $settingsDateFormat);
                $this->ObjView->assign('dateFrom', $dateFrom);
            }
            if ($dateTo != '') {
                $search['dateTo'] = $this->convertDateForSQL($dateTo, $settingsDateFormat) . '  23:59:59';
                $this->ObjView->assign('dateTo', $dateTo);
            }
            if ($status != '') {
                $search['status'] = $status;
                $this->ObjView->assign('status', $status);
            }
            if ($emailID != '') {
                $search['emailID'] = $emailID;
                $this->ObjView->assign('emailID', $search['emailID']);
            }
            if ($dateFrom && $dateTo == '') {
                $search['dateTo'] = $this->convertDateForSQL($dateFrom, $settingsDateFormat) . '  23:59:59';
                //$this->ObjView->assign('dateTo',$dateTo);
            }
            $date = $dateFrom;
            if ($dateTo) {
                $date .= " - " . $dateTo;
            }
            // pagination settings
            //list($limitFrom,$limitTo)   =   $this->getPageSettings('page',10);	
            list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
            //print_r($search);exit;
            $resListSubscribers = $ObjUsers->listSubscribers($languageIDs, $limitFrom, $limitTo, $search);
            $resPagesCount      = $this->setPagesCount($key = 'page');
        }
        //status in option box
        $statusOptions[0][] = 'Nochange';
        $statusOptions[0][] = $this->getLanguageValue('lblDonotchange');
        if (!isset($search['status'])) {
            $statusOptions[1][] = 'Subscribed';
            $statusOptions[1][] = $this->getLanguageValue('lblSubscribed');
            $statusOptions[2][] = 'Unsubscribed';
            $statusOptions[2][] = $this->getLanguageValue('lblUnsubscribed');
        } else {
            if (strtolower($search['status']) == 'unsubscribed') {
                $statusOptions[1][] = 'Subscribed';
                $statusOptions[1][] = $this->getLanguageValue('lblSubscribed');
            } elseif (strtolower($search['status']) == 'subscribed') {
                $statusOptions[1][] = 'Unsubscribed';
                $statusOptions[1][] = $this->getLanguageValue('lblUnsubscribed');
            }
        }
        $this->ObjView->assign('statusOptions', $statusOptions);
        $this->ObjView->assign('resListSubscribers', $resListSubscribers);
        $this->ObjView->assign('date_format', $this->getSettingValue('site_settings', 'date_format'));
        $this->ObjView->assign('time_format', $this->getSettingValue('site_settings', 'time_format'));
        //$this->ObjView->assign("privilage", $this->ObjCommon->hasPrivilege('subscriber/edit/'));
        $exportPrivilege	=	$this->ObjCommon->hasPrivilege('subscriber/export/');
        $this->ObjView->assign("exportPrivilege", $exportPrivilege);
        $statusPrivilege	=	$this->ObjCommon->hasPrivilege('subscriber/statusChange/');
        $this->ObjView->assign("statusPrivilege", $statusPrivilege);
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('subscriber/edit/'));
		$this->ObjView->display('Subscribers.tpl');
    }
    //TO EXPORT
    public function exportAction() {
        $languageIDs        = $this->ObjView->languageIDs;
        $ObjUsers           = new UserModel();
        $settingsDateFormat = '';
        $url                = '';
        $dateFrom           = '';
        $dateTo             = '';
        $date               = isset($_POST['date']) ? $_POST['date'] : '';  
        if ($date != '') {
            $searchDates = explode(' - ', $date);
            $dateFrom    = $searchDates[0];
            if (isset($searchDates[1])) {
                $dateTo = $searchDates[1];
            }
        }
        $dateFrom = isset($dateFrom) ? trim($dateFrom) : '';
        $dateTo   = isset($dateTo) ? trim($dateTo) : '';
        $this->ObjView->assign('dateTo', $dateTo);
        $this->ObjView->assign('dateFrom', $dateFrom);
        if (!empty($_POST)) {
            $ObjCsv             = new Csv();
            $settingsDateFormat = $this->getSettingValue("site_settings", "date_format");
            $_POST['dateFrom']  = $this->convertDateForSQL($dateFrom, $settingsDateFormat);
            $_POST['dateTo']    = $this->convertDateForSQL($dateTo, $settingsDateFormat);
            if ($_POST['dateFrom'] && $_POST['dateTo'] == '') {
                $_POST['dateTo'] = $_POST['dateFrom'];
            }
            $resListSubscribers = $ObjUsers->exportSubscribers();
            if (!empty($resListSubscribers)) {
                if (__AFFILIATE_MODULE) {
                    $header = array(
                        $this->getLanguageValue("lblEmailAddress"),
                        $this->getLanguageValue("lblSubscribedDate"),
                        $this->getLanguageValue("lblLanguageCodes"),
                        $this->getLanguageValue("lblIPAddress"),
                        $this->getLanguageValue("lblStatus")
//                        $this->getLanguageValue("lblAffiliate"),
                       
                    );
                } else {
                    $header = array(
                        $this->getLanguageValue("lblEmailAddress"),
                        $this->getLanguageValue("lblSubscribedDate"),
                        $this->getLanguageValue("lblLanguageCodes"),
                        $this->getLanguageValue("lblIPAddress"),
                        $this->getLanguageValue("lblStatus")
                    );
                }
                $dateTime = date('d_m_Y_H_i_s');
                $data     = $ObjCsv->output('subscribers_' . $dateTime . '.csv', $resListSubscribers, $header);
            } else {
                $this->setMessage("language.msgNoSubscribers", 'error');
                $url .= (($dateFrom != "") ? "/datefrom/" . $this->urlDate($dateFrom, 'set', $settingsDateFormat) : "");
                $url .= (($dateTo != "") ? "/dateto/" . $this->urlDate($dateTo, 'set', $settingsDateFormat) : "");
                $this->setRedirect("subscriber/export" . $url . "/");
            }
        }
        $date = $dateFrom;
        if ($dateTo) {
            $date .= " - " . $dateTo;
        }
        if ($date == '') {
            $dateFrom = $this->urlDate($this->getRequestValue('datefrom'), 'get', $settingsDateFormat);
            $dateTo   = $this->urlDate($this->getRequestValue('dateto'), 'get', $settingsDateFormat);
            $date     = $dateFrom;
            if ($dateTo) {
                $date .= " - " . $dateTo;
            }
        }
        $this->ObjView->assign("date", $date);
        $this->ObjView->assign("listPrivilege", $this->ObjCommon->hasPrivilege('subscriber/index/'));
        $this->ObjView->display('SubscribersExport.tpl');
    }
    //TO IMPORT
    public function importAction() {
        if ($this->ObjForm->isValid('subscriber_import', 'submit_import')) {
            $ObjCsv = new Csv();
            if ($_FILES['csvFile']['tmp_name'] != '') {
                $importFile = $_FILES['csvFile']['tmp_name'];
            } else {
                $this->setMessage($this->getLanguageValue('errFile'), 'error');
                $this->setRedirect("subscriber/import/");
            }
            $ObjCsv->auto($importFile);
            $resImportSubscribers = $ObjCsv->data;
            if (!empty($resImportSubscribers)) {
                $fields      = array_keys($resImportSubscribers[0]);
                $validFields = array(
                    'subscEmailID',
                    'subscribedDate',
                    'languageCode'
                );
                if ($fields != $validFields) {
                    $this->setMessage($this->getLanguageValue('errInvalidCsvFormat'), 'error');
                    $this->setRedirect("subscriber/import/");
                } else {
                    $ObjUsers                       = new UserModel();
                    $languageIDs                    = $this->ObjView->languageIDs;
                    $languageIDs['languageIDsList'] = $this->ObjView->languageIDsList;
                    $resImport                      = $ObjUsers->importSubscribers($resImportSubscribers, $languageIDs);
                    if ($resImport) {
                        if (($resImport['inserted'] == 0 && $resImport['updated'] == 0) && ($resImport['existing'] >= 1 || $resImport['failed'] >= 1)) {
                            $this->setMessage($this->getLanguageValue('msgContactImportFailure'), 'error');
                        } else {
                            $this->setMessage($this->getLanguageValue('msgContactImprotSuccess') . $resImport['inserted'] . $this->getLanguageValue('msgContactsInserted') . $resImport['updated'] . $this->getLanguageValue('msgContactsUpdated') . $resImport['existing'] . $this->getLanguageValue('msgContactsExists') . $resImport['failed'] . $this->getLanguageValue('msgContactsFailed'), 'success');
                        }
                        $this->setRedirect("subscriber/import/");
                    }
                }
            } else {
                //invalid/empty csv
                $this->setMessage($this->getLanguageValue('errInvalidCsv'), 'error');
                $this->setRedirect("subscriber/import/");
            }
        }
        $this->ObjView->assign("listPrivilege", $this->ObjCommon->hasPrivilege('subscriber/index/'));
        $this->ObjView->display('SubscribersImport.tpl');
    }
    //SAMPLE CSV
    public function ajaxSamplecsvAction() {
        $languageIDs        = $this->ObjView->languageIDs;
        $ObjUsers           = new UserModel();
        $ObjCsv             = new Csv();
        $MAX                = 3;
        $_POST['status']    = 'Subscribed';
        $resListSubscribers = $ObjUsers->exportSubscribers(5);
        if (!empty($resListSubscribers)) {
            foreach ($resListSubscribers as &$csvOutputRow) {
                $csvOutputRow = array_slice($csvOutputRow, 0, $MAX);
            }
            $header = array_keys($resListSubscribers[0]);
            $data   = $ObjCsv->output('example.csv', $resListSubscribers, $header);
        } else {
            $resListSubscribers = $ObjUsers->getDummyData($languageIDs, $_POST);
            $header             = array_keys($resListSubscribers[0]);
            $data               = $ObjCsv->output('example.csv', $resListSubscribers, $header);
        }
        $this->setRedirect("subscriber/import/");
    }
    /**
     * function updateThirdPartyMail
     * 
     * Manages bulk subscribe/unsubscribe of third party mail providers
     * 
     * @param array $emailIDs
     * @param string $status
     */
    private function updateThirdPartyMail($emailIDs, $status) {
        $ObjMail = new ThirdPartyMailModel();
        foreach ($emailIDs as $emailID) {
            $updateSubscription = $ObjMail->updateSubscribeStatus($emailID, $status);
        }
    }
	public function editAction(){
		
	}
}