<?php
/**
 * Metabox Add Action
 *
 * @since 1.0.0
 * @todo Replace only if your creating your own Plugin
 * @todo dst - Find all and replace text
 * @todo DST - Find all and replace text
 * @todo dealer - Find all and replace text
 */

// Exit if accessed directly
if( !defined( 'ABSPATH' ) ) exit;

/**
 * Register Two (2) Meta Boxes.
 * @link Add Meta Box https://developer.wordpress.org/reference/functions/add_meta_box/
 * @link Save Post https://codex.wordpress.org/Plugin_API/Action_Reference/save_post
 */
function dst_register_meta_boxes() {
		$post_type = 'dealer';
		/** Search Posts Metabox **/
		add_meta_box( 
			'dst_normal_high', __( 'Dealer Info and Store Location', 'dst-txt' ),  
			'dst_display_normal_high_metabox', // Callback function
			$post_type, 
			'normal', 
			'high' 
		);
}
add_action( 'add_meta_boxes', 'dst_register_meta_boxes' );

/**
 * Upload Function for Metabox
 *
 * @since 1.0.0
 * @return void
 */
function dst_load_wp_media_files() {
    wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'dst_load_wp_media_files' );

/**
 * Metabox for post IDs dropdown
 *
 * @since 1.0.0
 * @param array $post Current post data
 * @return void
 */

function dst_display_normal_high_metabox($post) {
	$options = "";
	$post_id = $post->ID; // Post ID of a curret Post Type `dealer`

	// Add some test data here - a custom field, that is
	$meta_key='dst_postmeta_input_key';
	$get_meta = get_post_meta($post_id, $meta_key);
	$map_key = DST()->db->get_option('','dst_options', 0);
	$map_key_str = '';
    
    // May Key Check
    if(!empty($map_key)){
        $map_key_str = '&key='.$map_key;
    }
?>
	<p class="form-field form-field-wide">
		<h3><label for="about"><?php _e('About the dealer ', 'dst-txt') ?></label></h3>
		<label for="label-"><?php _e('Description', 'dst-txt') ?></label>
		<textarea class="large-text" rows="2" name="dst_postmeta_input_key[]"><?php echo isset($get_meta[0])?$get_meta[0]:'' ?></textarea>

	<p>
		<label for="label-upload"><?php _e('Upload Company Logo', 'dst-txt') ?></label>
		<input id="dst-image_url" class="dst_postmeta_input_key[]" name="dst_postmeta_input_key[]" type="text" value="<?php echo isset($get_meta[1])?$get_meta[1]:'' ?>">
		<button type="button" id="insert-logo-dst" class="button insert-logo add_media"><span class="dashicons dashicons-format-image" style="vertical-align: text-top;"></span> Upload Logo</button>
	</p>
<script type="text/javascript">
jQuery(document).ready(function($){
    $('#insert-logo-dst').click(function(e) {
        e.preventDefault();
        var image = wp.media({ 
            title: 'Upload Logo',
            // mutiple: true if you want to upload multiple files at once
            multiple: false
        }).open()
        .on('select', function(e){
            // This will return the selected image from the Media Uploader, the result is an object
            var uploaded_image = image.state().get('selection').first();
            // We convert uploaded_image to a JSON object to make accessing it easier
            // Output to the console uploaded_image
            // console.log(uploaded_image);
            var image_url = uploaded_image.toJSON().url;
            // Let's assign the url value to the input field
            $('#dst-image_url').val(image_url);
        });
    });
});
</script>
	</p>

	<p class="form-field form-field-wide">
		<h3><label for="about"><?php _e('Store Location ', 'dst-txt') ?></label></h3>
	</p>
	<p class="form-field form-field-wide">
		<label for="label-"><?php _e('Street Address', 'dst-txt') ?></label>
		<input class="regular-text" type="text" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[2])?$get_meta[2]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<label for="label-"><?php _e('City', 'dst-txt') ?></label>
		<input class="regular-text" type="text" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[3])?$get_meta[3]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<label for="label-"><?php _e('Postcode', 'dst-txt') ?></label>
		<input class="regular-text" type="number" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[4])?$get_meta[4]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<label for="label-"><?php _e('State/County', 'dst-txt') ?></label>
		<input class="regular-text" type="text" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[5])?$get_meta[5]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<label for="label-"><?php _e('Country', 'dst-txt') ?></label>
		<input class="regular-text" type="text" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[6])?$get_meta[6]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<label for="label-"><?php _e('Email', 'dst-txt') ?></label>
		<input class="regular-text" type="email" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[7])?$get_meta[7]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<label for="label-"><?php _e('Phone', 'dst-txt') ?></label>
		<input class="regular-text" type="text" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[8])?$get_meta[8]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<h3><label for="google-map"><?php _e('Google Map (Auto Generated or Manually Refresh)', 'dst-txt') ?><a href="#"><span id="gst-map-refresh" class="dashicons dashicons-image-rotate"></span></a></label></h3>
	</p>
	<p class="form-field form-field-wide">
		<label for="label-latitude"><?php _e('Latitude', 'dst-txt') ?></label>
		<input id="dst-latitude" class="regular-text" type="text" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[9])?$get_meta[9]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<label for="label-longitude"><?php _e('Longitude', 'dst-txt') ?></label>
		<input id="dst-longitude" class="regular-text" type="text" name="dst_postmeta_input_key[]" value="<?php echo isset($get_meta[10])?$get_meta[10]:'' ?>">
	</p>
	<p class="form-field form-field-wide">
		<span><label for="google-map-note"><?php _e('You can manually get Latitude and Longitude values by inputting the address <a href="http://www.latlong.net/" target="_blank">here</a>', 'dst-txt') ?></label></span>
	</p>
	<script src="https://maps.google.com/maps/api/js?sensor=false<?php echo $map_key_str; ?>"></script>
	<script type="text/javascript">
		jQuery(document).ready(function($){
			'use strict'
			var inputName = 'input[name="dst_postmeta_input_key[]"]',
				getArray = [], address;

			function dstGeoMap(address){
					var geocoder = new google.maps.Geocoder();
					if (geocoder) {
						geocoder.geocode({ 'address': address }, function (results, status) {
							if (status == google.maps.GeocoderStatus.OK) {
								$("#dst-latitude").val(results[0].geometry.location.lat());
								$("#dst-longitude").val(results[0].geometry.location.lng());
							} else {
								$("#dst-latitude").val('Latitude Geocoding Failed');
								$("#dst-longitude").val('Longitude Geocoding Failed');
								console.log("Geocoding failed: " + status);
							}
						          
						});
					} 
			}
			function dstGetInputs(){
				// Just reset array
		    	getArray = [];
				$(inputName).each(function( index ) {
		  			// console.log( index + ": " + $( this ).val() );
		  			if(index==1 || index==2 || index==3 || index==4 || index==5){
		  				// check if not empty
		  				if($( this ).val()){
		  					getArray.push($( this ).val());
		  					address = getArray.toString();

		  					// Google Maps Geocoder
		  					dstGeoMap(address);
		  				}	
		  			}
				});
				console.log(address);
			}

		    $(inputName).change(function() {
		    	dstGetInputs();	
		    });

		    // Manual Refresh
			$("#gst-map-refresh").click(function(e) {
				e.preventDefault();
				dstGetInputs();	  				
		    });		

		  
		});
</script>
<?php
}

/**
 * Save Post for Metabox Best Practices
 *  
 * @since 1.0.0
 * @return void
 */

function dst_save_meta_box($post_id){

	// If post is an autosave, avoid it!
	if ( wp_is_post_autosave( $post_id || defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE) ) {
		return;
 	}

	// If this isn't a 'dealer' post type, don't update it.
	if ( get_post_type( $post_id ) != 'dealer' ) 
		return;
	
	$meta_key='dst_postmeta_input_key'; 

	// If the custom field is found, update the postmeta record
		// Also, filter the HTML just to be safe
	if ( isset( $_POST[$meta_key]  ) ) {
		update_post_meta( $post_id, $meta_key,  esc_html( $_POST[$meta_key] ) );
	}
	
	$old_postmeta = get_post_meta($post_id, $meta_key);
	$new_postmeta = isset ( $_POST[$meta_key] )  ? $_POST[$meta_key] : array();
	
	// If there's no values, delete post meta;
	if ( empty ($new_postmeta) ) {
	   // completely delete all meta values for the post
	   delete_post_meta($post_id, $meta_key);
	} else {
	  $already = array();
	  if ( ! empty($old_postmeta) ) {
	    foreach ($old_postmeta as $value) {
	      if ( ! in_array($value, $new_postmeta) ) {
	        // this value was selected, but now it isn't so delete it
	        delete_post_meta($post_id, $meta_key, $value);
	      } else {
	        // this value already saved, we can skip it from saving
	        $already[] = $value;
	      }
	    }
	  }
	  // we only need to save new values 
	  $to_save = array_diff($new_postmeta, $already);
	  if ( ! empty($to_save) ) {
	    foreach ( $to_save as $save_value ) {
	    		add_post_meta( $post_id, $meta_key, $save_value);
	    }
	  }
	}
}
add_action( 'save_post', 'dst_save_meta_box' );


