<?php

/**
 * Ajax Post Search in the Metabox
 *
 * @see Ajax using jQuery (http://api.jquery.com/jquery.ajax)
 * @see AJAX in Plugins (https://codex.wordpress.org/AJAX_in_Plugins)
 * @since 1.0.0
 * @return void
 * 
 */

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

/*
 * The JavaScript for our AJAX call
 */
function dst_footer_ajax_script() {
  wp_nonce_field('dst_ajax_action', 'dst-ajax-nonce'); // is a good practice to add nonces for HTTP Requests
?>
  <script type="text/javascript">
  
    jQuery(document).ready(function($) {
      $( '#dst_go' ).click( function(){

        // This only run the Ajax Query Once, afer removing ajaxable class
       // if($( '#post-selects.ajaxable' ).length < 1){
//          return;
//        }

        // To get the value of an input field
        var postCode = $( '#dst-postcode' ).val();
        var getNonce = $('input[name="dst-ajax-nonce"]').val(); 
        
        // Must have value
        if(!postCode || !getNonce){
          return;
        }

        $.ajax({
          method: "POST",
          url: "<?php echo  esc_url(admin_url( 'admin-ajax.php' )); ?>",
          data: { 
                'action': 'dst_action', // Related to wp_ajax_{dst_action}
                'dst-post-code': postCode, // hidden field for post ID
                'dst-ajax-nonce': getNonce // hidden nonce field
          }
        })
        .done(function(res) { 

        // Remove class `ajaxable` and only run the ajax once
        //  $('#post-selects').removeClass('ajaxable'); 
        
        // Removing the current option lists and replacing it with new values    
        $("#dst-ajax-results section").remove(); 

          var data = JSON.parse(res); // Takes a well-formed JSON string
           
          // Ajax success request but no data
          if(data.status=='no_results'){
            $( '#dst-ajax-results' ).append('<section class="col-xs-12 col-sm-6 col-md-12"><span>No related results</span></section>');
            console.log(res);
            return;
          }
           console.log(res);

          // Handling data array
          for(var i=0; i<data.length; i++){
            // var selected = data[i]['selected'] ? 'selected="selected"' : '';
            $( '#dst-ajax-results' ).append('<section class="col-xs-12 col-sm-6 col-md-12">'
  + '<article class="search-result row">'
  +  '<div class="col-xs-12 col-sm-12 col-md-3">'
  +    '<a href="'+data[i]['post_uri']+'" class="thumbnail"><img src="'+data[i]['post_meta'][1]+'"></a>'
  +  '</div>'
  +  '<div class="col-xs-12 col-sm-12 col-md-9">'
  +   '<h4><a href="'+data[i]['post_uri']+'" title="">'+data[i]['post_title']+'</a></h4>'
  +   '<p>'+data[i]['post_meta'][0]
  +   '<br><span="dst-address">Address: '+data[i]['post_meta'][2]+', '+data[i]['post_meta'][3]+', '+data[i]['post_meta'][4]+', '+data[i]['post_meta'][5]+', '+data[i]['post_meta'][6]+'</small></span>'
  +   '</p>'     
  +  '</div>'
  +  '<span class="clearfix"></span>'
  + '</article>'
+ '</section>');
          }

          // $("").prependTo("#dst-ajax-results");

          // Handling data array
          // for(var i=0; i<data.length; i++){
//             var selected = data[i]['selected'] ? 'selected="selected"' : '';
//             $( '#post-selects' ).append('<option '+ selected +' value="' + data[i]['ID'] + '">' + data[i]['post_title'] + '</option>');
//           }
          // $("#post-selects").trigger("chosen:updated"); // Chosen JS Plugin (reconstructed)
            
        })
        .fail(function( jqXHR, textStatus, errorThrown ) {
          // Error handler
          console.log( 'AJAX Fail! Status Code: ' +jqXHR.status+ '; Error Thrown:' +errorThrown );
        });
      }); 
    });
  </script>

<?php
}
add_action( 'wp_footer', 'dst_footer_ajax_script' );

/**
 * The AJAX handler function
 * @see AJAX in Plugins (https://codex.wordpress.org/AJAX_in_Plugins)
 */
function dst_ajax_handler() {
  $post_code = isset($_POST['dst-post-code']) ? $_POST['dst-post-code'] : ''; // To get the value from input hidden field.
  $nonce = isset($_POST['dst-ajax-nonce']) ? $_POST['dst-ajax-nonce'] : '';

  // return if there's no value or nonce fail
  if(!$post_code || !$nonce || ! wp_verify_nonce($nonce, 'dst_ajax_action')){
    wp_die(); // execute die() if doesn't meet the security
  }
  $get_postmeta = DST()->db->related_postmeta($post_code);
  
  // No data fallback, just echo and die
  if(empty($get_postmeta)){
    echo json_encode(array("status"=>"no_results"));
     wp_die(); // just to be safe
  }
  // DST()->db->related_postmeta(33607);
  echo json_encode($get_postmeta);

  // echo json_encode($post_code);
  wp_die(); // just to be safe
}
add_action( 'wp_ajax_dst_action', 'dst_ajax_handler' );
add_action( 'wp_ajax_nopriv_dst_action', 'dst_ajax_handler' );


