<?php
//die(print_r($_SESSION, true));
//error_reporting(E_ALL);
if(stripos($_SERVER['SCRIPT_FILENAME'],"/admin/")>0){
	include_once("../connect.php");
	include_once("../session.php");
	$isAdmin = $_SESSION['isAdmin'];
}else{
	include_once("./connect.php");
	$isAdmin= false;
	include_once("./functions.php");
}
$query = "SET SESSION time_zone = '-04:00'";
mysqli_query($con, $query);

?>


 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <!--<meta name="viewport" content="width=device-width, initial-scale=1">-->
     <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
     <title><?= $config['CompanyName'] ?> - Assignments Queue</title>

     <!-- Bootstrap -->
     <link href="../css/bootstrap.min.css" rel="stylesheet">
     <link rel="stylesheet" href="../css/bootstrap-combobox.css" />

     <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
     <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
     <!--[if lt IE 9]>
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
       <script src="../js/functions.js"></script>
       <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->

           <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
            <script src="../js/functions.js"></script>
           <!-- Include all compiled plugins (below), or include individual files as needed -->
           <script src="../js/bootstrap.min.js"></script>
       	 <script src="../js/bootstrap-combobox.js"></script>
       	 <script src="../js/excellentexport.js"></script>
           <script type="text/javascript">
             $(document).ready(function(){
               //$(.)
             });
           </script>
					<link rel="stylesheet" href="../css/jquery.filthypillow.css" type="text/css" />
					<script src="../js/jquery.filthypillow.min.js" type="text/javascript"></script>
					<script src="../js/moment.js" type="text/javascript"></script>
     <![endif]-->
	<link rel="stylesheet" href="../css/styles.css"/>
   </head>
   <body>
<?php
//die( "test");
	include_once("./navbar.php");

?>
        <br /><br />
   <!-- Stack the columns on mobile by making one full-width and the other half-width -->

	<div class="container" style="padding-top: 10px;">
		<link href="../css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
		<script src="../js/fileinput.js" type="text/javascript"></script>

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

				<h3 class="panel-title" style="float: left;">Assignments</h3>
        <div class="pull-right">
          <button id="addNewAssignmentButton" class="btn btn-primary">Add New Assignment</button>
        </div>
        <br>
        <b>Driver:</b>
        <?php
        if($deliveryDriver){
          echo $deliveryDriver->FullName;
          ?>

          <?php

        }else{
        ?>
          <select class="form-control" name="driverSelect" id="driverSelect">
            <option selected value="-1">Select Driver</option>
            <?php
            $query = "SELECT FullName, ID SalesmanID FROM SALESMAN ORDER BY FullName";
            $result = mysqli_query($con, $query);
            while($row = mysqli_fetch_array($result )){
            ?>
              <option value="<?= $row['SalesmanID'] ?>"><?= $row['FullName'] ?></option>
            <?php
            }
             ?>

          </select>

          <script>
            $('#driverSelect').on('change', function(){
              //window.location ="mod.php?p=assignments&a=queue&sm=" + $('#driverSelect').val();

            });
          </script>

        <?php

      }
        ?>

				<small></small>
			</div>
			<div class="panel-body">
        <div id="assignmentList" class="list-group">

        </div>
			</div>
		</div>
    <script>
    $('#addNewAssignmentButton').on("click", function(){

      $("#AddEditAssignmentModal").modal('toggle');
    });
		fillAssignmentList("%");
		setInterval(function(){
			fillAssignmentList("%");
		}, 10000);
    function fillAssignmentList(SalesmanID){

			var oldData = $('#assignmentList').html();
      $.get("mod.php?p=assignments&a=functions&f=getAssignmentsByDriver&sm=" + SalesmanID, function(data){
				data = JSON.parse(data);
				for(var i = 0; i < data.length; i++){

	        var listElement =
	        $("<a/>").addClass("list-group-item").append(
	          $("<div/>").addClass("row").append(
	            $("<div/>").addClass("col-xs-6").append($("<h4/>").text("A" + data[i].AssignmentID)),

	          ),
	          $("<div/>").addClass("row").append(
	            $("<div/>").addClass("col-xs-9").append(
	              $("<span/>").text(data[i].ShipToName),
	              $("<br/>"),
	              $("<span/>").append($("<i/>").text(data[i].Driver.Name))
	            ),
	            $("<div/>").addClass("col-xs-3").append(
	                $("<button/>")
	                  .attr("data-id", data[i].ID)
	                  .addClass('btn')
	                  .addClass("btn-danger")
	                  .html('<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>')
	                  .on("click", function(e){
											console.log(e);
											console.log(e.target);
	                    $.get('mod.php?p=assignments&a=functions&f=deleteAssignment&id=' + $(e.currentTarget).data("id"), function(data){
	                      data = JSON.parse(data);
	                      fillAssignmentList("%");

	                    });

	                })
	            )

	          ),
	          $('<div/>').addClass("row").append(
	            $("<div/>").addClass("col-xs-12").append($("<h5/>").html(data[i].AssignmentDate)),
	              $("<div/>").addClass("col-xs-12").append($("<h5/>").html(data[i].PickupDate))
	          )

	        );
					var newData = $(listElement)[0].outerHTML;
					if(newData != oldData){
							console.log(newData);
							console.log(oldData);
							console.log('updated');
							$('#assignmentList').html('')
							$('#assignmentList').append(listElement);
					}else{
						console.log('update not needed');
					}

	      }
			});
    }


    </script>
	</div>

  <!-- ADD/EDIT ASSIGNMENT MODAL -->
	 <div class="modal fade" id="AddEditAssignmentModal">
		 <div class="modal-dialog modal-lg">
		   <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="AddEditAssignmentModalTitle">Add New Assigment</h4>
			 </div>
			 <div class="modal-body">
         <div class="row">
           <input type="hidden" id="AssignmentID">
           <div class="col-md-6">
             <div class="form-group">
               <label for="AccountNumber">Customer</label>
               <select class="form-control combobox" id="AccountNumber">
                 <option></option>
                 <?php
                 $query = "SELECT AccountNumber, Name, ShipToAddress1, ShipToAddress2, ShipToCity, ShipToState, ShipToZip, Contact, Phone  FROM CUSTOMER ORDER BY Name";
                 $result = mysqli_query($con, $query);
                 while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
                ?>
                <option
                  data-name="<?= htmlentities($row['Name']) ?>"
                  data-addr1="<?= htmlentities($row['ShipToAddress1']) ?>"
                  data-addr2="<?= htmlentities($row['ShipToAddress2']) ?>"
                  data-city="<?= htmlentities($row['ShipToCity']) ?>"
                  data-state="<?= htmlentities($row['ShipToState']) ?>"
                  data-zip="<?= htmlentities($row['ShipToZip']) ?>"
                  data-contact="<?= htmlentities($row['Contact']) ?>"
                  data-phone="<?= htmlentities($row['Phone']) ?>"
                  value="<?= $row['AccountNumber'] ?>"><?= $row['AccountNumber'] . " - " . $row['Name'] . " - " . $row['ShipToCity'] ?></option>
                <?php
                 }
                  ?>
               </select>


             </div>
             <div class="form-group">
               <label for="ShipToName">Name</label>
               <input type="text" class="form-control" id="ShipToName">
               <label for="ShipToAddress1">Address</label>
               <input type="text" class="form-control" id="ShipToAddress1">
               <input type="text" class="form-control" id="ShipToAddress2">
               <label for="ShipToCity">City</label>
               <input type="text" class="form-control" id="ShipToCity">
             </div>
             <div class="form-group">
               <div class="col-xs-6">
                 <label for="ShipToState">State</label>
                 <input type="text" class="form-control" id="ShipToState">
               </div>
               <div class="col-xs-6">
                 <label for="ShipToZip">Zip</label>
                 <input type="text" class="form-control" id="ShipToZip">
               </div>


             </div>
           </div>
           <div class="col-md-6">
             <div class="form-group">
               <label for="ContactName">Contact</label>
               <input type="text" class="form-control" id="ContactName">
             </div>
             <div class="form-group">
               <label for="ContactPhone">Phone</label>
               <input type="text" class="form-control" id="ContactPhone">
             </div>
             <div class="form-group">
               <label for="AssignmentTitle">Assigment Title</label>
               <input type="text" class="form-control" id="AssignmentTitle">
             </div>
             <div class="form-group">
               <label for="AssignmentText">Details</label>
               <textarea class="form-control" id="AssignmentText"></textarea>
             </div>

           </div>

           </div>
  			 </div>

			 <div class="modal-footer">

			   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
				 <button type="button" onclick="saveAssignment();" id="saveButton" class="btn btn-success">Save</button>
			 </div>
		   </div><!-- /.modal-content -->
		 </div><!-- /.modal-dialog -->
	   </div><!-- /.modal -->
     <script type="text/JavaScript">
      $('#AccountNumber').on("change", function(e){
        var selected = $('#AccountNumber option:selected');
        $('#ShipToName').val(selected.data("name"));
        $('#ShipToAddress1').val(selected.data("addr1"));
        $('#ShipToAddress2').val(selected.data("addr2"));
        $('#ShipToCity').val(selected.data("city"));
        $('#ShipToState').val(selected.data("state"));
        $('#ShipToZip').val(selected.data("zip"));
        $('#ContactName').val(selected.data("contact"));
        $('#ContactPhone').val(selected.data("phone"));
      });
			function saveAssignment(){
				$('#saveButton').prop("disabled", true);
				$.post("mod.php?p=assignments&a=functions&f=saveAssignment",
				{
					"AssignmentID"		:	$('#AssignmentID').val(),
					"AccountNumber"		:	$('#AccountNumber').val(),
					"ShipToName"			:	$('#ShipToName').val(),
					"ShipToAddress1"	:	$('#ShipToAddress1').val(),
					"ShipToAddress2"	:	$('#ShipToAddress2').val(),
					"ShipToCity"			:	$('#ShipToCity').val(),
					"ShipToState"			:	$('#ShipToState').val(),
					"ContactName"			:	$('#ContactName').val(),
					"ContactPhone"		:	$('#ContactPhone').val(),
					"AssignmentTitle"	: $('#AssignmentTitle').val(),
					"AssignmentText"	: $('#AssignmentText').val(),

				}, function(data){
						data = JSON.parse(data);
						if(data.Result){
							$("#AddEditAssignmentModal").modal('hide');
							clearAssignmentModal();
						}

				});
			}
     </script>
     <!-- END ADD/EDIT ASSIGNMENT MODAL -->




	   <script type="text/javascript">


		   function clearAssignmentModal() {
			   $('#isNew').val("0");
				 $('#saveButton').prop("disabled", false);
			   $('#AssignmentID').val("0");
				 $('#AccountNumber').val("");
				 $('#ShipToName').val("");
				 $('#ShipToAddress1').val("");
				 $('#ShipToAddress2').val("");
				 $('#ShipToCity').val("");
				 $('#ShipToState').val("");
				 $('#ContactName').val("");
				 $('#ContactPhone').val("");
				 $('#AssignmentTitle').val("");
				 $('#AssignmentText').val("");
				 $('#DeliveryUser').val("");
			 }


		   </script>

	 </div>

   </body>
 </html>
