<?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();
        $formID      = $this->getRequestValue('key');
        $languageIDs = $this->ObjView->languageIDs;
        $languageID  = $languageIDs['Current'];
		$userSubgroupID    = ($this->ObjSession->getSession("REGISTERED_USER_GROUP_ID")>0)?$this->ObjSession->getSession("REGISTERED_USER_GROUP_ID"):'0';
        $params      = array(
            'languageID' => $languageID,
            'formStatus' => "'publish','Draft'",
            'formID' => $formID,
            'userGroupID' => $userSubgroupID
        );
        $resultForm  = $objForm->getForm($params);
        if (empty($resultForm)) {
            $this->setRedirect("/");
        }
        $resultElement    = $objForm->getElements($params);
        $uploadFolder     = __CORE_PUBLIC_PATH . "/uploads/forms/" . $resultForm['globalUploadFolder'];
        $_POST['formKey'] = $resultForm['formKey'];
        $_POST['formID']  = $formID;
        $formDisable      = false;
        switch ($resultForm['disableForm']) {
            case 'afterdays':
                $disableFormCriteria = $resultForm['disableFormCriteria'];
                $formCreatedDate     = $resultForm['formCreatedDate'];
                $now                 = date('Y-m-d');
                $formCreatedDate     = date('Y-m-d', strtotime("+" . $disableFormCriteria . " day", strtotime($formCreatedDate)));
                if ($now > $formCreatedDate) {
                    $formDisable        = true;
                    $disableFormMessage = $resultForm['disableFormMessage'];
                }
                break;
            case 'aftersubmission':
                if ($resultForm['submissions'] >= $resultForm['disableFormCriteria']) {
                    $formDisable        = true;
                    $disableFormMessage = $resultForm['disableFormMessage'];
                }
                break;
        }
        //echo '<pre>'; print_r($resultForm); 
        //exec('rm -R '.$uploadFolder);
        //exec('rm -R '.__CORE_PUBLIC_PATH."/uploads/formsoorjitForm_516fd19bb913cimages_image_47_130418162633.jpg");
        //echo 'oorjitForm_'.$resultForm['formKey'];
        $validationEnable = false;
        $tet              = "1";
        if (isset($_POST['submitForm'])) {
            $validationEnable = true;
            foreach ($resultElement as $element) {
                if ($element['validateRule'] != '') {
                    $validationEnable = $validationEnable && false;
                }
                if ($element['attributeType'] == 'file') {
                    $extraAttributes = json_decode($element['extraAttributes']);
                    if (!empty($extraAttributes->defaults->allowedExtensions)) {
                        $validationEnable = $validationEnable && false;
                    }
                }
            }
        }
        if (!$formDisable) {
            $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;
                }
            }
            //echo '<pre>'; print_r($resultForm); exit;
            //echo '<pre>'; print_r($resultElement); exit;
            $this->ObjView->assign('resultElement', $resultElement);
            $this->ObjView->assign('formID', $formID);
            $this->ObjView->assign('elementType', isset($elementType) ? $elementType : array());
            $this->ObjView->assign('resultForm', $resultForm);
        } else {
            $this->ObjView->assign('formDisable', $formDisable);
            $this->ObjView->assign('disableFormMessage', $disableFormMessage);
        }
        $enable_captcha = $this->getSettingValue('security_settings', 'enable_captcha');
        if ($this->ObjForm->isValid('oorjitForm_' . $resultForm['formKey'], 'submitForm') || $validationEnable) {            
            $errorExists = 0;
            if($_POST['oorjitFormSecurityCode']!='' && $_SESSION['captcha_val']!='' && ($_POST['oorjitFormSecurityCode']!=$_SESSION['captcha_val']) && $enable_captcha=='Yes') {
                $this->setMessage(trim($this->getLanguageValue("errSecurityCode")), "error");
                $errorExists  =1;
            } 
            if($errorExists<=0) {
                $objCache       = new Cache("file");
                $globalSettings = $objCache->get('m_form_config');
                $formElements   = array();
                $formValues     = array();
                foreach ($resultElement as $elements) {
                    if ($elements['attributeType'] != 'html' && $elements['attributeType'] != 'submit') {
                        $formAttributeName = $elements['attributeType'] . "_" . $elements['formElementID'];
                        if ($elements['attributeType'] == 'image' || $elements['attributeType'] == 'file') {
                            if (!is_dir($uploadFolder)) {
                                mkdir($uploadFolder, 0777);
                            }
                            if ($elements['attributeType'] == 'image') {
                                $fileName = uniqid('oorjitForm') . "_" . $_POST[$formAttributeName];
                                copy($_POST[$formAttributeName . "_temp"], $uploadFolder . "/" . $fileName);
                            } else if ($elements['attributeType'] == 'file') {
                                if ($_FILES[$formAttributeName]['name'] != '') {
                                    $fileName = uniqid('oorjitForm') . "_" . $_FILES[$formAttributeName]['name'];
                                    copy($_FILES[$formAttributeName]["tmp_name"], $uploadFolder . "/" . $fileName);
                                } else {
                                    $fileName = '';
                                }
                            }
                            $_POST[$formAttributeName] = ($fileName != '') ? $uploadFolder . "/" . $fileName : '';
                        } else if ($elements['attributeType'] == 'date') {
                            $settingsDateFormat        = $this->getSettingValue('site_settings', 'date_format');
                            $_POST[$formAttributeName] = $this->convertDateForSQL($_POST[$formAttributeName], $settingsDateFormat);
                        }
                        array_push($formElements, $formAttributeName);
                        if (is_array($_POST[$formAttributeName])) {
                            array_push($formValues, implode(",", $_POST[$formAttributeName]));
                        } else {
                            array_push($formValues, $_POST[$formAttributeName]);
                        }
                    }
                }
                $locationDetails = array(); {
                    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                        $ipAddress = $_SERVER['HTTP_CLIENT_IP'];
                    } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                        $ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
                    } else {
                        $ipAddress = $_SERVER['REMOTE_ADDR'];
                    }
                    //Usage => new geoip lib
                    $locationSettings['provider'] = $this->getSettingValue('product_cart_settings', 'location_provider');
                    if ($locationSettings['provider'] == 'maxmind') {
                        $locationSettings['apiKey'] = $this->getSettingValue('product_cart_settings', 'maxmind_api_key');
                    } else {
                        $locationSettings['apiKey'] = $this->getSettingValue('product_cart_settings', 'ipinfodb_api_key');
                    }
                    $locationSettings['apiKey'] = $this->encryptDecrypt("decrypt", $locationSettings['apiKey']);
                    $ObjGeoip                   = new Geoip($locationSettings);
                    $locationDetails            = $ObjGeoip->getCity($ipAddress);
                }
                $userAgent  = $_SERVER['HTTP_USER_AGENT'];
                $parameters = array(
                    "fields" => $formElements,
                    "values" => $formValues,
                    "formDetails" => $resultForm,
                    "elementDetails" => $resultElement,
                    "locationDetails" => $locationDetails,
                    "userAgent" => $userAgent,
                    "ipAddress" => $ipAddress
                );
                if ($resultForm['saveToDataBase'] != 'No') {
                    $objForm->saveSubmission($languageID, $parameters);
                }
                $mail_settings                  = $this->getSettingValue('mail_settings');
                $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                $ObjMail                        = new Mail($mail_settings);
                $ObjMail->IsHTML();
                $this->sendMail($ObjMail, $languageID, $parameters, 'admin', $globalSettings);
                if ($resultForm['sendConfirmMailToSubmitter'] == 'Yes') {
                    preg_match_all("/\{(.+?)\}/", $resultForm['userEmailFields'], $emails);
                    $emailFields  = $emails[1];
                    $userEmailIDs = array();
                    foreach ($emailFields as $emailField) {
                        array_push($userEmailIDs, $_POST[$emailField]);
                    }
                    if (!empty($userEmailIDs)) {
                        $parameters['userEmail'] = $userEmailIDs;
                        $this->sendMail($ObjMail, $languageID, $parameters, 'user', $globalSettings);
                    }
                }

                switch ($resultForm['afterFormSubmission']) {
                    case 'NoAction':
                        break;
                    case 'ShowText':
                        $this->setMessage($resultForm['afterFormSubmissionAction'], "success");
                        $this->setRedirect("form/index/key/" . $formID);
                        break;
                    case 'RedirectToUrl':
                    case 'RedirectToMenu':
                        $this->setRedirect($resultForm['afterFormSubmissionAction']);
                        break;
                }
            }
        }        
        $this->ObjView->assign('enable_captcha', $enable_captcha);
        $this->ObjView->display('Form.tpl');
    }
    private function sendMail($ObjMail, $languageID, $param, $reciever, $globalSettings) {
        $objForm     = new FormModel();
        $languageIDs = $this->ObjView->languageIDs;
        $languageID  = $languageIDs['Current'];
        $formDetails = $param['formDetails'];
        $fields      = $param['fields'];
        if ($formDetails['emailFromName'] == '') {
            $formDetails['emailFromName'] = $globalSettings['emailFromName'];
        }
        $fromEmailName = $formDetails['emailFromName'];
        $fromEmailId   = $this->getSettingValue('site_settings', 'global_notification_email');
        $companyLogo   = $this->getSettingValue('company_information', 'company_logo');
        $siteName      = $this->getSettingValue('site_settings', 'site_name');
        $siteUrl       = $this->getSettingValue('site_settings', 'global_http_url');
        if ($reciever == 'admin') {
            if ($formDetails['adminEmails'] == '') {
                $formDetails['adminEmails'] = $globalSettings['adminEmails'];
            }
            if ($formDetails['adminEmailSubject'] == '') {
                $formDetails['adminEmailSubject'] = $globalSettings['adminEmailSubject'];
            }
            if ($formDetails['adminEmailContent'] == '') {
                $formDetails['adminEmailContent'] = $globalSettings['adminEmailContent'];
            }
            $toEmailID = explode(",", $formDetails['adminEmails']);
            if (empty($formDetails['adminEmails'])) {
                return true;
            }
            $Subject = $formDetails['adminEmailSubject'];
            $body    = $formDetails['adminEmailContent'];
            if (strrpos($body, '}]') != false) {
                $body = preg_replace("/\-(.+?)\-/", "", $body);
                foreach ($fields as $field) {
                    $elem = explode("_", $field);
                    $text = $objForm->getOptionLabel($_POST[$field], $elem[1], $languageID, $elem[0]);
                    if ($elem[0] == 'image') {
                        $imageUrl = $siteUrl . "public/" . end(explode("/public/", $text));
                        $text     = "<img src='" . $imageUrl . "' height='100' width='100'/>";
                    } else if ($elem[0] == 'file') {
                        $fileUrl = $siteUrl . "public/" . end(explode("/public/", $text));
                        $text    = "<a href='" . $fileUrl . "'/>" . $fileUrl . "</a>";
                    }
                    $body = str_replace('[{' . $field . '}]', $text, $body);
                }
            }
        } else {
            $toEmailID = $param['userEmail'];
            if (empty($toEmailID)) {
                return true;
            }
            if ($formDetails['userEmailSubject'] == '') {
                $formDetails['userEmailSubject'] = $globalSettings['userEmailSubject'];
            }
            if ($formDetails['userEmailContent'] == '') {
                $formDetails['userEmailContent'] = $globalSettings['userEmailContent'];
            }
            $Subject = $formDetails['userEmailSubject'];
            $body    = $formDetails['userEmailContent'];
            if (strrpos($body, '}]') != false) {
                $body = preg_replace("/\-(.+?)\-/", "", $body);
                foreach ($fields as $field) {
                    $elem = explode("_", $field);
                    $text = $objForm->getOptionLabel($_POST[$field], $elem[1], $languageID, $elem[0]);
                    if ($elem[0] == 'image') {
                        $imageUrl = $siteUrl . "public/" . end(explode("/public/", $text));
                        $text     = "<img src='" . $imageUrl . "' height='100' width='100'/>";
                    } else if ($elem[0] == 'file') {
                        $fileUrl = $siteUrl . "public/" . end(explode("/public/", $text));
                        $text    = "<a href='" . $fileUrl . "'/>" . $fileUrl . "</a>";
                    }
                    $body = str_replace('[{' . $field . '}]', $text, $body);
                }
            }
        }
        $body = preg_replace("/{\[(.+?)\]}/", "Not Specified", $body);
        $this->ObjView->assign('emailbody', html_entity_decode($body));
        $this->ObjView->assign('companyLogo', $companyLogo);
        $this->ObjView->assign('siteName', $siteName);
        $this->ObjView->assign('siteUrl', $siteUrl);
        $email_body = $this->ObjCommon->fetch('email_templates/Layout.tpl', $languageID);
        $ObjMail->sendMail(array(
            $fromEmailId,
            $fromEmailName
        ), $toEmailID, $Subject, $email_body);
        if ($ObjMail->Send()) {
            $ObjMail->clearAddresses();
        }
    }
    public function ajaxStateAction() {
        $ObjState        = new StateModel();
        $languageIDs     = $this->ObjView->languageIDs;
        $countryID       = $_POST['countryID'];
        $stateSelectedID = $_POST['stateID'];
        $resListState    = $ObjState->listStates($languageIDs, $countryID, $status = "Active", $page = "");
        $this->ObjView->assign('resListState', $resListState);
        $this->ObjView->assign('stateSelectedID', $stateSelectedID);
        $this->ObjView->display('CountryState.tpl');
    }
    public function isExists($params) {
        $objForm = new FormModel();
        $formKey = $_POST['formKey'];
        $params  = array(
            'formKey' => $formKey,
            'field' => $params['field'],
            'value' => $params['value']
        );
        $res     = $objForm->checkValueExists($params);
        if ($res['exist']) {
            return false;
        } else {
            return true;
        }
    }
}

