<?php
//die(print_r($_SESSION, true));
//error_reporting(E_ALL);
//echo "test";
$query = "SET SESSION time_zone = '-04:00'";
if(isset($_REQUEST['sm'])){
  $deliveryDriver = new Salesman($_REQUEST['sm']);
}
?>


 <!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'] ?> - Load Deliveries</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

	include("./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;">Load Deliveries</h3>
        <button style="margin-left: 10px;" class="btn btn-primary" onclick="$('#WaitingToBeLoadedModal').modal();">View Waiting to be Loaded</button>
        <br><br>
        <b>Delivery Driver:</b>
        <?php
        if($deliveryDriver){
          echo $deliveryDriver->FullName;
          ?>
          <a href="mod.php?p=deliveryroutes&a=loadDeliveries" class="btn btn-primary">Change Driver</a><br><BR>
          <b>Delivery Count: </b><span id="deliveryCount"></span><br>
          <input type="text" name="LoadInvoiceByID"  class="form-control" placeholder="INVOICE ID" />
          <?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=deliveryroutes&a=loadDeliveries&sm=" + $('#driverSelect').val();

            });
          </script>

        <?php

      }
        ?>

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

        </div>
			</div>
		</div>
    <script>
    getDeliveriesList();
    $('[name=LoadInvoiceByID]').on("keyup", function(e){
      if(e.keyCode == "13" || e.keyCode == "0"){
        addToDeliveryList($('[name=LoadInvoiceByID]').val());
      }
    });
    function fillDeliveriesList(data){
      $('#deliveryList').html('');
      $('#deliveryCount').text(data.length);

      for(var i = 0; i < data.length; i++){
        //console.log(data);
        var listElement =
        $("<a/>").addClass("list-group-item").append(
          $("<div/>").addClass("row").append(
            $("<div/>").addClass("col-xs-6").append($("<h4/>").text(data[i].InvoiceID)),


          ),
          $("<div/>").addClass("row").append(
            $("<div/>").addClass("col-xs-9").append(
              $("<span/>").text(data[i].ShipToName),
              $("<br/>"),
              $("<span/>").append($("<b/>").text(data[i].ShipToCity)),
              $("<br/>"),
              $("<span/>").append($("<i/>").text(data[i].FullName))
            ),
            $("<div/>").addClass("col-xs-3").append(
                $("<button/>")
                  .data("id", data[i].id)
                  .addClass('btn')
                  .addClass("btn-danger")
                  .html('<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>')
                  .on("click", function(data){
                    $.get('mod.php?p=deliveryroutes&a=functions&f=deleteLoadedDelivery&id=' + $(this).data("id") + "&sm=<?= $_REQUEST['sm'] ?>", function(data){
                      data = JSON.parse(data);
                      fillDeliveriesList(data);
                      $('[name=LoadInvoiceByID]').val("");
                      $('[name=LoadInvoiceByID]').focus();
                    });

                })
            )

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

        );
        $('#deliveryList').append(listElement);
      }


    }
    function addToDeliveryList(invoiceID){
      $.get("mod.php?p=deliveryroutes&a=functions&f=addToDeliveryList&invoice=" + invoiceID + "&sm=" + "<?= $_REQUEST['sm'] ?>", function(data){
        data = JSON.parse(data);
        fillDeliveriesList(data);
        $('[name=LoadInvoiceByID]').val("");
        $('[name=LoadInvoiceByID]').focus();
      })
    }
      function getDeliveriesList(){
        $.ajax({
            url : "mod.php?p=deliveryroutes&a=functions&f=getDeliveriesBySalesman&sm=" + "<?= $_REQUEST['sm'] ?>",
            type : "get",
            async: true,
            success : function(data) {
               data = JSON.parse(data);
               fillDeliveriesList(data);
            },
            error: function() {
              return null;
            }
         });

      }

    </script>
	</div>

  <!-- WAITING TO BE DELIVERED MODAL LIST -->
	 <div class="modal fade" id="WaitingToBeLoadedModal">
		 <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="WaitingToBeLoadedModalTitle">Invoices Waiting to Be Loaded</h4>
			 </div>
			 <div class="modal-body">
         <table id="WaitingToBeLoadedTable" class="table table-condensed">
           <tr>
             <th>Inv ID</th>
             <th>Name</th>
            <th>City</th>
             <th>Days</th>

             <th>Salesman</th>
             <th>Mark as Delivered</th>
           </tr>

         <?php
         $query = "SELECT InvoiceID, InvoiceDate, ShipToName, ShipToCity FROM INVOICE_HEAD LEFT JOIN DELIVERY_RECORD USING(InvoiceID) WHERE Delivered = 0 AND Void = 0 AND Status = 1 AND PickupDate IS NULL
UNION
SELECT CONCAT(\"A\", AssignmentID) InvoiceID, AssignmentDate InvoiceDate, ShipToName, ShipToCity FROM ASSIGNMENT_HEAD WHERE DeliveryUser IS NULL AND Completed = 0
ORDER BY ShipToCity";
         $result = mysqli_query($con, $query);
         $rows = mysqli_num_rows($result);
         while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
           $invoice = new Invoice($row['InvoiceID']);
           $daysInvoiced = (new DateTime($row['InvoiceDate']))->diff(new DateTime())->days;
           if(substr($row['InvoiceID'],0,1) == "A"){
             $url = "mod.php?p=assignments&a=view&id={$row['InvoiceID']}";
           }else{
             $url = "mod.php?p=invoice&a=view&id={$invoice->InvoiceID}";
           }
           ?>
           <tr class="<?= $daysInvoiced>6?"danger":"" ?>" id="row-<?= $row['InvoiceID']?>">
             <td><a target="_blank" href="<?= $url ?>"><?= $row['InvoiceID'] ?></a></td>
             <td><?= $row['ShipToName'] ?></td>
             <td><?= $row['ShipToCity'] ?></td>
            <td><?= $daysInvoiced ?></td>
             <td><?= $invoice->Salesman->FullName ?></td>

             <td><button onclick="openSetAsDeliveredModal('<?= $row['InvoiceID'] ?>');" class="btn btn-success"><span class="glyphicon glyphicon-ok" aria-hidden="true"></span></button></td>
           </tr>
           <?php
         }
          ?>
			   </table>
         <br>
         Total Rows: <span id="WaitingToBeLoadedNumRows"><?= $rows ?></span>
			 </div>
			 <div class="modal-footer">
			   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
			 </div>
		   </div><!-- /.modal-content -->
		 </div><!-- /.modal-dialog -->
	   </div><!-- /.modal -->
     <!-- END WAITING TO BE DELIVERED MODAL LIST -->



     <!-- SET AS DELIVERED MODAL -->
   	 <div class="modal fade" id="SetAsDeliveredModal">
   		 <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="SetAsDeliveredModalTitle">Set As Delivered</h4>
   			 </div>
   			 <div class="modal-body">
            <form class="">
              <input class="form-control" id="setAsDeliveredInvoiceID" type="hidden" name="setAsDeliveredInvoiceID" />
              <div class="form-group">
                <label for="deliveredDate">Delivery Date</label>
                <input class="form-control" id="deliveredDate" type="date" name="deliveredDate" />
              </div>
              <div class="form-group">
                <label for="deliveryDriver">Delivery Driver</label>
                <select class="form-control" name="deliveryDriver" id="deliveryDriver">
                  <option 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
                  }
                   ?>
                   <option value="customer">Customer Pickup</option>

                </select>
              </div>
            </form>
   			 </div>
   			 <div class="modal-footer">
           <button type="button" onclick="submitSetAsDelivered();" class="btn btn-primary">Save</button>
   			   <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   			 </div>
   		   </div><!-- /.modal-content -->
   		 </div><!-- /.modal-dialog -->
   	   </div><!-- /.modal -->
        <!-- END SET AS DELIVERED MODAL -->
	   <script type="text/javascript">


      function openSetAsDeliveredModal(InvoiceID){
        $('#setAsDeliveredInvoiceID').val(InvoiceID);
        $('#SetAsDeliveredModal').modal();
      }
      function submitSetAsDelivered(){
        var invoiceID = $('#setAsDeliveredInvoiceID').val();
        var deliveryDate = $('#deliveredDate').val();
        var deliveryDriver = $('#deliveryDriver').val();
        $.post("mod.php?p=deliveryroutes&a=functions&f=setAsDelivered",
          {
            "invoiceID" : invoiceID,
            "deliveryDate" : deliveryDate,
            "deliveryDriver" : deliveryDriver
          }
        ,function(data){
            if(data == "true"){
              $('#setAsDeliveredInvoiceID').val("");
              $('#SetAsDeliveredModal').modal('hide');
              $('#SetAsDeliveredModal').on('hidden.bs.modal', function () {
                setTimeout(function(){
                  $('body').addClass("modal-open");
                },500);
              });
              $("#row-" + invoiceID).hide();

              $('#WaitingToBeLoadedNumRows').text($('#WaitingToBeLoadedTable tr').length-1);
            }

        });
      }
		   $('[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");
			   $('#DeliveryOptionID').val("-1");
			   $('#DeliveryOptionName').val("");
			   $('#DeliveryOptionStartTime').val("");
				 $('#DeliveryOptionCutoffTime').val("");
			   $('#DeliveryOptionDeliveredBy').val("");
			   $('#DeliveryOptionComment').val("");
				 $('#DeliveryOptionFeeRule').val("");
			 }


		   </script>

	 </div>

   </body>
 </html>
