<?php
/*
....
*/
require_once dirname( __FILE__ ).'/base.addon.php';

if( !class_exists( 'cpabc_Signature' ) )
{
    class cpabc_Signature extends CPABC_BaseAddon
    {
        /************* ADDON SYSTEM - ATTRIBUTES AND METHODS *************/
		protected $addonID = "addon-signature-20171025";
		protected $name = "Signature Fields";
		protected $description;

		public function get_addon_form_settings( $form_id )
		{
			global $wpdb;

			// Insertion in database
			if( !empty( $_REQUEST[ 'cpabc_signature_addon' ] ) )
			{

				// Fields
				$fields = array();
				if(
					isset( $_REQUEST[ 'cpabc_signature_field' ] ) &&
					is_array( $_REQUEST[ 'cpabc_signature_field' ] )
				)
				{
					foreach( $_REQUEST[ 'cpabc_signature_field' ] as $field )
					{
						$field = trim( $field );
						if( !empty( $field ) ) $fields[] = $field;
					}
				}

				// Settings
				$settings = array_merge( array(), $this->default_settings );

				if(
					isset($_REQUEST[ 'cpabc_signature_color' ]) &&
					( $cpabc_signature_color = trim($_REQUEST[ 'cpabc_signature_color' ]) ) != ''
				) $settings[ 'color' ] = $cpabc_signature_color;

				if(
					isset($_REQUEST[ 'cpabc_signature_line_thickness' ]) &&
					( $cpabc_signature_line_thickness = trim($_REQUEST[ 'cpabc_signature_line_thickness' ]) ) != ''
				) $settings[ 'thickness' ] = $cpabc_signature_line_thickness;

				$settings[ 'guideline' ] = ( isset($_REQUEST[ 'cpabc_signature_guideline' ]) ) ? 1 : 0;

				if(
					isset($_REQUEST[ 'cpabc_signature_guideline_color' ]) &&
					( $cpabc_signature_guideline_color = trim($_REQUEST[ 'cpabc_signature_guideline_color' ]) ) != ''
				) $settings[ 'guidelineColor' ] = $cpabc_signature_guideline_color;

				// Refresh database
				$wpdb->delete( $wpdb->prefix.$this->form_signature_table, array( 'formid' => $form_id ), array( '%d' ) );
				$wpdb->insert( 	$wpdb->prefix.$this->form_signature_table,
								array(
									'formid' 	=> $form_id,
									'fields'	=> serialize( $fields ),
									'settings'	=> serialize( $settings )
								),
								array( '%d', '%s', '%s' )
							);
			}

			// Read from database and display the fields.
			$c = 0;
			$row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_signature_table." WHERE formid=%d", $form_id ) );

			$fields = array();
			$settings = array_merge( array(), $this->default_settings );

			if( !empty($row) )
			{
				if( ( $tmp_fields = @unserialize( $row->fields ) ) != false && is_array( $tmp_fields ) ) $fields = $tmp_fields;
				if( ( $tmp_settings = @unserialize( $row->settings ) ) != false && is_array( $tmp_settings ) ) $settings = array_merge( $settings, $tmp_settings );
			}

			?>
			<input type="hidden" name="cpabc_signature_addon" value="1" />
			<div id="metabox_basic_settings" class="postbox" >
				<style>
					.cpabc-signature-field-container{width:100%;}
					.cpabc-signature-attribute-container{ clear:both; padding:10px 0;}
				</style>
				<h3 class='hndle' style="padding:5px;"><span><?php print $this->name; ?></span></h3>
				<div class="inside">
					<div class="cpabc-signature-field-container">
					<?php
					foreach( $fields as $field )
					{
						$field = trim( $field );
						if( !empty( $field ) )
						{
							$this->_addField( $c, $field );
							$c++;
						}
					}

					$this->_addField( $c );
					$c++;
					?>
					</div>
					<input type="button" value="<?php esc_attr_e('Add field', 'cpabc');?>" onclick="cpabc_signature_addField( this );" />
					<h3><?php _e( 'Signature Settings', 'cpabc' ); ?></h3>
					<table class="form-table">
						<tr valign="top">
							<th scope="row"><?php _e( 'Color', 'cpabc' );?></th>
							<td><input type="text" name="cpabc_signature_color" value="<?php echo esc_attr( $settings[ 'color' ] ); ?>" /></td>
						</tr>
						<tr valign="top">
							<th scope="row"><?php _e( 'Line thickness', 'cpabc' );?></th>
							<td><input type="text" name="cpabc_signature_line_thickness" value="<?php echo esc_attr( $settings[ 'thickness' ] ); ?>" /></td>
						</tr>
						<tr valign="top">
							<th scope="row"><?php _e( 'Show guideline', 'cpabc' );?></th>
							<td><input type="checkbox" name="cpabc_signature_guideline" <?php if( $settings['guideline'] ) echo 'CHECKED'; ?> /></td>
						</tr>
						<tr valign="top">
							<th scope="row"><?php _e( 'Guideline color', 'cpabc' );?></th>
							<td><input type="text" name="cpabc_signature_guideline_color" value="<?php echo esc_attr( $settings[ 'guidelineColor' ] ); ?>" /></td>
						</tr>
					</table>
				</div>
				<script>
					var cpabc_signature_fields_counter = <?php print $c; ?>;
					function cpabc_signature_deleteField( e )
					{
						try{
							jQuery( e ).closest( '.cpabc-signature-attribute-container' ).remove();
						}catch(err ){}
					}

					function cpabc_signature_addField( e )
					{
						try
						{
							var $   = jQuery,
								str = $( '<div class="cpabc-signature-attribute-container"><b><?php _e( 'Field name', 'cpabc'); ?>:</b>&nbsp;<input type="text" name="cpabc_signature_field['+cpabc_signature_fields_counter+']" placeholder="fieldname#" /><input type="button" value="<?php esc_attr_e('Delete field', 'cpabc');?>" onclick="cpabc_signature_deleteField( this );" /><div style="clear:both;"></div><div><em><?php _e( 'Enter the field name to be reaplaced by the signature', 'cpabc'); ?></em></div></div>' );

							$( e ).before( str );
							cpabc_signature_fields_counter++;
						}
						catch( err ){}
					}
				</script>
			</div>
			<?php
		}

		/************************ ADDON CODE *****************************/
        /************************ ATTRIBUTES *****************************/

		private $form_signature_table = 'cpabc_signature';
		private $javascript_code = '';
		private $signature_images = array();
		private $default_settings = array(
			'color' => '#000000',
			'background' => '#FFFFFF',
			'thickness' => 2,
			'guideline'	=> 0,
			'guidelineColor' => '#000000'
		);

        /************************ CONSTRUCT *****************************/

        function __construct()
        {
			$this->description = __("The add-on allows to replace form fields with \"Signature\" fields", 'cpabc');

            // Check if the plugin is active
			if( !$this->addon_is_active() ) return;

			// Checks the form's settings and generate the javascript code
			add_filter( 'cpabc_pre_form', array( &$this, 'generate_javascript' ) );

			// Inserts the javascript code in the page's footer
			add_action( 'wp_footer', array( &$this, 'insert_javascript' ), 99 );

			add_filter( 'wp_mail', array(&$this, 'wp_mail') );

			add_action( 'phpmailer_init', array(&$this, 'phpmailer_init') );

			if( is_admin() )
			{
				add_action( 'cpabc_messages_filters', array( &$this, 'messages_list'), 99 );
			}

            $this->update_database();
            
		} // End __construct

        /************************ PROTECTED METHODS *****************************/

		/**
         * Create the database tables
         */
        protected function update_database()
		{
			global $wpdb;
			$charset_collate = $wpdb->get_charset_collate();
			$sql = "CREATE TABLE IF NOT EXISTS ".$wpdb->prefix.$this->form_signature_table." (
					formid INT NOT NULL,
					fields text,
					settings text,
					PRIMARY KEY (formid)
				) $charset_collate;";

			$wpdb->query($sql);
		} // End update_database

        /************************ PRIVATE METHODS *****************************/

		private function _addField( $index, $field = '' )
		{
		?>
			<div class="cpabc-signature-attribute-container">
				<b><?php _e( 'Field name', 'cpabc'); ?>:</b>&nbsp;
				<input type="text" name="cpabc_signature_field[<?php print $index; ?>]" value="<?php print trim( $field ); ?>" placeholder="fieldname#" />
				<input type="button" value="<?php esc_attr_e('Delete field', 'cpabc');?>" onclick="cpabc_signature_deleteField( this );" />
				<div style="clear:both;"></div>
				<div><em><?php _e( 'Enter the field name to be reaplaced by the signature', 'cpabc'); ?></em></div>
			</div>
		<?php
		} // End _addField

		/************************ PUBLIC METHODS  *****************************/

		public function wp_mail($atts)
		{
			$this->signature_images = array();
			$reg_exp= '/"data\:image\/svg\+xml\;base64\,([^"]+)"/';
			if(preg_match_all($reg_exp, $atts[ 'message' ], $_match_all))
			{
				$this->signature_images = $_match_all;
				foreach($this->signature_images[0] as $counter => $signature_image)
				{
					$atts[ 'message' ] = str_replace($signature_image, '"cid:'.$counter.'-signature-uid"' ,$atts[ 'message' ]);
				}
			}
			return $atts;
		} // End wp_mail

		public function phpmailer_init(&$phpmailer)
		{
			foreach($this->signature_images[1] as $counter => $signature_image)
			{
				$uid = $counter.'-signature-uid';
				$file_code = $signature_image;
				$file_code = base64_decode($file_code);
				$name = "signature$counter.svg";
				$phpmailer->addStringEmbeddedImage($file_code, $uid, $name);
			}
		} // End phpmailer_init

		/**
		 * Checks the form's settings and generates the javascript code
		 */
		public function generate_javascript( $atts )
		{
			if(
				!empty( $atts ) &&
				is_array( $atts ) &&
				!empty( $atts[ 'id' ] )
			)
			{              
				global $wpdb;
   
                wp_enqueue_script( "jquery-ui-button" );
                wp_enqueue_script( "jquery-ui-slider" );
                wp_enqueue_script( "jquery-ui-mouse" );  
                 
				$instance = "";

				$row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM ".$wpdb->prefix.$this->form_signature_table." WHERE formid=%d", $atts[ 'id' ] ) );
				if(
					!empty( $row ) &&
					!empty( $row->fields ) &&
					( $fields = @unserialize( $row->fields ) ) !== false &&
					is_array( $fields )
				)
				{                           
					// Fields
					foreach( $fields as $field )
					{
						$this->javascript_code .= 'fields.push( "'.esc_js($field.$instance).'" );';
					}

					//Settings
					$settings = array_merge( array(), $this->default_settings );
					if(
						!empty( $row->settings ) &&
						( $tmp_settings = @unserialize( $row->settings ) ) !== false &&
						is_array( $tmp_settings )
					)
					{
						$settings = array_merge( $settings, $tmp_settings );
					}

					$this->javascript_code .= 'settings["'.esc_js($field).'"]={};';
					foreach( $settings as $setting_name => $setting_value )
					{
						$this->javascript_code .= 'settings["'.esc_js($field).'"]["'.esc_js($setting_name).'"]="'.esc_js($setting_value).'";';
					}
				}
			}

			return $atts;
		} // End generate_javascript

		/**
		 * Inserts the javascript code in the footer section of page
		 */
		public function insert_javascript()
		{
			if( !empty( $this->javascript_code ) )
			{           
			?>
				<script>if(typeof jQuery == 'undefined' && typeof fbuilderjQuery != 'undefined' ) jQuery = fbuilderjQuery;</script>
			<?php
				// Load required scripts
				echo '<link href="'.plugins_url('/signature.addon/jquery.signature.css', __FILE__ ).'"  rel="stylesheet" type="text/css" />';
				echo '<!--[if IE]><script src="'.plugins_url('/signature.addon/excanvas.js', __FILE__ ).'"></script><![endif]-->';
				echo '<script src="'.plugins_url('/signature.addon/jquery.signature.min.js', __FILE__ ).'"></script>';
				echo '<script src="'.plugins_url('/signature.addon/jquery.ui.touch-punch.min.js', __FILE__ ).'"></script>';
				echo '<script src="'.plugins_url('/signature.addon/jquery.base64.js', __FILE__ ).'"></script>';

			?>
			<script>
				jQuery(window).on(
					'load',
					function()
					{
						var $ = jQuery,
							cpabc_signature = {},
							fields = [],
							settings = {},
							field, form, size, default_val;

						window[ 'resize_signature_field' ] = function(){
								$('[id$="_signature"]').each(function(){
									var e = $(this), c = e.find('canvas');
									if(c.length)
									{
										var c = c[0],
											tmpCanvas = document.createElement( 'canvas' ),
											tmpCtx = tmpCanvas.getContext('2d'),
											ctx;

										tmpCanvas.width = c.width;
										tmpCanvas.height = c.height;

										tmpCtx.drawImage(c, 0, 0);
										c.width = e.width();
										c.height = e.height();
										ctx = c.getContext('2d');
										ctx.drawImage(tmpCanvas, 0, 0, tmpCanvas.width, tmpCanvas.height, 0, 0, c.width, c.height);

										var parts = /(_\d+)_signature/.exec(e.attr('id'));
										if(parts != null )
										{
											var f = parts[1];
											ctx.strokeStyle = settings[f].color;
											ctx.lineWidth = settings[f].thickness;
											ctx.lineCap = 'round';
											ctx.lineJoin = 'round';
										}
									}
								});
							};
						<?php
						print $this->javascript_code;
						?>
						for( var i in fields )
						{
							form = fields[i]; // /_\d+$/.exec(fields[i]);                         
							field = $( '#'+fields[i] );

							if(
								form == null ||
								field.length == 0 ||
								typeof settings[ form ] == 'undefined'
							) continue;

							//form = form[0];
							size = ( field.hasClass( 'large' ) ) ? 'large' : ( ( field.hasClass( 'medium' ) ) ? 'medium' : 'small' );
							field.hide()
								.before( '<div id="'+fields[i]+'_signature" class="'+size+'" style="height:200px;"></div>' )
								.after( '<div id="'+fields[i]+'_signature_clear" style="position:absolute;z-index:999;padding:5px;border: 1px solid '+settings[form]['color']+'; color:'+settings[form]['color']+';margin:5px;top:0;font-family:Helvetica, Arial, Sans-Serif;cursor:pointer;">X</div>');
							settings[ form ][ 'guideline' ] *= 1;
							settings[ form ][ 'change' ] = function(event, ui) {
								var s 	 = $(this),
									svg  = s.signature( 'toSVG' ),
									rect = $( svg ).find( 'rect' );

								svg = svg.replace( /width="[^"]*"/i, 'width="'+rect.attr('width')+'"')
										.replace( /height="[^"]*"/i, 'height="'+rect.attr('height')+'"');

								var	svg64 = $.base64('encode', svg),
									img = '<img src="data:image/svg+xml;base64,'+svg64+'" class="cpabc-signature" />';

								$('#'+s.attr('id').replace('_signature', '')).val(img).change();
							};

							$('[id="'+fields[i]+'_signature"]').signature( settings[ form ] );
						}

						$(document).on(
							'mouseup',
							'.pbNext',
							function()
							{
								setTimeout(resize_signature_field, 200);
							}
						);

						$( document ).on(
							'click',
							'[id$="_signature_clear"]',
							function()
							{
								var signature = $(this).attr('id').replace(/_clear$/, '' );
								$( '#'+signature ).signature( 'clear' );
							}
						);

						$(window).resize( function(){
							setTimeout( resize_signature_field,500);
						});
					}
				);
			</script>
			<?php
			}
		} // End insert_javascript

		public function messages_list()
		{
			print '<style>.cpabc-signature{max-width: 100%;}</style>';
		} // End messages_list


	} // End Class

    // Main add-on code
    $cpabc_signature_obj = new cpabc_Signature();

	// Add addon object to the objects list
	$cpabc_addons_objs_list[ $cpabc_signature_obj->get_addon_id() ] = $cpabc_signature_obj;
}
?>