<?php
class OTW_Shortcode_Contact_Form extends OTW_Shortcodes{
	
	public $form_name = 'otw-shortcode-contanct-form';
	
	public $form_anchor = 'otwcf';
	
	private $sessions = array();
	
	public function __construct(){
		
		$this->has_custom_options = true;
		
		$this->get_sessions();
		
		parent::__construct();
	}
	
	private function get_sessions(){
	
		$sessions = get_option( $this->form_name.'_sessions' );
		
		if( !is_array( $sessions ) ){
			$sessions = array();
		}
		
		$this->sessions = array();
		foreach( $sessions as $session_time ){
			
			if( $session_time > strtotime( 'now -1 hour' ) ){
				$this->sessions[] = $session_time;
			}
		}
	}
	
	/**
	 * register external libs
	 */
	public function register_external_libs(){
		
		
		$this->add_external_lib( 'css', 'otw-shortcode-general_foundicons', $this->component_url.'css/general_foundicons.css', 'all', 10 );
		$this->add_external_lib( 'css', 'otw-shortcode-social_foundicons', $this->component_url.'css/social_foundicons.css', 'all', 20 );
		
		$this->add_external_lib( 'css', 'otw-shortcode', $this->component_url.'css/otw_shortcode.css', 'all', 100 );
		
		$this->add_external_lib( 'js', 'otw-shortcode-core', $this->component_url.'js/otw_shortcode_core.js', 'all', 99, array( 'jquery' ) );
		$this->add_external_lib( 'js', 'otw-shortcode', $this->component_url.'js/otw_shortcode.js', 'front', 100 );
		
		$this->add_external_lib( 'js', 'otw-shortcode_live_preview', $this->component_url.'js/otw_shortcode_live_preview.js', 'live_preview', 200 );
	}
	
	/**
	 * apply settings
	 */
	public function apply_settings(){
		
		$this->settings = array(
			
			'sendcopy' => array(
				'yes'   => $this->get_label( 'yes(default)' ),
				'no'    => $this->get_label( 'no' )
			),
			'default_sendcopy' => 'yes',
			
			'recaptcha' => array(
				'yes'   => $this->get_label( 'yes' ),
				'no'    => $this->get_label( 'no(default)' )
			),
			'default_recaptcha' => 'no',
			
			'default_success_msg' => 'Message sent.',
			
			'default_error_msg' => ' One or more errors found.',
			
			'default_field_error_msg' => 'Fill this field in'
		);
		
	}
	
	/**
	 * Shortcode admin interface
	 */
	public function build_shortcode_editor_options(){
		
		$html = '';
		
		$source = array();
		if( isset( $_POST['shortcode_object'] ) ){
			$source = $_POST['shortcode_object'];
		}
		
		$html .= OTW_Form::text_input( array( 'id' => 'otw-shortcode-element-sendfrom', 'label' => $this->get_label( 'Email to send from' ), 'description' => $this->get_label( 'The email address to send mails from.' ), 'parse' => $source )  );
		
		$html .= OTW_Form::text_input( array( 'id' => 'otw-shortcode-element-fromtext', 'label' => $this->get_label( 'From text' ), 'description' => $this->get_label( 'Sender name.' ), 'parse' => $source )  );
		
		$html .= OTW_Form::select( array( 'id' => 'otw-shortcode-element-sendcopy', 'label' => $this->get_label( 'Send copy' ), 'description' => $this->get_label( 'Enable "Send a copy of this email to yourself" checkbox.' ), 'parse' => $source, 'options' => $this->settings['sendcopy'], 'value' => $this->settings['default_sendcopy'] ) );
		
		$html .= OTW_Form::select( array( 'id' => 'otw-shortcode-element-recaptcha', 'label' => $this->get_label( 'Enable reCAPTCHA' ), 'description' => $this->get_label( 'Enables reCAPTCHA. More info on reCAPTCHA <a href="http://www.google.com/recaptcha">here</a>' ), 'parse' => $source, 'options' => $this->settings['recaptcha'], 'value' => $this->settings['default_recaptcha'] ) );
		
		$html .= OTW_Form::text_input( array( 'id' => 'otw-shortcode-element-recaptcha_public_key', 'label' => $this->get_label( 'reCAPTCHA public key' ), 'description' => $this->get_label( 'Enter reCAPTCHA publick key' ), 'parse' => $source )  );
		
		$html .= OTW_Form::text_input( array( 'id' => 'otw-shortcode-element-recaptcha_private_key', 'label' => $this->get_label( 'reCAPTCHA private key' ), 'description' => $this->get_label( 'Enter reCAPTCHA private key' ), 'parse' => $source )  );
		
		$html .= OTW_Form::text_input( array( 'id' => 'otw-shortcode-element-success_msg', 'label' => $this->get_label( 'Success message' ), 'description' => $this->get_label( 'Enter success message.' ), 'parse' => $source, 'value' => $this->settings['default_success_msg'] )  );
		
		$html .= OTW_Form::text_input( array( 'id' => 'otw-shortcode-element-error_msg', 'label' => $this->get_label( 'Error message' ), 'description' => $this->get_label( 'Enter error message.' ), 'parse' => $source, 'value' => $this->settings['default_error_msg'] )  );
		
		$html .= OTW_Form::text_input( array( 'id' => 'otw-shortcode-element-field_error_msg', 'label' => $this->get_label( 'Field error' ), 'description' => $this->get_label( 'Enter field error message.' ), 'parse' => $source, 'value' => $this->settings['default_field_error_msg'] )  );
		
		
		return $html;
	}
	
	/**
	 * Shortcode admin interface custom options
	 */
	public function build_shortcode_editor_custom_options(){
		
		$html = '';
		
		$source = array();
		if( isset( $_POST['shortcode_object'] ) ){
			$source = $_POST['shortcode_object'];
		}
		
		$html .= OTW_Form::text_input( array( 'id' => 'otw-shortcode-element-css_class', 'label' => $this->get_label( 'CSS Class' ), 'description' => $this->get_label( 'If you\'d like to style this element separately enter a name here. A CSS class with this name will be available for you to style this particular element..' ), 'parse' => $source )  );
		
		return $html;
	}
	
	/** build shortcode
	 *
	 *  @param array
	 *  @return string
	 */
	public function build_shortcode_code( $attributes ){
		
		$code = '';
		
		if( !$this->has_error ){
		
			$code = '[otw_shortcode_contact_form';
			
			$code .= $this->format_attribute( 'sendfrom', 'sendfrom', $attributes, false, '', true );
			
			$code .= $this->format_attribute( 'fromtext', 'fromtext', $attributes, false, '', true );
			
			$code .= $this->format_attribute( 'sendcopy', 'sendcopy', $attributes );
			
			$code .= $this->format_attribute( 'recaptcha', 'recaptcha', $attributes );
			
			$code .= $this->format_attribute( 'recaptcha_public_key', 'recaptcha_public_key', $attributes, false, '', true );
			
			$code .= $this->format_attribute( 'recaptcha_private_key', 'recaptcha_private_key', $attributes, false, '', true );
			
			$code .= $this->format_attribute( 'success_msg', 'success_msg', $attributes, false, '', true );
			
			$code .= $this->format_attribute( 'error_msg', 'error_msg', $attributes, false, '', true );
			
			$code .= $this->format_attribute( 'field_error_msg', 'field_error_msg', $attributes, false, '', true );
			
			$code .= $this->format_attribute( 'css_class', 'css_class', $attributes, false, '', true  );
			
			$code .= ']';
			
			$code .= '[/otw_shortcode_contact_form]';
		}
		
		return $code;

	}
	
	/**
	 * Display shortcode
	 */
	public function display_shortcode( $attributes, $content ){
		
		//default form element values
		$field_values = array();
		$field_values['contactName'] = '';
		$field_values['email'] = '';
		$field_values['subject'] = '';
		$field_values['comments'] = '';
		$field_values['sendCopy'] = false;
		
		//field errors
		$field_errors = array();
		$field_errors['contactName'] = '';
		$field_errors['email'] = '';
		$field_errors['subject'] = '';
		$field_errors['comments'] = '';
		$field_errors['sendCopy'] = '';
		$field_errors['recaptcha'] = '';
		
		if( $this->format_attribute( '', 'recaptcha', $attributes, false, '' ) != 'no' ){
			include_once( $this->component_path.'libs/recaptcha-php-1.11/recaptchalib.php' );
		}
		
		$is_valid = true;
		$mail_sent = false;
		
		if( isset( $_POST ) && isset( $_POST[ $this->form_name ] ) && otw_validator::is_unsigned( $_POST[ $this->form_name ] ) && !in_array( $_POST[ $this->form_name ], $this->sessions ) ){
			
			if( isset( $_POST['contactName'] ) ){
				$field_values['contactName'] = otw_stripslashes( $_POST['contactName'] );
			}
			if( isset( $_POST['email'] ) ){
				$field_values['email'] = $_POST['email'];
			}
			if( isset( $_POST['subject'] ) ){
				$field_values['subject'] = otw_stripslashes( $_POST['subject'] );
			}
			if( isset( $_POST['comments'] ) ){
				$field_values['comments'] = otw_stripslashes( $_POST['comments'] );
			}
			if( isset( $_POST['sendCopy'] ) ){
				$field_values['sendCopy'] = $_POST['sendCopy'];
			}
			if( $this->format_attribute( '', 'recaptcha', $attributes, false, '' ) != 'no' ){
				
				if( isset( $_POST["recaptcha_challenge_field"] ) ){
					
					$resp = recaptcha_check_answer( $this->format_attribute( '', 'recaptcha_private_key', $attributes, false, '' ), $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
					
					if( !$resp->is_valid ){
						$is_valid = false;
						$field_errors['recaptcha'] = $this->get_label( 'You entered an invalid captcha.' );
					}
				}
			}
			
			if( otw_validator::is_empty( $field_values['contactName'] ) ){
				$is_valid = false;
				$field_errors['contactName'] = $this->format_attribute( '', 'field_error_msg', $attributes, false, '' );
			}
			if( otw_validator::is_empty( $field_values['email'] ) ){
				$is_valid = false;
				$field_errors['email'] = $this->format_attribute( '', 'field_error_msg', $attributes, false, '' );
			}
			elseif( !otw_validator::is_email( $field_values['email'] ) ){
				$is_valid = false;
				$field_errors['email'] = $this->get_label( 'You entered an invalid email address.' );
			}
			if( otw_validator::is_empty( $field_values['comments'] ) ){
				$is_valid = false;
				$field_errors['comments'] = $this->format_attribute( '', 'field_error_msg', $attributes, false, '' );
			}
			
			if( $is_valid ){
				
				$emailTo = $this->format_attribute( '', 'sendfrom', $attributes, false, '' );
				if( !otw_validator::is_empty( $field_values['subject'] ) ){
					$subject = $field_values['subject'];
				}else{
					$subject = $this->get_label( 'Contact from' ).' '.get_bloginfo( 'title' );
				}
				$body = $this->get_label( 'Name:' ).' '.$field_values['contactName'];
				$body .= "\n\n".$this->get_label( 'Email:' ).' '.$field_values['email'];
				$body .= "\n\n".$this->get_label( 'Comments:' ).' '.$field_values['comments'];
				if( $fromtext = $this->format_attribute( '', 'fromtext', $attributes, false, '' ) ){
					$headers = 'From: '.$fromtext.' <'.$field_values['email'].'>';
				}else{
					$headers = 'From: '.get_bloginfo( 'title' ).' <'.$field_values['email'].'>';
				}
				
				wp_mail($emailTo, $subject, $body, $headers);
				
				$mail_sent = true;
				
				if( $field_values['sendCopy'] ){
				
					$subject = $this->get_label( 'You mailed: ').get_bloginfo('title');
					$headers = 'From: '.get_bloginfo( 'title' ).' <'.$emailTo.'>';
					
					wp_mail($emailTo, $subject, $body, $headers);
				}
				
				$this->sessions[] = $_POST[ $this->form_name ];
				
				update_option( $this->form_name.'_sessions', $this->sessions );
				
				$field_values['contactName'] = '';
				$field_values['email'] = '';
				$field_values['subject'] = '';
				$field_values['comments'] = '';
				$field_values['sendCopy'] = false;
			}
		}
		$html = '<div';
		
		/*class attributes*/
		$class = 'otw-sc-contact-form otw-row';
		
		$class .= $this->format_attribute( '', 'css_class', $attributes, false, $class );
		
		if( strlen( $class ) ){
			$html .= ' class="'.$class.'"';
		}
		/*end class attributes*/
		
		/*style attribute*/
		$style = '';
		
		if( strlen( $style ) ){
			$html .= ' style="'.$style.'"';
		}
		
		$html .= '>';
		$html .= '<a id="'.$this->form_anchor.'" id="'.$this->form_anchor.'"></a>';
		
		if( !$is_valid ){
			
			if( $error_msg = $this->format_attribute( '', 'error_msg', $attributes, false, '' ) ){
				
				$html .= otw_form::message( 'error', $this->get_label( 'Error' ), $error_msg );
			}
		}
		
		if( $mail_sent ){
			if( $success_msg = $this->format_attribute( '', 'success_msg', $attributes, false, '' ) ){
				
				$html .= otw_form::message( 'success', $this->get_label( 'Success' ), $success_msg );
			}
		}
		$html .= '<form action="#'.$this->form_anchor.'" method="post">';
		$html .= '<input type="hidden" name="'.$this->form_name.'" value="'.time().'"/>';
		$html .= '<div class="otw-eight otw-columns">';
			$html .= '<label for="contactName">Name<span class="additional required">*</span></label>';
			$html .= '<input type="text" name="contactName" id="contactName" value="'.otw_htmlentities( $field_values['contactName'] ).'" class="txt requiredField" />';
			if( $field_errors['contactName'] ){
				$html .= otw_form::message( 'red_text', $this->get_label( 'Error' ), $field_errors['contactName'] );
			}
			$html .= '<label for="email">Email<span class="additional required">*</span></label>';
			$html .= '<input type="text" name="email" id="email" value="'.otw_htmlentities($field_values['email'] ).'" class="txt requiredField email" .>';
			if( $field_errors['email'] ){
				$html .= otw_form::message( 'red_text', $this->get_label( 'Error' ), $field_errors['email'] );
			}
			$html .= '<label for="subject">Subject<span class="additional">('.$this->get_label('optional').')</span></label>';
			$html .= '<input type="text" name="subject" id="subject" value="'.otw_htmlentities($field_values['subject'] ).'" class="txt requiredField email" />';
			if( $field_errors['subject'] ){
				$html .= otw_form::message( 'red_text', $this->get_label( 'Error' ), $field_errors['subject'] );
			}
		$html .= '</div>';
		
		$html .= '<div class="otw-sixteen otw-columns">';
			$html .= '<label for="commentsText">Message<span class="additional required">*</span></label>';
			$html .= '<textarea name="comments" id="commentsText" rows="8" cols="30" class="requiredField">'.$field_values['comments'].'</textarea>';
			if( $field_errors['comments'] ){
				$html .= otw_form::message( 'red_text', $this->get_label( 'Error' ), $field_errors['comments'] );
			}
			if( $this->format_attribute( '', 'recaptcha', $attributes, false, '' ) != 'no' ){
				$html .= '<div class="otw_recaptcha_conteniner">';
					$html .= recaptcha_get_html( $this->format_attribute( '', 'recaptcha_public_key', $attributes, false, '' ) );
				if( $field_errors['recaptcha'] ){
					$html .= otw_form::message( 'red_text', $this->get_label( 'Error' ), $field_errors['recaptcha'] );
				}
				$html .= '</div>';
			}
			$html .= '<div class="right">';
				$html .= '<span class="additional required">* '.$this->get_label('this field is mandatory').'</span>';
				
				if( $this->format_attribute( '', 'sendcopy', $attributes, false, '' ) != 'no' ){
					$html .= '<input type="checkbox" class="checkbox" name="sendCopy" '.( $field_values['sendCopy']?' checked="checked"':'' ).' id="sendCopy" value="true"><label class="inline" for="sendCopy">'.$this->get_label('Send a copy of this email to yourself').'</label>';
				}
				
				$html .= '<button class="radius button" type="submit">'.$this->get_label('Submit').'</button>';
				
			$html .= '</div>';
			
		$html .= '</div>';
		
		
		
		$html .= '</form>';
		
		$html .= '</div>';
		
		return $this->format_shortcode_output( $html );
	}
}