<?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: FormController.php, v 1.0 2013/04/16 20:52:11
//
class FormController extends Controller {
    public function indexAction() {
        $objForm        = new FormModel();
        $adminUserModel = new AdminuserModel();
        $ObjBrand       = new BrandModel();
        $languageIDs    = $this->ObjView->languageIDs;
        $languageID     = $languageIDs['Content'];
        $adminUsers     = $adminUserModel->listAdmin();
        $link           = 'form/index/';
        if (isset($_POST['formStatus'])) {
            $formStatus = $_POST['formStatus'];
            if ($formStatus == '') {
                $this->setMessage('language.lblSelectStatus', "error");
                $this->setRedirect("form/index/");
            }
            $formIDs = "'" . implode("','", $_POST['contentBulkStatus']) . "'";
            $objForm->formChangeStatus($formIDs, $formStatus);
            if ($formStatus == 'Deleted') {
                $this->setMessage('language.lblMsgFormStatusDeleted', "success");
            } else {
                $this->setMessage('language.lblMsgFormStatusUpdated', "success");
            }
            $this->setRedirect("form/index/");
        }
        $brandID = '';
        if (isset($_POST['submitSearch'])) {
            if ($_POST['searchTitle'] != '') {
                $link .= 'title/' . $this->encodeUrlString($_POST['searchTitle']) . '/';
            }
            if ($_POST['statusSearch'] != '') {
                $link .= 'status/' . $this->encodeUrlString($_POST['statusSearch']) . '/';
            }
            if ($_POST['searchCreatedBy'] != '') {
                $link .= 'create/' . $this->encodeUrlString($_POST['searchCreatedBy']) . '/';
            }
            if ($_POST['brandID']>0) {
                $link .= "frID/" . $_POST['brandID'] . "/";
            }
            $this->setRedirect($link);
        } else {
            $searchTitle     = $this->decodeUrlString($this->getRequestValue('title'));
            $statusSearch    = $this->decodeUrlString($this->getRequestValue('status'));
            $searchCreatedBy = $this->decodeUrlString($this->getRequestValue('create'));
            $sortby          = $this->decodeUrlString($this->getRequestValue('sortby'));
            $orderby         = $this->decodeUrlString($this->getRequestValue('orderby'));
            if ($searchTitle != '') {
                $link .= 'title/' . $searchTitle . '/';
            }
            if ($statusSearch != '') {
                $link .= 'status/' . $statusSearch . '/';
            }
            if ($searchCreatedBy != '') {
                $link .= 'create/' . $searchCreatedBy . '/';
            }
            if ($this->getRequestValue('frID')) {
                $brandID = $this->getRequestValue('frID');
            }
            $params     = array(
                'languageID' => $languageID,
                'searchTitle' => $searchTitle,
                'statusSearch' => $statusSearch,
                'sortby' => $sortby,
                'orderby' => $orderby,
                'formStatus' => "'draft','publish'",
                'searchCreatedBy' => $searchCreatedBy,
                'brandID'=>$brandID
            );
            $resultForm = $objForm->listForm($params);
            $this->ObjView->assign('link', $link);
            $this->ObjView->assign('searchTitle', $searchTitle);
            $this->ObjView->assign('statusSearch', $statusSearch);
            $this->ObjView->assign('searchCreatedBy', $searchCreatedBy);
            $this->ObjView->assign('orderby', ($orderby == 'asc') ? 'desc' : 'asc');
        }
        $this->ObjView->assign('resultForm', $resultForm);
        $this->ObjView->assign('adminUsers', $adminUsers);
        $params    = array(
            'languageIDs' => $languageIDs
        );
        $listBrand = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign('brandID', $brandID);
        $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('form/build/'));
        $this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('form/destroy/'));
        $this->ObjView->assign("submissionPrivilege", $this->ObjCommon->hasPrivilege('form/submission/'));
        $this->ObjView->display('Forms.tpl');
    }
    public function submissionAction() {
        $formID          = $this->getRequestValue('id');
        $dateFormat      = $this->getSettingValue('site_settings', 'date_format');
        $elementOptions  = array();
        $formAllElements = array();
        $resSubmissions  = array();
        $formElement     = array();
        $searchField     = array();
        if ($formID > 0) {
            $objForm            = new FormModel();
            $languageIDs        = $this->ObjView->languageIDs;
            $languageID         = $languageIDs['Content'];
            $settingsDateFormat = $this->getSettingValue('site_settings', 'date_format');
            $link               = 'form/submission/id/' . $formID . "/";
            $params             = array(
                'languageID' => $languageID,
                'formStatus' => "'draft','publish'",
                'formID' => $formID
            );
            $resultForm         = $objForm->getForm($params);
            if (empty($resultForm)) {
                $this->setRedirect("form/index/");
            }
            $resultElement = $objForm->getElements($params);
            if (!empty($resultElement)) {
                $searchField         = array();
                $searchFieldElements = array();
                foreach ($resultElement as $key => $elements) {
                    $formElementName = $elements['attributeType'] . "_" . $elements['formElementID'];
                    if ($elements['attributeType'] != 'html' && $elements['attributeType'] != 'submit' && $elements['attributeType'] != 'image' && $elements['attributeType'] != 'file') {
                        $formAllElements[$elements['attributeType']][] = $formElementName;
                        $formElement[]                                 = $formElementName;
                    }
                    $extraAttributes = json_decode($elements['extraAttributes'], TRUE);
                    if (isset($extraAttributes['defaults']['enableSearch']) && $extraAttributes['defaults']['enableSearch'] == 'true') {
                        $options = array();
                        if ($elements['attributeType'] == 'select' || $elements['attributeType'] == 'checkbox' || $elements['attributeType'] == 'radio') {
                            $options = $objForm->getOptions($languageID, $elements['formElementID']);
                        } else if ($elements['attributeType'] == 'country') {
                            $objCountry = new CountryModel();
                            $options    = $objCountry->listCountries($languageIDs);
                        } else if ($elements['attributeType'] == 'businesstype') {
                            $ObjBusinessType = new BusinessTypeModel();
                            $options         = "<option value>" . $this->getLanguageValue("lblSelect") . "</option>";
                            $options .= $ObjBusinessType->getBusinessTypeOption($languageIDs, $businessType = "others");
                        }
                        array_push($searchField, array(
                            'label' => $elements['formElementLabel'],
                            'type' => $elements['attributeType'],
                            'name' => $elements['attributeType'] . "_" . $elements['formElementID'],
                            'options' => $options
                        ));
                    }
                    if ($elements['attributeType'] == 'select_multiple' || $elements['attributeType'] == 'checkbox') {
                        $formElementID                    = $elements['formElementID'];
                        $optRes                           = $objForm->getOptions($languageID, $formElementID);
                        $elementOptions[$formElementName] = $optRes;
                    }
                }
                if (!empty($elementOptions)) {
                    foreach ($elementOptions as $elem => $optionElem) {
                        foreach ($optionElem as $key => $options) {
                            $optionElem[$options['formElementOptionID']] = $options;
                        }
                        $elementOptions[$elem] = $optionElem;
                    }
                }
                if (isset($_POST['submitSearch'])) {
                    foreach ($searchField as $elments) {
                        if ($_POST[$elments['name']] != '') {
                            if ($elments['type'] == 'date') {
                                $link .= $elments['name'] . '/' . $this->urlDate($_POST[$elments['name']], 'set', $dateFormat) . '/';
                            } else {
                                $link .= $elments['name'] . '/' . $_POST[$elments['name']] . '/';
                            }
                        }
                    }
                    if ($_POST['searchSubmittedDate'] != '') {
                        $dates = explode(" - ", $_POST['searchSubmittedDate']);
                        if (count($dates) > 1) {
                            $link .= 'fromdate/' . $this->urlDate($dates[0], 'set', $dateFormat) . '/';
                            $link .= 'todate/' . $this->urlDate($dates[1], 'set', $dateFormat) . '/';
                        } else {
                            $link .= 'date/' . $this->urlDate($_POST['searchSubmittedDate'], 'set', $dateFormat) . '/';
                        }
                    }
                    $this->setRedirect($link);
                } else {
                    $fromdate = $this->getRequestValue('fromdate');
                    $todate   = $this->getRequestValue('todate');
                    $date     = $this->getRequestValue('date');
                    $fromdate = $this->urlDate($fromdate, 'get', $settingsDateFormat);
                    $todate   = $this->urlDate($todate, 'get', $settingsDateFormat);
                    $date     = $this->urlDate($date, 'get', $settingsDateFormat);
                    if (isset($fromdate) && $fromdate != '') {
                        $link .= 'fromdate/' . $this->urlDate($fromdate, 'set', $dateFormat) . '/';
                    }
                    if (isset($todate) && $todate != '') {
                        $link .= 'todate/' . $this->urlDate($todate, 'set', $dateFormat) . '/';
                    }
                    if (isset($date) && $date != '') {
                        $link .= 'date/' . $this->urlDate($date, 'set', $dateFormat) . '/';
                    }
                    list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page');
                    $searchArr = array();
                    foreach ($searchField as $elments) {
                        $elmentval = $this->getRequestValue($elments['name']);
                        if ($elmentval != '') {
                            $this->ObjView->assign($elments['name'], $elmentval);
                            if ($elments['type'] == 'date') {
                                $elmentval = $this->urlDate($elmentval, 'get', $settingsDateFormat);
                                $elmentval = $this->convertDateForSQL($elmentval, $settingsDateFormat);
                            }
                            array_push($searchArr, array(
                                'value' => $elmentval,
                                'name' => $elments['name'],
                                'type' => $elments['type']
                            ));
                        }
                        if (isset($elmentval) && $elmentval != '') {
                            $link .= $elments['name'] . '/' . $elmentval . '/';
                        }
                    }
                    if (isset($_POST['submissionStatus'])) {
                        $submissionStatus = $_POST['submissionStatus'];
                        if ($submissionStatus == '') {
                            $this->setMessage('language.lblSelectStatus', "error");
                            $this->setRedirect("form/submission/id/" . $formID);
                        }
                        $submissions = "'" . implode("','", $_POST['submissions']) . "'";
                        $objForm->submissionChangeStatus($submissions, $submissionStatus);
                        $this->setMessage('language.msgSubmissionDataUpdated', "success");
                        $this->setRedirect($link);
                    }
                    $defaultFields  = array(
                        'formID',
                        'dateSubmitted',
                        'userAgent',
                        'submittedIP',
                        'submittedDataStatus',
                        'submittedLocation',
                        'forSub.submissionDetailsID',
                        'forKey.submissionID'
                    );
                    $params         = array(
                        "languageID" => $languageID,
                        "limitFrom" => $limitFrom,
                        "limitTo" => $limitTo,
                        "formKey" => $resultForm['formKey'],
                        "formAllElements" => $formAllElements,
                        "searchArr" => $searchArr,
                        "formElement" => array_merge($formElement, $defaultFields),
                        "fromdate" => $this->convertDateForSQL($fromdate, $settingsDateFormat),
                        "todate" => $this->convertDateForSQL($todate, $settingsDateFormat),
                        "date" => $this->convertDateForSQL($date, $settingsDateFormat)
                    );
                    $resSubmissions = $objForm->listSubmission($params);
                    $resPagesCount  = $this->setPagesCount($key = 'page');
                    foreach ($resSubmissions as $keyOuter => $submissions) {
                        foreach ($submissions as $keyInner => $value) {
                            if (strpos($keyInner, 'select_multiple') === 0 || strpos($keyInner, 'checkbox') === 0) {
                                $values = '';
                                foreach (explode(",", $value) as $key => $selected) {
                                    if ($key > 0) {
                                        $values .= ",";
                                    }
                                    $values .= $elementOptions[$keyInner][$selected]['optionDesc'];
                                }
                                $submissions[$keyInner] = $values;
                            }
                        }
                        $resSubmissions[$keyOuter] = $submissions;
                    }
                    $this->ObjView->assign('searchSubmittedDate', ($fromdate != '' && $todate != '') ? $fromdate . " - " . $todate : $date);
                }
            }
            $this->ObjView->assign('resultForm', $resultForm);
            $this->ObjView->assign('formElement', $formElement);
            $this->ObjView->assign('resultElement', $resultElement);
            $this->ObjView->assign('resSubmissions', $resSubmissions);
            $this->ObjView->assign('elementOptions', $elementOptions);
            $this->ObjView->assign('formID', $formID);
            $this->ObjView->assign('date_format', $dateFormat);
            $this->ObjView->assign('searchField', $searchField);
			 $this->ObjView->assign("showPrivilege", $this->ObjCommon->hasPrivilege('form/showsubmission/'));
			$this->ObjView->assign("deletePrivilege", $this->ObjCommon->hasPrivilege('form/submissiondestroy/'));
			$this->ObjView->assign("submissionPrivilege", $this->ObjCommon->hasPrivilege('form/submission/'));
			$this->ObjView->assign("cstatusPrivilege", $this->ObjCommon->hasPrivilege('form/edit/'));
			$this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('form/build/'));
			$this->ObjView->assign("addPrivilege", $this->ObjCommon->hasPrivilege('form/new/'));
			
            $this->ObjView->display('FormSubmissions.tpl');
        }
    }
    public function showsubmissionAction() {
        $this->ObjCommon->askPrivilege('form/submission/');
        $elementOptions      = array();
        $submissionDetailsID = $this->getRequestValue('did');
        $formID              = $this->getRequestValue('formid');
        if ($submissionDetailsID > 0 && $formID > 0) {
            $objForm     = new FormModel();
            $languageIDs = $this->ObjView->languageIDs;
            $languageID  = $languageIDs['Content'];
            $params      = array(
                'languageID' => $languageID,
                'formStatus' => "'draft','publish'",
                'formID' => $formID
            );
            $resultForm  = $objForm->getForm($params);
            if (empty($resultForm)) {
                $this->setRedirect("form/index/");
            }
            $resultElement = $objForm->getElements($params);
            foreach ($resultElement as $key => $elements) {
                $formElementName = $elements['attributeType'] . "_" . $elements['formElementID'];
                if ($elements['attributeType'] != 'html' && $elements['attributeType'] != 'submit') {
                    $formAllElements[$elements['attributeType']][] = $formElementName;
                    $formElement[]                                 = $elements['attributeType'] . "_" . $elements['formElementID'];
                }
                if ($elements['attributeType'] == 'select_multiple' || $elements['attributeType'] == 'checkbox') {
                    $formElementID                    = $elements['formElementID'];
                    $optRes                           = $objForm->getOptions($languageID, $formElementID);
                    $elementOptions[$formElementName] = $optRes;
                }
            }
            if (!empty($elementOptions)) {
                foreach ($elementOptions as $elem => $optionElem) {
                    foreach ($optionElem as $key => $options) {
                        $optionElem[$options['formElementOptionID']] = $options;
                    }
                    $elementOptions[$elem] = $optionElem;
                }
            }
            $params               = array(
                "languageID" => $languageID,
                "formKey" => $resultForm['formKey'],
                "submissionDetailsID" => $submissionDetailsID,
                "formID" => $formID,
                "formAllElements" => $formAllElements,
                "formElement" => $formElement
            );
            $resultSubmissionData = $objForm->getSubmissionData($params);
            $this->ObjView->assign('resultSubmissionData', $resultSubmissionData);
            $this->ObjView->assign('formID', $formID);
            $this->ObjView->assign('submissionDetailsID', $submissionDetailsID);
            $this->ObjView->assign('elementOptions', $elementOptions);
            $this->ObjView->assign('resultForm', $resultForm);
            $this->ObjView->assign('resultElement', $resultElement);
            $this->ObjView->assign("editPrivilege", $this->ObjCommon->hasPrivilege('form/build/'));
            $this->ObjView->display('FormSubmissionDetails.tpl');
        }
    }
    public function buildAction() {
        $objCache      = new Cache("file");
        $languageIDs   = $this->ObjView->languageIDs;
        $languageID    = $languageIDs['Content'];
        $objFormAction = new FormActionModel();
        $objCustommenu = new CustommenuModel();
        $ObjBrand      = new BrandModel();
        $ObjUsergroup  = new UsergroupModel();
        if ($this->ObjForm->isValid('formSettings', 'submitSettings')) {
            $objForm                     = new FormModel();
            $formID                      = $this->getRequestValue('id');
            $_POST['formID']             = $formID;
            $params                      = array(
                'user' => $this->ObjCommon->manageUserID,
                'currentlanguageID' => $languageID,
                'languageIDs' => $languageIDs
            );
            $resultForm                  = $resultForm = $objCache->get('m_form_config');
            $_POST['globalUploadFolder'] = $resultForm['globalUploadFolder'];
            $_POST['__FORM_SETTINGS']    = $_POST;
            list($formID, $formKey) = $objForm->saveForm($params);
            if ($formID > 0) {
                if ($formID > 0) {
                    $_POST = array(
                        'adminEmailSubject' => $resultForm['adminEmailSubject'],
                        'adminEmailContent' => $resultForm['adminEmailContent'],
                        'userEmailSubject' => $resultForm['userEmailSubject'],
                        'userEmailContent' => $resultForm['userEmailContent']
                    );
                    $objForm->updateEmail('user', $formID);
                    $objForm->updateEmail('admin', $formID);
                }
            }
            $this->setMessage('language.msgFormSettings', "success");
            $this->setRedirect('/form/build/id/' . $formID . "/");
        }
        if ($this->ObjForm->isValid('frmAction', 'submitContent')) {
            $objForm                  = new FormModel();
            $_POST['formID']          = $this->getRequestValue('id');
            $params                   = array(
                'user' => $this->ObjCommon->manageUserID,
                'currentlanguageID' => $languageID
            );
            $_POST['__FORM_SETTINGS'] = array(
                'adminEmails' => $_POST['adminEmails'],
                'emailFromName' => $_POST['emailFromName'],
                'sendConfirmMailToSubmitter' => $_POST['sendConfirmMailToSubmitter'],
                'userEmailFields' => isset($_POST['userEmailFields']) ? $_POST['userEmailFields'] : '',
                'userEmailFields' => isset($_POST['userEmailFields']) ? $_POST['userEmailFields'] : '',
                'codeAction' => $_POST['codeAction'],
                'afterFormSubmission' => $_POST['afterFormSubmission'],
                'afterFormSubmissionActiontext' => $_POST['afterFormSubmissionActiontext'],
                'afterFormSubmissionActionarea' => $_POST['afterFormSubmissionActionarea'],
                'saveToDataBase' => $_POST['saveToDataBase'],
                'submitButtonValue' => isset($_POST['submitButtonValue']) ? $_POST['submitButtonValue'] : '',
                'formID' => $_POST['formID'],
                'brandID' => $_POST['brandID']
            );
            list($formID, $formKey) = $objForm->saveFormAction($params);
            $this->setMessage('language.msgFormSettings', "success");
            $this->setRedirect('/form/build/id/' . $formID . "/");
        }
        $formID = $this->getRequestValue('id');
        $page   = $this->getRequestValue('page');
        if ($formID > 0) {
            $objForm    = new FormModel();
            $params     = array(
                'languageID' => $languageID,
                'formStatus' => "'draft','publish'",
                'formID' => $formID
            );
            $resultForm = $objForm->getForm($params);
            if (empty($resultForm)) {
                $this->setRedirect("/form/build/");
            }
            $resultElement = $objForm->getElements($params);
            $formLayout    = array(
                'top_align_two_column' => "frm-style01",
                'left_align_one_column' => "frm-style02",
                'left_align_two_column' => "frm-style03",
                'top_align_one_column' => "frm-style04"
            );
            $__FORMOBJECT  = array();
            foreach ($resultElement as $elements) {
                if ($elements['uniqueID'] != '') {
                    $elementArr = array(
                        'uniqueID' => $elements['uniqueID'],
                        'order' => $elements['attributeOrder'],
                        'data' => (array) json_decode($elements['extraAttributes'])
                    );
                    if ($elements['attributeType'] == 'html') {
                        $elements['formElementDesc']          = str_replace('"', "", $elements['formElementDesc']);
                        $elementArr['data']['defaults']->text = html_entity_decode($elements['formElementDesc']);
                    }
                    if ($elements['attributeType']) {
                        $formElementID = $elements['formElementID'];
                        $optRes        = $objForm->getOptions($languageID, $formElementID);
                        $items         = array();
                        foreach ($optRes as $options) {
                            array_push($items, array(
                                //'optionID'=>$options['optionID'],
                                'optionOrder' => $options['optionOrder'],
                                'formElementOptionID' => $options['formElementOptionID'],
                                'formElementID' => $options['formElementID'],
                                'text' => html_entity_decode($options['optionDesc']),
                                'selected' => (($options['isDefault'] == 'Yes') ? true : false)
                            ));
                        }
                        $elementArr['data']['defaults']->items       = $items;
                        $elementArr['data']['caption']               = $elements['formElementLabel'];
                        $elementArr['data']['defaults']->text        = $elements['formElementDesc'];
                        $elementArr['data']['defaults']->instruction = $elements['formElementSubText'];
                        $elementArr['data']['defaults']->value       = $elements['formElementValue'];
                        $elementArr['data']['defaults']->error       = $elements['formValidationMessage'];
                    }
                    array_push($__FORMOBJECT, $elementArr);
                }
            }
            $__FORM_SETTINGS = array(
                'formName' => $resultForm['formName'],
                'formDesc' => $resultForm['formDesc'],
                'fieldAlignment' => isset($formLayout[$resultForm['fieldAlignment']]) ? $formLayout[$resultForm['fieldAlignment']] : '',
                'globalUploadFolder' => $resultForm['globalUploadFolder'],
                'accessGroupIDs' => explode(",", $resultForm['accessGroupIDs']),
                'formStatus' => $resultForm['formStatus'],
                'enableCaptcha' => $resultForm['enableCaptcha'],
                'disableForm' => $resultForm['disableForm'],
                'enableAgreement' => $resultForm['enableAgreement'],
                'agreementText' => html_entity_decode($resultForm['agreementText']),
                'disableFormCriteria' => $resultForm['disableFormCriteria'],
                'codeAction' => $resultForm['codeAction'],
                'disableFormMessage' => $resultForm['disableFormMessage'],
                'adminEmails' => $resultForm['adminEmails'],
                'sendConfirmMailToSubmitter' => $resultForm['sendConfirmMailToSubmitter'],
                'sendCopyToSubmitter' => isset($resultForm['sendCopyMailToSubmitter']) ? $resultForm['sendCopyMailToSubmitter'] : '',
                'afterFormSubmission' => $resultForm['afterFormSubmission'],
                'afterFormSubmissionAction' => $resultForm['afterFormSubmissionAction'],
                'afterFormSubmissionActionarea' => $resultForm['afterFormSubmissionAction'],
                'afterFormSubmissionActiontext' => $resultForm['afterFormSubmissionAction'],
                'saveToDataBase' => $resultForm['saveToDataBase'],
                'adminEmailSubject' => $resultForm['adminEmailSubject'],
                'emailFromName' => $resultForm['emailFromName'],
                'adminEmailContent' => $resultForm['adminEmailContent'],
                'userEmailSubject' => $resultForm['userEmailSubject'],
                'userEmailContent' => $resultForm['userEmailContent'],
                'captchaValidation' => $resultForm['captchaValidation'],
                'userEmailFields' => $resultForm['userEmailFields'],
                'submitButtonValue' => isset($resultForm['submitButtonValue']) ? $resultForm['submitButtonValue'] : '',
                'elementRule' => $resultForm['elementRule'],
                'brandID' => $resultForm['brandID']
            );
            $this->ObjView->assign('formID', $formID);
            $this->ObjView->assign('__FORM_SETTINGS', json_encode($__FORM_SETTINGS));
            $resultForm['fieldAlignment'] = isset($formLayout[$resultForm['fieldAlignment']]) ? $formLayout[$resultForm['fieldAlignment']] : '';
            $this->ObjView->assign('fieldAlignment', isset($formLayout[$resultForm['fieldAlignment']]) ? $formLayout[$resultForm['fieldAlignment']] : '');
            $this->ObjView->assign('__FORMOBJECT', json_encode($__FORMOBJECT));
            $this->ObjView->assign('__FORMELEMENT', $__FORMOBJECT);
        }
        if (empty($resultForm)) {
            $resultForm = $objCache->get('m_form_config');
        }
        if ($resultForm['afterFormSubmission'] == 'ShowText') {
            $this->ObjView->assign('afterFormSubmissionActionarea', $resultForm['afterFormSubmissionAction']);
        } else if ($resultForm['afterFormSubmission'] == 'RedirectToUrl') {
            $this->ObjView->assign('afterFormSubmissionActiontext', $resultForm['afterFormSubmissionAction']);
        }
        /* START : list Usergroups */
        $params         = array(
            'languageIDs' => $languageIDs
        );
        $listUsergroups = $ObjUsergroup->listUsergroups($params);
        $this->ObjView->assign('userType', $listUsergroups);
        /* END : list Usergroups */
        $this->ObjView->assignValues($resultForm);
        $this->ObjView->assign('resultForm', $resultForm);
        $this->ObjView->assign('accessGroups', explode(",", $resultForm['accessGroupIDs']));
        if (isset($resultElement))
            $this->ObjView->assign('resultElement', $resultElement);
        $this->ObjView->assign('resActionList', $objFormAction->getActionList());
        $params    = array(
            'languageIDs' => $languageIDs
        );
        $listBrand = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->display('FormBuild.tpl');
    }
    public function destroyAction() {
        $formID  = $this->getRequestValue('id');
        $objForm = new FormModel();
        $objForm->formChangeStatus($formID, "Deleted");
        $this->setMessage('language.msgFormDeleted', "success");
        $this->setRedirect("form/index/");
    }
    public function submissiondestroyAction() {
        $this->ObjCommon->askPrivilege('form/submission/');
        $formID       = $this->getRequestValue('formid');
        $submissionID = $this->getRequestValue('did');
        $objForm      = new FormModel();
        $objForm->submissionChangeStatus($submissionID, "Deleted");
        $this->setMessage('language.msgSubmissionDeleted', "success");
        $this->setRedirect("form/submission/id/" . $formID);
    }
    /* public function cloneAction(){
    $formID=$this->getRequestValue('id');
    $objForm	= 	new FormModel();
    $objForm->createClone($formID);
    $this->setMessage('Clone Created Successfully', "success");
    $this->setRedirect("form/index/");
    } */
    public function ajaxSaveFormAction() {
        $objForm     = new FormModel(); 
        $languageIDs = $this->ObjView->languageIDs;
        $languageID  = $languageIDs['Content'];
        $params      = array(
            'user' => $this->ObjCommon->manageUserID,
            'currentlanguageID' => $languageID,
            'languageIDs' => $languageIDs,
            'brandID'=>$_POST['brandID']
        );
        list($formID, $formKey) = $objForm->saveForm($params);
        /* Assign the newly created formID  into local params array */
        $params['formID']  = $_POST['formID'];
        $params['formKey'] = $objForm->getFormKey($formID);
        list($formID, $formKey) = $objForm->saveFormAction($params);
        if (!empty($_POST['__FORMOBJECT'])) {
            /* Save the elements in the form */
            $objForm->saveFormElements($params);
        }
        $this->setMessage('language.msgFormUpdated', "success");
        echo trim($params['formID']);
        exit;
    }
    public function emailPopUpAction() {
        $this->ObjCommon->askPrivilege('form/build/');
        $objCache = new Cache("file");
        $page     = $this->getRequestValue('page');
        $formID   = $this->getRequestValue('formID');
        $mailType = $this->getRequestValue('usertype');
        if (isset($page) && $page == 'build') {
            $objForm                    = new FormModel();
            $languageIDs                = $this->ObjView->languageIDs;
            $languageID                 = $languageIDs['Content'];
            $_POST['currentlanguageID'] = $languageID;
            if ($this->ObjForm->isValid('frmEmail_user', 'submitEmail_user')) {
                $objForm->updateEmail('user', $formID);
                $this->setMessage('language.msgFormMailUpdated', "success");
            }
            if ($this->ObjForm->isValid('frmEmail_admin', 'submitEmail_admin')) {
                $objForm->updateEmail('admin', $formID);
                $this->setMessage('language.msgFormMailUpdated', "success");
            }
            $params        = array(
                'languageID' => $languageID,
                'formStatus' => "'draft','publish'",
                'formID' => $formID
            );
            $resultForm    = $objForm->getForm($params);
            $resultElement = $objForm->getElements($params);
        } else {
            if ($this->ObjForm->isValid('frmEmail_user', 'submitEmail_user')) {
                $res                     = $objCache->get('m_form_config');
                $res['userEmailSubject'] = $_POST['userEmailSubject'];
                $res['userEmailContent'] = $_POST['userEmailContent'];
                $objCache->set('m_form_config', $res, 'no_ttl');
                $this->setMessage('language.msgFormMailUpdated', "success");
            }
            if ($this->ObjForm->isValid('frmEmail_admin', 'submitEmail_admin')) {
                $res                      = $objCache->get('m_form_config');
                $res['adminEmailSubject'] = $_POST['adminEmailSubject'];
                $res['adminEmailContent'] = $_POST['adminEmailContent'];
                $objCache->set('m_form_config', $res, 'no_ttl');
                $this->setMessage('language.msgFormMailUpdated', "success");
            }
        }
        $result = $objCache->get('m_form_config');
        if (isset($resultForm['userEmailSubject']) && $resultForm['userEmailSubject'] == '') {
            $resultForm['userEmailSubject'] = $result['userEmailSubject'];
        }
        if (isset($resultForm['userEmailContent']) && $resultForm['userEmailContent'] == '') {
            $resultForm['userEmailContent'] = $result['userEmailContent'];
        }
        if (isset($resultForm['adminEmailSubject']) && $resultForm['adminEmailSubject'] == '') {
            $resultForm['adminEmailSubject'] = $result['adminEmailSubject'];
        }
        if (isset($resultForm['adminEmailContent']) && $resultForm['adminEmailContent'] == '') {
            $resultForm['adminEmailContent'] = $result['adminEmailContent'];
        }
        $this->ObjView->assign('mailType', $mailType);
        if (isset($mailType) && $mailType == 'user') {
            $this->ObjView->assign('subject', 'userEmailSubject');
            $this->ObjView->assign('message', 'userEmailContent');
        } else {
            $this->ObjView->assign('subject', 'adminEmailSubject');
            $this->ObjView->assign('message', 'adminEmailContent');
        }
        $this->ObjView->assign('resultElement', $resultElement);
        $this->ObjView->assign('page', $page);
        $this->ObjView->assignValues($resultForm);
        $this->ObjView->display('FormEmailPopup.tpl');
    }
    public function configurationAction() {
        $objCache      = new Cache("file");
        $ObjUsergroup  = new UsergroupModel();
        $objCustommenu = new CustommenuModel();
        //echo '<pre>'; print_r($_POST);
        if ($this->ObjForm->isValid('frmConfig', 'submitConfig')) {
            $mailSettings                                = $objCache->get('m_form_config');
            $globalSettings                              = array();
            $globalSettings['globalUploadFolder']        = $_POST['globalUploadFolder'];
            $globalSettings['accessGroupIDs']            = $_POST['accessGroupIDs'];
            $globalSettings['fieldAlignment']            = $_POST['fieldAlignment'];
            $globalSettings['emailFromName']             = $_POST['emailFromName'];
            $globalSettings['formStatus']                = $_POST['formStatus'];
            $globalSettings['disableForm']               = $_POST['disableForm'];
            $globalSettings['disableFormCriteria']       = $_POST['disableFormCriteria'];
            $globalSettings['disableFormMessage']        = $_POST['disableFormMessage'];
            $globalSettings['enableCaptcha']             = $_POST['enableCaptcha'];
            $globalSettings['afterFormSubmission']       = $_POST['afterFormSubmission'];
            $globalSettings['afterFormSubmissionAction'] = $_POST['afterFormSubmissionAction'];
            $globalSettings['adminEmails']               = $_POST['adminEmails'];
            $globalSettings['userEmailSubject']          = $mailSettings['userEmailSubject'];
            $globalSettings['userEmailContent']          = $mailSettings['userEmailContent'];
            $globalSettings['adminEmailSubject']         = $mailSettings['adminEmailSubject'];
            $globalSettings['adminEmailContent']         = $mailSettings['adminEmailContent'];
            $globalSettings['captchaValidation']         = $_POST['captchaValidation'];
           
            if ($_POST['sendConfirmMailToSubmitter'][0] == 'Yes') {
                $globalSettings['sendConfirmMailToSubmitter'] = 'Yes';
            } else {
                $globalSettings['sendConfirmMailToSubmitter'] = 'No';
            }
            if ($_POST['sendCopyMailToSubmitter'][0] == 'Yes') {
                $globalSettings['sendCopyMailToSubmitter'] = 'Yes';
            } else {
                $globalSettings['sendCopyMailToSubmitter'] = 'No';
            }
            if ($_POST['saveToDataBase'][0] == 'Yes') {
                $globalSettings['saveToDataBase'] = 'Yes';
            } else {
                $globalSettings['saveToDataBase'] = 'No';
            }
            $objCache->set('m_form_config', $globalSettings, 'no_ttl');
            $this->setMessage("Global Settings saved Successfully", "success");
            $this->setRedirect("form/configuration/");
        } else {
            $res = $objCache->get('m_form_config'); //echo '<pre>'; print_r($res); exit;
            $this->ObjView->assignValues($res);
            $this->ObjView->assign('result', $res);
        }
        /* START : list Usergroups */
        $params   = array(
            'languageIDs' => $languageIDs
        );
        $userType = $ObjUsergroup->listUsergroups($params);
        /* END : list Usergroups */
        $this->ObjView->assign('userType', $userType);
        $this->ObjView->display('FormConfiguration.tpl');
    }
    public function ajaxGetEditorAction() {
        $this->ObjView->assign('content', $_POST['content']);
        $this->ObjView->display('AjaxEditor.tpl');
    }
    public function changeFormStatusAction() {
        $this->ObjCommon->askPrivilege('form/build/');
        $objForm = new FormModel();
        $formID  = $this->getRequestValue('id');
        $status  = $this->getRequestValue('status');
        $objForm->formChangeStatus($formID, $status);
        $this->setMessage('Form Status Updated Successfully', "success");
        $this->setRedirect("form/index/");
    }
    public function changeSubmissionStatusAction() {
        $this->ObjCommon->askPrivilege('form/submission/');
        $objForm = new FormModel();
        $formID  = $this->getRequestValue('formid');
        $id      = $this->getRequestValue('id');
        $status  = $this->getRequestValue('status');
        $objForm->submissionChangeStatus($id, $status);
        $this->setMessage('language.msgSubmissionDataUpdated', "success");
        exit;
        //$this->setRedirect("form/submission/id/".$formID);
    }
    public function editorPreviewAction() {
        $params = array(
            'formID' => $_POST['key'],
            'returntype' => (isset($_POST['returntype']) ? $_POST['returntype'] : '')
        );
        $this->getFormContent($params);
    }
    public function getFormContent($params = array()) {
        extract($params);
        $objForm                 = new FormModel();
        $languageIDs             = $this->ObjView->languageIDs;
        $languageID              = $languageIDs['Content'];
        $elementType             = '';
        $params                  = array(
            'languageID' => $languageID,
            'formStatus' => "'publish'",
            'status' => 'Active',
            'formID' => $formID
        );
        $resultForm              = $objForm->getForm($params);
        $resultElement           = $objForm->getElements($params);
        $uploadFolder            = __CORE_PUBLIC_PATH . "/uploads/forms/" . $resultForm['globalUploadFolder'];
        /* $_POST['formKey']	=	$resultForm['formKey'];
        $_POST['formID']	=	$formID; */
        $formDisable             = false;
        $allowAccess             = false;
        $resultForm['userGroup'] = isset($resultForm['userGroup']) ? $resultForm['userGroup'] : '';
        switch ($resultForm['userGroup']) {
            case '0':
                $allowAccess = true;
                break;
            case 'registered':
                if ($this->ObjSession->getSession("REGISTERED_USER_ID") > 0) {
                    $allowAccess = true;
                }
                break;
            default:
                $allowAccess = true;
        }
        if (!$allowAccess) {
            $this->ObjView->display('NoPage.tpl');
            exit;
        }
        $countryList = array();
        foreach ($resultElement as $key => $element) {
            $attributeType     = $element['attributeType'];
            $formElementID     = $element['formElementID'];
            $extraAttributes   = json_decode($element['extraAttributes']);
            $allowUserChoice   = isset($extraAttributes->allowUserChoice) ? $extraAttributes->allowUserChoice : '';
            $elementType[$key] = $attributeType;
            switch ($attributeType) {
                case 'select':
                case 'select_multiple':
                    $resultElement[$key]['options'] = $objForm->getOptions($languageID, $formElementID);
                    if (isset($allowUserChoice->status) && $allowUserChoice->status == 'Yes') {
                        array_push($resultElement[$key]['options'], array(
                            0 => "-1",
                            1 => $this->getLanguageValue("lblOther")
                        ));
                    }
                    break;
                case 'radio':
                case 'checkbox':
                    $resultElements = $objForm->getOptions($languageID, $formElementID);
                    $tempArray      = array();
                    foreach ($resultElements as $options) {
                        array_push($tempArray, $options['formElementOptionID'] . "->" . $options['optionDesc']);
                    }
                    $resultElement[$key]['options'] = implode("~*", $tempArray);
                    if (isset($allowUserChoice->status) && $allowUserChoice->status == 'Yes') {
                        $resultElement[$key]['options'] .= "~*0->" . $this->getLanguageValue("lblOther");
                    }
                    break;
                case 'country':
                    $objCountry = new CountryModel();
                    if (empty($countryList)) {
                        $countryList = $objCountry->listCountries($languageIDs);
                    }
                    $resultElement[$key]['options'] = $countryList;
                    if (isset($allowUserChoice->status) && $allowUserChoice->status == 'Yes') {
                        array_push($resultElement[$key]['options'], array(
                            0 => "0",
                            1 => $this->getLanguageValue("lblOther")
                        ));
                    }
                    break;
                case 'businesstype':
                    $ObjBusinessType                = new BusinessTypeModel();
                    $resultElement[$key]['options'] = "<option value>" . $this->getLanguageValue("lblSelect") . "</option>";
                    $resultElement[$key]['options'] .= $ObjBusinessType->getBusinessTypeOption($languageIDs, $businessType = "others");
                default:
                    break;
            }
        }
        $this->ObjView->assign('resultElement', $resultElement);
        $this->ObjView->assign('formID', $formID);
        $this->ObjView->assign('elementType', $elementType);
        $this->ObjView->assign('resultForm', $resultForm);
        if ($returntype == 'html') {
            return $this->ObjView->fetch('Forminclude.tpl');
        } else {
            $this->ObjView->display('Forminclude.tpl');
        }
    }
    public function exportAction() {
        $this->ObjCommon->askPrivilege('form/submission/');
        $objForm            = new FormModel();
        $languageIDs        = $this->ObjView->languageIDs;
        $languageID         = $languageIDs['Content'];
        $settingsDateFormat = $this->getSettingValue('site_settings', 'date_format');
        $type               = $this->getRequestValue('type');
        $formID             = $this->getRequestValue('id');
        switch ($type) {
            case 'submission':
                if ($formID > 0) {
                    $params     = array(
                        'languageID' => $languageID,
                        'formStatus' => "'draft','publish'",
                        'formID' => $formID
                    );
                    $resultForm = $objForm->getForm($params);
                    if (empty($resultForm)) {
                        $this->setRedirect("form/index/");
                    }
                    $resultElement                = $objForm->getElements($params);
                    $searchField                  = array();
                    $searchFieldElements          = array();
                    $formElements[]               = array(
                        'dateSubmitted',
                        $this->getLanguageValue("lblSubmittedDate")
                    );
                    $formElements[]               = array(
                        'submittedIP',
                        $this->getLanguageValue("lblSubmittedIP")
                    );
                    $elementName['dateSubmitted'] = $this->getLanguageValue("lblSubmittedDate");
                    $elementName['submittedIP']   = $this->getLanguageValue("lblSubmittedIP");
                    foreach ($resultElement as $key => $elements) {
                        $formElementName = $elements['attributeType'] . "_" . $elements['formElementID'];
                        if ($elements['attributeType'] != 'html' && $elements['attributeType'] != 'submit') {
                            $formAllElements[$elements['attributeType']][] = $formElementName;
                            $formElements[]                                = array(
                                $formElementName,
                                $elements['formElementLabel']
                            );
                            $elementName[$formElementName]                 = $elements['formElementLabel'];
                        }
                    }
                    if (isset($_POST['submit'])) {
                        $params      = array(
                            "languageID" => $languageID,
                            "formKey" => $resultForm['formKey'],
                            "formAllElements" => $formAllElements,
                            "formElement" => $_POST['formElement'],
                            "limitTo" => 0
                        );
                        $submissions = $objForm->listSubmission($params);
                        $options     = array(
                            'filename' => 'form_submissions.csv',
                            'force_header' => 'yes'
                        );
                        $heads       = array();
                        $keys        = array();
                        foreach ($elementName as $key => $head) {
                            if (in_array($key, $_POST['formElement'])) {
                                $heads[] = $head;
                                $keys[]  = $key;
                            }
                        }
                        $resSubmissions = array();
                        foreach ($submissions as $submission) {
                            $tmpSubmission = array();
                            foreach ($keys as $key) {
                                $tmpSubmission[] = $submission[$key];
                            }
                            $resSubmissions[] = $tmpSubmission;
                        }
                        $ObjCsv        = new Csv();
                        $csvOutputData = $ObjCsv->output($resultForm['formKey'] . '_form_submissions.csv', $resSubmissions, $heads);
                    }
                    $this->ObjView->assign('formElements', $formElements);
                    $this->ObjView->assign('resultForm', $resultForm);
                    $this->ObjView->assign('formID', $formID);
                    $this->ObjView->display('FormSubmissionsExport.tpl');
                } else {
                    $this->setRedirect("form/index/");
                }
                break;
        }
    }
    //Add/Build
    public function newAction() {
        $this->buildAction();
    }
	public function editAction() {
        
    }
}
