<div class="panel panel-default">
  <div class="panel-heading form-inline">

  		<a class="btn btn-success" role="button" style="float: right;" href="#" download="Salesmen<?= "(" . date("m.d.Y") . ")" ?>.xls" href="#" onclick="return ExcellentExport.excel(this, 'salesmen', 'Salesmen');" data-toggle="tooltip" data-placement="left" title="Does not work with Internet Explorer">Export To Excel</a>
  		<div style="margin-right: 10px; float: right;">
        <div class="input-group">
  			
          <label for="active">Active Status</label>
          <select name="active" id="active">
            <option <?= (isset($_REQUEST['active'])&&$_REQUEST['active']=="1")?"selected":"" ?> value="1">Active</option>
            <option <?= (isset($_REQUEST['active'])&&$_REQUEST['active']=="0")?"selected":"" ?> value="0">Inactive</option>
            <option <?= (isset($_REQUEST['active'])&&$_REQUEST['active']=="-1")?"selected":"" ?> value="-1">All</option>
          </select>
          
        </div>
  		<div class="input-group">
  			<div id="clearButton" style="display: none;" class="input-group-addon" onclick="clearFilter()">
  				<span class="glyphicon glyphicon-remove" aria-hidden="true"></span></div>
  		 	<input type="text"   class="form-control" name="filter" placeholder="Filter" value="" />
  			<div class="input-group-addon" onclick="filter()">
  		      	<span class="glyphicon glyphicon-search" aria-hidden="true"></span></div>
  		</div>
  			<button class="btn btn-primary" onclick="addSalesman()" >Add New Salesman</button>
  	</div>

    <h3 class="panel-title">Salesmen</h3>
    <small>Click on a row to edit the salesman</small>
  </div>
  <div class="panel-body">
  <table class="table table-hover" id="salesmen">
    <thead>
    	<tr>
    		<th>Salesman ID</th>
    		<th>Name</th>
    		<th>Username</th>
    		<th>Email</th>
    		<th>Last Login</th>
    		<th>Update</th>
    	</tr>
    </thead>
   <?php
    $ShowActive = "Active = 1";
    if(isset($_REQUEST['active'])){
      if($_REQUEST['active'] == "0"){
        $ShowActive = "Active = 0";
      }elseif($_REQUEST['active'] == "-1"){
        $ShowActive = "1";
      }
    }
    
   	$query = "SELECT SALESMAN.*, UpdateDate FROM SALESMAN LEFT JOIN CUSTOMER_UPDATE ON(SALESMAN.ID = CUSTOMER_UPDATE.AccountNumber) WHERE $ShowActive ORDER BY FullName";
   	$result = mysqli_query($con, $query);
   	while ($row = mysqli_fetch_array($result)) {
   ?>
   		<tr onclick="editSalesman('<?= $row['ID'] ?>')">
   			<td><?= $row['ID'] ?></td>
   			<td><?= $row['FullName'] ?></td>
   			<td><?= $row['Username'] ?></td>
   			<td><?= $row['Email'] ?></td>
   			<td><?= date("m/d/Y g:i a",strtotime($row['LastLogin'])) ?></td>
				<td><?= $row['UpdateDate']?date("m/d/Y h:i a", strtotime($row['UpdateDate'])):"N" ?></td>
   		</tr>
   <?php
   	}
    ?>
    </table>
  </div>
</div>


<div class="modal fade" id="AddEditSalesman">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="AddEditTitle">Edit Salesman</h4>
      </div>
      <div class="modal-body">
      	<form>
      		<input type="hidden" id="isNew" name="isNew" value="" />
      		<div class="form-group">
      		    <label for="SalesmanID">Salesman ID</label>
      		    <input type="text" class="form-control" name="SalesmanID" readonly autocomplete="off" id="SalesmanID" placeholder="ID">
      		  </div>
      		<div class="form-group">
      		    <label for="SalesmanName">Name</label>
      		    <input type="text" class="form-control" name="SalesmanName" autocomplete="off" id="SalesmanName" placeholder="Name">
      		  </div>
      		  <div class="form-group">
      		    <label for="SalesmanUsername">Username</label>
      		    <input type="text" class="form-control" id="SalesmanUsername" placeholder="Username">
      		  </div>
      		  <div class="form-group">
      		    <label for="SalesmanEmail">Email</label>
      		    <input type="text" class="form-control" id="SalesmanEmail" placeholder="Email" value="">
      		  </div>
						<div class="form-group">
      		    <label for="SalesmanPhone">Phone (no symbols, just the numbers)</label>
      		    <input type="text" class="form-control" id="SalesmanPhone" placeholder="Phone" value="">
      		  </div>
      		  <div class="form-group">
      		    <label for="SalesmanPassword">Password</label>
      		    <input type="password" class="form-control" id="SalesmanPassword" placeholder="Password">
      		  </div>
      		  <div class="form-group">
      		    <label for="LastLogin">Last Login</label>
      		    <p id="LastLogin" class="help-block"></p>
      		  </div>
            <div class="form-group">
      		    <label for="MobileLoginBarcode">Login Barcode</label>
              <br>
      		    <img id="MobileLoginBarcode" />
      		  </div>

      	</form>
      </div>
      <div class="modal-footer">
      	<button type="button" class="btn btn-danger" id="deleteButton" onclick="deleteSalesman()" data-dismiss="modal">Delete</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" onclick="saveSalesmanInfo()">Save</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script src="/js/md5.js"></script>

<script type="text/javascript">
  $('#active').on("change", function(elem){
    var activeValue = ($($(elem)[0].target).val());
    window.location = "manage.php?a=salesmen&active=" + activeValue;
    });
	$('[name=filter]').on('keypress', function(e) {
		if (e.which == 13) {
			filter();
		}

	});
	function clearFilter() {
		$('[name=filter]').val("");
		$('#clearButton').css('display', 'none');
		$('tr').css('display', '');

	}
	function filter() {
		var	name = $('[name=filter]').val();
		filterByName(name);
	}
	function filterByName(name) {
		$('#clearButton').css('display', '');
		for (var i = 0; i < $('tr').length; i++) {
			if (i != 0) {
				var result = $('tr')[i].innerText.toUpperCase().indexOf(name.toUpperCase());
				if (result < 0) {
					$($('tr')[i]).css('display', 'none');
				}else {
					$($('tr')[i]).css('display', '');
				}
			}
		}
	}

	function clearModal() {
		$('#isNew').val("0");
		$('#SalesmanID').val("");
		$('#SalesmanID').prop("readonly", true);
		$('#SalesmanName').val("");
		$('#SalesmanUsername').val("");
		$('#SalesmanEmail').val("");
		$('#SalesmanPhone').val("");
		$('#SalesmanPassword').val("");
    $('#MobileLoginBarcode').attr("src","");
    $('#MobileLoginBarcode').hide();
		$('#LastLogin').text("");
	}
	function addSalesman() {
		clearModal();
		$('#isNew').val("1");
		$('#AddEditTitle').text("Add Salesman");
		$('#SalesmanID').prop("readonly", null);
		$('#LastLogin').text("Never");
		$('#deleteButton').css('display', 'none');
		$('#AddEditSalesman').modal('toggle');
	}
	function editSalesman(ID) {
		clearModal();
		$.get("functions.php?action=getSalesmanInfo&salesman=" + ID, function(data){
		 	var salesman = JSON.parse(data);
		 	var lastLogin = salesman.LastLogin;
		 	if (lastLogin == null) {
		 		lastLogin = "Never";
		 	}else{
		 		lastLogin = new Date(lastLogin);
		 		lastLogin = lastLogin.format("M j, Y g:i a");
		 	}

			$('#isNew').val("0");
			$('#AddEditTitle').text("Edit Salesman");
			$('#SalesmanID').val(salesman.ID);
			$('#SalesmanName').val(salesman.Name);
			$('#SalesmanUsername').val(salesman.Username);
			$('#SalesmanEmail').val(salesman.Email);
			$('#SalesmanPhone').val(salesman.Phone);
			$('#SalesmanPassword').val("NOCHANGE");
			$('#LastLogin').text(lastLogin);
			$('#deleteButton').css('display', '');
			$('#MobileLoginBarcode').show();
      //var hash = CryptoJS.MD5(salesman.Username + salesman.Password);
      //console.log(hash);
      $('#MobileLoginBarcode').attr("src", "/assets/barcode.php?text=" + salesman.MobileLoginBarcode);
      $('#AddEditSalesman').modal();
		});
	}
	function saveSalesmanInfo() {
		var salesmanData = '{ "ID" : "' + $('#SalesmanID').val() + '", "Name" 	:	"' + $('#SalesmanName').val() + '", "Username"	:	"' + $('#SalesmanUsername').val() + '", "Email"	:	"' + $('#SalesmanEmail').val() + '", "Phone"	:	"' + $('#SalesmanPhone').val() + '", "Password"	:	"' + $('#SalesmanPassword').val() + '", "IsNew" : "' + $('#isNew').val() + '"}';
		salesmanData = JSON.parse(salesmanData);
		$.post( "functions.php?action=saveSalesmanInfo", salesmanData)
		  .done(function( data ) {
		    if (data == "true") {
		    	clearModal();
		    	$('#AddEditSalesman').modal('toggle')
		    	location.reload();
		    }else {
		    	alert("There has been an error saving the salesman data");
		    }
		  });
	}
	function deleteSalesman() {
		if (confirm("Are you sure you want to delete this salesman from the database? This cannot be undone.\r\nThis action can leave customers and orders orphaned")) {
			var SalesmanID = $('#SalesmanID').val();
			$.post( "functions.php?action=deleteSalesman&salesmanID=" + SalesmanID, null)
			  .done(function( data ) {
			  data = $.parseJSON(data);
			  console.log(data.result);
			    if (data.result == true) {
			    	clearModal();
			    	$('#AddEditSalesman').modal('toggle')
			    	location.reload();
			    }else {
			    	alert("There has been an error deleting the salesman");
			    }
			  });
		  }

	}
	Date.prototype.format=function(e){var t="";var n=Date.replaceChars;for(var r=0;r<e.length;r++){var i=e.charAt(r);if(r-1>=0&&e.charAt(r-1)=="\\"){t+=i}else if(n[i]){t+=n[i].call(this)}else if(i!="\\"){t+=i}}return t};Date.replaceChars={shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],longMonths:["January","February","March","April","May","June","July","August","September","October","November","December"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],longDays:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],d:function(){return(this.getDate()<10?"0":"")+this.getDate()},D:function(){return Date.replaceChars.shortDays[this.getDay()]},j:function(){return this.getDate()},l:function(){return Date.replaceChars.longDays[this.getDay()]},N:function(){return this.getDay()+1},S:function(){return this.getDate()%10==1&&this.getDate()!=11?"st":this.getDate()%10==2&&this.getDate()!=12?"nd":this.getDate()%10==3&&this.getDate()!=13?"rd":"th"},w:function(){return this.getDay()},z:function(){var e=new Date(this.getFullYear(),0,1);return Math.ceil((this-e)/864e5)},W:function(){var e=new Date(this.getFullYear(),0,1);return Math.ceil(((this-e)/864e5+e.getDay()+1)/7)},F:function(){return Date.replaceChars.longMonths[this.getMonth()]},m:function(){return(this.getMonth()<9?"0":"")+(this.getMonth()+1)},M:function(){return Date.replaceChars.shortMonths[this.getMonth()]},n:function(){return this.getMonth()+1},t:function(){var e=new Date;return(new Date(e.getFullYear(),e.getMonth(),0)).getDate()},L:function(){var e=this.getFullYear();return e%400==0||e%100!=0&&e%4==0},o:function(){var e=new Date(this.valueOf());e.setDate(e.getDate()-(this.getDay()+6)%7+3);return e.getFullYear()},Y:function(){return this.getFullYear()},y:function(){return(""+this.getFullYear()).substr(2)},a:function(){return this.getHours()<12?"am":"pm"},A:function(){return this.getHours()<12?"AM":"PM"},B:function(){return Math.floor(((this.getUTCHours()+1)%24+this.getUTCMinutes()/60+this.getUTCSeconds()/3600)*1e3/24)},g:function(){return this.getHours()%12||12},G:function(){return this.getHours()},h:function(){return((this.getHours()%12||12)<10?"0":"")+(this.getHours()%12||12)},H:function(){return(this.getHours()<10?"0":"")+this.getHours()},i:function(){return(this.getMinutes()<10?"0":"")+this.getMinutes()},s:function(){return(this.getSeconds()<10?"0":"")+this.getSeconds()},u:function(){var e=this.getMilliseconds();return(e<10?"00":e<100?"0":"")+e},e:function(){return"Not Yet Supported"},I:function(){var e=null;for(var t=0;t<12;++t){var n=new Date(this.getFullYear(),t,1);var r=n.getTimezoneOffset();if(e===null)e=r;else if(r<e){e=r;break}else if(r>e)break}return this.getTimezoneOffset()==e|0},O:function(){return(-this.getTimezoneOffset()<0?"-":"+")+(Math.abs(this.getTimezoneOffset()/60)<10?"0":"")+Math.abs(this.getTimezoneOffset()/60)+"00"},P:function(){return(-this.getTimezoneOffset()<0?"-":"+")+(Math.abs(this.getTimezoneOffset()/60)<10?"0":"")+Math.abs(this.getTimezoneOffset()/60)+":00"},T:function(){var e=this.getMonth();this.setMonth(0);var t=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,"$1");this.setMonth(e);return t},Z:function(){return-this.getTimezoneOffset()*60},c:function(){return this.format("Y-m-d\\TH:i:sP")},r:function(){return this.toString()},U:function(){return this.getTime()/1e3}}
	</script>
