<?xml version="1.0" encoding="utf-8"?>
<modification>
  <name>Store Locator</name>
  <code>store_locator</code>
  <version>1.3</version>
  <author>GravityIncPK</author>
  <link>http://gravityincpk.com</link>
  <file path="admin/view/template/catalog/product_form.tpl">
    <operation>
      <search>
	    <![CDATA[<li><a href="#tab-design" data-toggle="tab"><?php echo $tab_design; ?></a></li>]]>
      </search>
      <add position="after">
        <![CDATA[<li><a href="#tab-locator" data-toggle="tab">Store Locator</a></li>]]>
      </add>
    </operation>
	
	<operation>
      <search index="0">
	    <![CDATA[<div class="tab-content">]]>
      </search>
      <add position="after">
        <![CDATA[<div class="tab-pane" id="tab-locator">
          
			<div class="form-group">
			<!--- modal  -->
			<div id="locatorModal" class="modal fade" role="dialog">
			  <div class="modal-dialog">
				<!-- Modal content-->
				<div class="modal-content">
				  <div class="modal-header">   
					  Store
				  </div>
				  <div class="modal-body">
				  <iframe src="storelocator.php" height="360" id="iframsrc" width="550"></iframe>
				  </div>
				  <div class="modal-footer">
				  <button type="button" id="addtomap" data-mapadd="" class="btn btn-success" onclick="addmapnow(this);" >Add</button>
					<button type="button" class="btn btn-default" id="closemodal" data-dismiss="modal">Close</button>
				  </div>
				</div>
			
			  </div>
			</div>
           <?php $loc_row=0; ?>
            <?php foreach($locations as $key=>$location){
               
           echo '<div style="border-bottom: 1px solid#CCC;" id="loc-row'.$key.'">
           <div class="form-group">
           <div style="padding: 15px;" class="col-sm-10 col-md-offset-2">
           <a onclick="openmap(this);" class="btn btn-info btn-lg" id="button'.$key.'" data-btn="'.$key.'" data-backdrop="static" data-toggle="modal" data-target="#locatorModal">Add Location</a>
           </div>
           
           <label class="control-label col-sm-2">Location Address</label>
           <div class="col-sm-6"><input type="text" class="form-control" name="locations['.$key.'][name]" value="'.$location['address'].'" id="location'.$key.'" >
           <input type="hidden" class="form-control" name="locations['.$key.'][lat]" value="'.$location['latitude'].'" id="lat'.$key.'" >
           <input type="hidden" class="form-control" name="locations['.$key.'][lng]" value="'.$location['longitude'].'" id="lng'.$key.'" >
           </div>';
           echo '<div class="col-sm-2">
           <button type="button" onclick="$(\'#loc-row'.$key.'\').remove();" data-toggle="tooltip" title="Remove Row '.$key.'" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button>
           </div>
           </div>
           </div>';
           $loc_row++;
            } ?>
            <div id="locatemap"></div>
               <div class="form-group">
               <label class="control-label col-sm-2">Add Location</label>
               <div class="col-sm-2 ">
            <button type="button" id="getlocation" onclick="addlocation();" data-location="<?php echo $loc_row; ?>" data-toggle="tooltip" title="Add Location" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button>
            </div>
            </div>
          </div>
     
            </div>
            <script>
           
            
           function addmapnow(vals){
           
         var idno=  $(vals).attr("data-mapadd");
           $("#location"+idno).val($('iframe').contents().find('#pac-input').val());
           $("#lat"+idno).val($('iframe').contents().find('#cityLat').val());
           $("#lng"+idno).val($('iframe').contents().find('#cityLng').val());
           $('iframe').contents().find('#pac-input').val("");
           $('iframe').contents().find('#cityLat').val("");
           $('iframe').contents().find('#cityLng').val("");
           $("#closemodal").click();
          
           }
            function addlocation(){
           var loc= $("#getlocation").attr('data-location');
           html="";
           html += '<div id="loc-row'+loc+'" style="border-bottom: 1px solid#CCC;"><div class="form-group"><div style="padding: 15px;" class="col-sm-10 col-md-offset-2"><a onclick="openmap(this);" class="btn btn-info btn-lg" id="button'+loc+'" data-btn="'+loc+'" data-backdrop="static" data-toggle="modal" data-target="#locatorModal">Add Location</a></div><label class="control-label col-sm-2">Location Address</label><div class="col-sm-6"><input type="text" class="form-control" name="locations['+loc+'][name]" id="location'+loc+'" ><input type="hidden" class="form-control" name="locations['+loc+'][lat]" id="lat'+loc+'" ><input type="hidden" class="form-control" name="locations['+loc+'][lng]" id="lng'+loc+'" ></div>';
           html +='<div class="col-sm-2"><button type="button" onclick="$(\'#loc-row' + loc + '\').remove();" data-toggle="tooltip" title="Remove Row '+loc+'" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></div></div></div>';
           $("#locatemap").append(html);
           //$("#addtomap").attr("data-btn",loc);
           loc++;
           $("#getlocation").attr('data-location',loc);
            }
            function openmap(ids){
           var addloc= $(ids).attr('data-btn');
           $("#addtomap").attr("data-mapadd",addloc);
           var lat= $("#lat"+addloc).val();
           var lng= $("#lng"+addloc).val();
         
         //this.iframeSrc="storelocator.php?lat="+lat+"&lng="+lng;
         //$("#iframesrc").attr("src","storelocator.php?lat="+lat+"&lng="+lng);
         if(lat!=""&&lng!=""){
           $("#locatorModal").find("iframe").attr("src","storelocator.php?lat="+lat+"&lng="+lng);
           }
            }
            </script>
            <style>
              #pac-input{
                    margin-left: 20% !important;
                    width: 70% !important;
              }
            </style>]]>
      </add>
    </operation>
    
  </file>
   <file path="admin/controller/catalog/product.php">
    <operation>
      <search>
	    <![CDATA[if (isset($this->request->post['upc'])) {]]>
      </search>
      <add position="before">
        <![CDATA[$data['locations'] = array();
		if (isset($this->request->post['locations'])) {
			$data['locations'] = $this->request->post['locations'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['locations'] = $this->model_catalog_product->getLocations($this->request->get['product_id']);
			
		} else {
			$data['locations'] = array();
		}]]>
      </add>
    </operation>
  </file>

     <file path="admin/model/catalog/product.php">
    <operation>
      <search>
	    <![CDATA[public function addProduct($data) {]]>
      </search>
      <add position="before">
        <![CDATA[public function getLocations($product_id)
	{
		$query=$this->db->query("SELECT * FROM ". DB_PREFIX ."store_to_map WHERE product_id='".$product_id."' ");
		if($query->num_rows){
			return $query->rows;
		}else{
			return array();
		}
	}]]>
      </add>
    </operation>
	<operation>
      <search>
	    <![CDATA[if (isset($data['product_attribute'])) {]]>
      </search>
      <add position="before">
        <![CDATA[if(isset($data['locations'])){
           $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_store_locations SET product_id='". (int)$product_id ."'");
           $store_location_id = $this->db->getLastId();
         foreach ($data['locations'] as $location_name => $location) {
            $this->db->query("INSERT INTO " . DB_PREFIX . "store_to_map SET address='". $this->db->escape($location['name']) ."',store_location_id='". (int) $store_location_id ."',latitude='".$this->db->escape($location['lat']) ."',longitude='".$this->db->escape($location['lng']) ."',product_id='".  (int)$product_id  ."'");
         }
		}]]>
      </add>
    </operation>
	<operation>
      <search index="0">
	    <![CDATA[$this->db->query("DELETE FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "'");]]>
      </search>
      <add position="before">
        <![CDATA[$this->db->query("DELETE FROM " . DB_PREFIX . "product_to_store_locations WHERE product_id = '" . (int)$product_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "store_to_map WHERE product_id = '" . (int)$product_id . "'");

		if(isset($data['locations'])){
           $this->db->query("INSERT INTO " . DB_PREFIX . "product_to_store_locations SET product_id='". (int)$product_id ."'");
           $store_location_id = $this->db->getLastId();
         foreach ($data['locations'] as $location_name => $location) {
            $this->db->query("INSERT INTO " . DB_PREFIX . "store_to_map SET address='". $this->db->escape($location['name']) ."',store_location_id='". (int) $store_location_id ."',latitude='".$this->db->escape($location['lat']) ."',longitude='".$this->db->escape($location['lng']) ."',product_id='".  (int)$product_id  ."'");
         }
		}]]>
      </add>
    </operation>
  </file>
  
     <file path="catalog/view/theme/*/template/product/product.tpl">
    <operation>
      <search>
	    <![CDATA[<?php if ($tags) { ?>]]>
      </search>
      <add position="before">
        <![CDATA[ 
		<?php if(!empty($locations)){ ?>
        <div id="map" style="height: 400px; width: 100%;">
        <?php } ?>
</div>
<script type="text/javascript">
      var locations = [
     <?php $count=1; foreach($locations as $location){
     echo "['".$location['address']."',".$location['latitude'].",".$location['longitude'].",".$count."],";
     $count++;
     } ?>
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();
 var bounds = new google.maps.LatLngBounds();
    var marker, i;

    for (i = 0; i < locations.length; i++) { 
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map,
         url : "http://www.google.com/maps/place/"+locations[i][0]+"/@"+locations[i][1]+"/"+locations[i][2],
      });
      
       google.maps.event.addListener(marker, 'click', function() { 
			window.open(this.url, '_blank');
      });
      
      bounds.extend(marker.position);

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

    map.fitBounds(bounds);
  </script>]]>
      </add>
    </operation>
  </file>
     <file path="catalog/controller/product/product.php">
    <operation>
      <search>
	    <![CDATA[if ($product_info['quantity'] <= 0) {]]>
      </search>
      <add position="before">
        <![CDATA[$data['locations']=array();
			if(isset($this->request->get['product_id'])){
			$query=$this->db->query("SELECT * FROM ". DB_PREFIX ."store_to_map WHERE product_id='".$this->request->get['product_id']."' ");
			if($query->num_rows){
				$data['locations']= $query->rows;
			}else{
				$data['locations']=array();
			}
			}]]>
      </add>
    </operation>
	<operation>
      <search>
	    <![CDATA[public function index() {]]>
      </search>
      <add position="before">
        <![CDATA[public function getLocationsById(){
    $category_id=$this->request->get['category_id'];

    $result=$this->db->query("SELECT * FROM ". DB_PREFIX ."store_to_map WHERE product_id='".$category_id."'");
    if($result->num_rows){
    
    echo json_encode($result->rows);
   
    }else{
    return array();
    }
    }]]>
      </add>
    </operation>
  </file>
  
    <file path="catalog/view/theme/*/template/extension/module/*.tpl">
    <operation>
      <search>
	    <![CDATA[<div class="button-group">]]>
      </search>
      <add position="after">
        <![CDATA[ <a href="javascript:void(0);" onclick="openmaplocation('<?php echo $product['product_id']; ?>')" style="width:100% !important;" class="btn btn-primary" ><i class="fa fa-map-marker"></i><span class="button-cart-text">Store Locator</span><i class="button-right-icon"></i></a>]]>
      </add>
    </operation>
	
	<operation>
      <search>
	    <![CDATA[<div class="button-group">]]>
      </search>
      <add position="before">
        <![CDATA[  <a class="btn btn-info btn-lg" style="display:none" id="buttonlocation" data-backdrop="static" data-toggle="modal" data-target="#locatorModal">Add Location</a>
    <div id="locatorModal" class="modal fade" role="dialog">
      <div class="modal-dialog" style="width: 75%;">
        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">   
              Store
          </div>
          <div class="modal-body">
          <div id="location_not">
          </div>
          <div id="map" style="height: 400px; width: 100%;">
          
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" id="closemodal" data-dismiss="modal">Close</button>
          </div>
        </div>
    
      </div>
    </div>
    </div>
    
 

    <script>
    function show_locator(id){
    $("#store_locator"+id).show();
    }
    function hide_locator(id){
    $("#store_locator"+id).hide();
    }
    function openmaplocation(id){
    var locations = "";
    $.ajax({
    type:'GET',
    dataType:'json',
    url:'index.php?route=product/product/getLocationsById&category_id='+id,
    cache:false,
    success:function(data){
    if(data){
 
    $("#locatorModal").on("shown.bs.modal", function () { 

$("#map").show();
       var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();
 var bounds = new google.maps.LatLngBounds();
    var marker, i;

    for (i = 0; i < data.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(data[i].latitude, data[i].longitude),
        map: map,
         url : "http://www.google.com/maps/place/"+data[i].address+"/@"+data[i].latitude+"/"+data[i].longitude,
      });
      google.maps.event.addListener(marker, 'click', function() { 
			window.open(this.url, '_blank');
      });
      
      bounds.extend(marker.position);

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(data[i].address);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

    map.fitBounds(bounds);
    
    $("#location_not").html("");

}).modal('show');
    }else{
    $("#locatorModal").on("shown.bs.modal", function () { 
    $("#location_not").html('<b>Location is not set</b>');
    $("#map").hide();
    }).modal('show');
    }
    }
    });
    
     
    
      
    }
    
    </script>
	
	]]>
      </add>
    </operation>
  </file>
      <file path="catalog/view/theme/*/template/common/header.tpl">
    <operation>
      <search>
	    <![CDATA[<link href="catalog/view/theme/default/stylesheet/stylesheet.css" rel="stylesheet">]]>
      </search>
      <add position="before">
        <![CDATA[ <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&key=AIzaSyA3GRViajhZibChYv0YVIZZ6MuOXvmNyi8"></script>]]>
      </add>
    </operation>
  </file>
  
</modification>
