<?php
/**
 * @version    CVS: 1.0.0
 * @package    com_jbeasyformmaker
 * @author     Priya Bose <support@joomlabuff.com>
 * @copyright  2016 www.joomlabuff.com
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 */
// no direct access
defined ( '_JEXEC' ) or die ();
require_once JPATH_LIBRARIES . '/f0f/include.php';
require_once JPATH_ADMINISTRATOR . '/components/com_jbeasyformmaker/helpers/helper.php';
/**
 * Formbuilder - formbuilder Helper Class.
 *
 * @package Joomla.Site
 *          @subpakage Formbuilder.formbuilder
 */
abstract class ModJBEasyFormMakerHelper {
	
	/**
	 * Get a list of articles from a specific category
	 *
	 * @param
	 *        	\Joomla\Registry\Registry &$params object holding the models parameters
	 *        	
	 * @return mixed
	 *
	 * @since 1.6
	 */
	public static function getCForm(&$params) {
		$cform_id = $params->get ( 'cform_id' );
		$db = JFactory::getDbo ();
		$query = $db->getQuery ( true );
		$query->select ( '*' );
		$query->from ( '#__jbeasyformmaker_cforms' );
		$query->where ( 'jbeasyformmaker_cform_id=' . $params->get ( 'cform_id' ) );
		$db->setQuery ( $query );
		$item = $db->loadObject ();
		$extras = array ();
		JBHelper::Shortcode ( $item );
		return $item;
	}
	
	/**
	 * Method to send Mail
	 */
	public static function getJBEasyFormMakerDataAjax() {
		$app = JFactory::getApplication ();
		// Check for request forgeries.
		JSession::checkToken () or jexit ( JText::_ ( 'JINVALID_TOKEN' ) );
		
		$formbuilder_cform_id = $app->input->getInt ( 'jbeasyformmaker_cform_id' );
		$config = JFactory::getConfig ();
		$item = self::getItem ( $formbuilder_cform_id );
		
		$inputs = $app->input->getArray ( $_POST );
		
		//print_r($inputs); exit;
		  self::sendMailToAdmin ( $inputs, $item );
		// $inputs['send_copy']
			//echo json_encode(array('status' =>1 , 'message' => JText::_ ( $item->notify_success )));
		   self::showResponse ( 1, 'success', array (
				JText::_ ( $item->notify_success ) 
		) );  
		  
		  
		//exit;
	}
	public static function getItem($anyform_item_id) {
		$db = JFactory::getDbo ();
		$query = $db->getQuery ( true );
		$query->select ( '*' );
		$query->from ( '#__jbeasyformmaker_cforms' );
		$query->where ( 'jbeasyformmaker_cform_id=' . $anyform_item_id );
		$db->setQuery ( $query );
		return $db->loadObject ();
	}
	public static function sendMailToAdmin($data, $item) {
		$app = JFactory::getApplication ();
	//$jbeasyformmaker_cform_id = $app->input->getInt ( 'jbeasyformmaker_cform_id' );
		$config = JFactory::getConfig ();		
		$jInput = JFactory::getApplication ()->input;
		// get the current module params
		
		$admin_email = $item->to_email;
		$admin_fromname = $item->to_name;
		
		if (empty ( $admin_email )) {
			if (version_compare ( JVERSION, '3.0', 'ge' )) {
				$admin_email = $config->get ( 'mailfrom' );
				$admin_fromname = $config->get ( 'fromname' );
			} else {
				$admin_email = $config->getValue ( 'config.mailfrom' );
				$admin_fromname = $config->getValue ( 'config.fromname' );
			}
		}
		
		if (version_compare ( JVERSION, '3.0', 'ge' )) {
			$sitename = $config->get ( 'sitename' );
		} else {
			$sitename = $config->getValue ( 'config.sitename' );
		}
		
		$bcc_email = $item->to_bcc_email;
		$cc_email = $item->to_cc_email;
		
		$ip_remote = $jInput->server->get ( 'REMOTE_ADDR' );
		
		$fromname = isset ( $data ['name'] ) ? $data ['name'] : $app->get ( 'fromname' );
		
		$mailfrom = isset ( $data ['email'] ) ? $data ['email'] : $app->get ( 'mailfrom' );
		// $fromname = $app->get ( 'fromname' );
		
		if (isset ( $data ['first_name'] )) {
			$fromname = $data ['first_name'];
		}
		if (isset ( $data ['last_name'] )) {
			$fromname .= ' ' . $data ['last_name'];
		}
		
		// print_r()
		if (isset ( $data ['email'] )) {
			$mailfrom = JStringPunycode::emailToPunycode ( $data ['email'] );
		}
		
		// Prepare email body
		$prefix = JText::sprintf ( 'JB_FORMBUILDER_ENQUIRY_TEXT', $sitename );
		
		$subject = isset ( $data ['subject'] ) ? $data ['subject'] : $mailfrom . ' ' . $prefix;
		$body = $prefix . $fromname . ' <' . $mailfrom . '>';
		
		$mail_body = '';
		foreach ( $data as $key => $value ) {
			if (is_array ( $value )) {
				$value = implode ( ',', $value );
			}
			$item->email_message = str_replace ( '[' . $key . ']', $value, $item->email_message );
			$mail_body = $item->email_message;
		}
		
		if (isset ( $data ['message'] ) && ! empty ( $data ['message'] )) {
			$msg = preg_replace ( '#<script(.*?)>(.*?)</script>#is', '', $data ['message'] );
			$body .= "\n" . $msg;
		}
		$body .= "\n" . JText::sprintf ( 'JB_ANYFORM_EMAIL_THANKS', $sitename );
		$mail_body = "\r\n\r\n" . stripslashes ( $body );
		$mail = JFactory::getMailer ();
		
		$mail->addRecipient ( $admin_email );
		
		try {
			if (version_compare ( JVERSION, '3.0', 'ge' )) {
				$mail->addReplyTo ( $mailfrom, $fromname );
			} else {
				$mail->addReplyTo ( array (
						$mailfrom,
						$fromname 
				) );
			}
		} catch ( Exception $e ) {
			// do nothing
		}
		
		if (isset ( $cc ) && ! empty ( $cc )) {
			$mail->addCC ( $cc_email );
		}
		if (isset ( $bcc_email ) && ! empty ( $bcc_email )) {
			$mail->addBCC ( $bcc_email );
		}
		
		$mail->setSender ( array (
				$mailfrom,
				$fromname 
		) );
		$mail->setSubject ( $sitename . ': ' . $subject );
		$mail->setBody ( $mail_body );
		
		// print_r($mail); exit;
		return $mail->Send ();
	}
	
	/**
	 * Method to validate data
	 *
	 * @param array $post        	
	 * @return $errors
	 */
	public static function getValidatedData($post) {
		$errors = array ();
		if (empty ( $post ['name'] )) {
			// $sender_email = $post['email'];
			$errors ['name'] = JText::_ ( 'JB_ANYFORM_MISSING_NAME_FIELD' );
		}
		
		if (empty ( $post ['email'] )) {
			$errors ['email'] = JText::_ ( 'JB_ANYFORM_MISSING_EMAIL_ID' );
		}
		
		if (isset ( $post ['email'] ) && ! JMailHelper::isEmailAddress ( $post ['email'] )) {
			$errors ['email'] = JText::_ ( 'JB_ANYFORM_MISSING_EMAIL_ID' );
		}
		
		if (isset ( $post ['phone'] )) {
			if (! preg_match ( "/^[1-9][0-9]*$/", $post ['phone'] )) {
				$errors ['phone'] = JText::_ ( 'JB_ANYFORM_INVALID_PHONE' );
			}
		}
		
		if (! isset ( $post ['askQuestion'] )) {
			if (isset ( $post ['subject'] ) && empty ( $post ['subject'] )) {
				$errors ['subject'] = JText::_ ( 'JB_ANYFORM_MISSING_SUBJECT' );
			}
		} else {
			if (empty ( $post ['phone'] )) {
				$errors ['phone'] = JText::_ ( 'JB_ANYFORM_MISSING_PHONE' );
			} else {
				if (! preg_match ( "/^[1-9][0-9]*$/", $post ['phone'] )) {
					$errors ['phone'] = JText::_ ( 'JB_ANYFORM_INVALID_PHONE' );
				}
			}
		}
		
		if (empty ( $post ['message'] )) {
			$errors ['message'] = JText::_ ( 'JB_ANYFORM_MISSING_MESSAGE' );
		}
		
		if (isset ( $post ['captcha_enabled'] ) && ! isset ( $_POST ['g-recaptcha-response'] )) {
			$errors ['captcha'] = JText::_ ( 'JB_ANYFORM_INVALID_CAPTCHA' );
		}
		
		if (isset ( $post ['captcha_enabled'] )) {
			$res = self::captcha ( 'onCheckAnswer', $_POST ['g-recaptcha-response'] );
			if (! $res [0]) {
				$errors ['captcha'] = JText::_ ( 'JB_ANYFORM_INVALID_CAPTCHA' );
			}
		}
		
		return $errors;
	}
	
	/**
	 * Method to show response
	 *
	 * @param boolean $status        	
	 * @param string $message        	
	 * @param array $warnings        	
	 */
	protected static function showResponse($status, $message, $warnings = array()) {
		$app = JFactory::getApplication ();
		$response = array (
				'status' => $status,
				'message' => $message,
				'warnings' => $warnings 
		);
		 JFactory::getDocument ()->setMimeEncoding ( 'application/json' );
		 echo json_encode ( $response );
 

		$app->close ();
	}
	
	/**
	 * Method to clean input
	 *
	 * @param unknown $input        	
	 */
	public static function cleanInput($input) {
		return htmlentities ( is_array ( $input ) ? implode ( ', ', $input ) : $input, ENT_QUOTES, "UTF-8" );
	}
}
