<?php
session_start();
//error_reporting(0);
include "../../includes/config.php";
require_once "../../includes/dbcontroller.php";
$db_handle = new DBController();
$delievery_image_desc_dropdowns = explode(",", $delievery_image_desc);

$role = $_SESSION["role"];
if ($role != "Admin" && $role != "User") {
    header("location:$website_url/");
    exit();
}
$delivery_id = $_GET["id"];
if (!isset($_GET["id"])) {
    header("location:$website_url$deliveries_url");
    exit();
}
$deldate = $_GET["deldate"];
$deltruckid = $_GET["deltruckid"];

$delivery_query = "SELECT * FROM deliveries where DeliveryID ='$delivery_id'";
$delivery_data_available = $db_handle->numRows($delivery_query);

if ($delivery_data_available > 0) {
    $delivery_data = current($db_handle->runQuery($delivery_query));
} else {
    header("location:$website_url$deliveries_url");
}

if (isset($_POST["update"])) {
    $address = $_POST["address"];
    $deliveryNotes = $_POST["deliverynotes"];
    $safetyNotes = $_POST["safetyissues"];
    $deliveryType = $_POST["deliverytype"];
    $deliveredTime = $_POST["deliveredtime"];
    if ($deliveredTime) {
        $update_delivery_query = "update deliveries set address ='$address',deliveryNotes='$deliveryNotes',safetyNotes='$safetyNotes',deliveryType='$deliveryType',deliveredTime='$deliveredTime',LastUpdated=NOW() where DeliveryID='$delivery_id'";
    } else {
        $update_delivery_query = "update deliveries set address ='$address',deliveryNotes='$deliveryNotes',safetyNotes='$safetyNotes',deliveryType='$deliveryType',LastUpdated=NOW() where DeliveryID='$delivery_id'";
    }

    $update_delivery_result = $db_handle->executeQuery($update_delivery_query);
    if ($update_delivery_result == 1) {
        echo "<script>alert('Delivery Record Updated Succesfully')</script>";
        echo "<script>location.href = '$website_url$deliveries_url?deldate=$deldate&deltruckid=$deltruckid';</script>";
    } else {
        echo "<script>alert('There is an issue on updating Delivery Record')</script>";
        echo "<script>location.href = '$website_url$deliveries_url';</script>";
    }
}
include "../../includes/menu.php";
?>

<div class="container main-cont single-edit-delivery">
	<h2 class="page-title">Edit delivery for <?php echo $delivery_data[
     "Address"
 ]; ?></h2>
	<div class="form-group">
		<form  enctype="multipart/form-data" method="post" accept-charset="utf-8">
			<div class="col-lg-12 col-xs-12 col-sm-12  col-md-12 outer-cell">
				<div class="inner-cell">
					<div class="frm-item">
						<label for="address">Delivery Address</label>            
						<input type="text" name="address" value="<?php echo $delivery_data[
          "Address"
      ]; ?>" class="form-control">
					</div>
				</div>
			</div>
			<div class="clearfix"></div>
				<div class="form-group col-md-6">
					<label for="deliverynotes">Delivery Notes</label>
					<textarea class="form-control" rows=4 id="deliverynotes" name="deliverynotes" placeholder="Delivery Notes"><?php echo $delivery_data[
         "DeliveryNotes"
     ]; ?></textarea>
				</div>			
			<div class="clearfix"></div> 
				<div class="form-group col-md-6">
					<label for="safetyissues">Safety Issues</label>
					<textarea class="form-control" rows=4 id="safetyissues" name="safetyissues" placeholder="Safety Issues"><?php echo $delivery_data[
         "SafetyNotes"
     ]; ?></textarea>
				</div>			
			<div class="clearfix"></div>
			<div class="col-lg-12 col-xs-12 col-sm-12  col-md-12 outer-cell">
				<div class="inner-cell">
					<div class="frm-item">
						<label for="deliverytype">DeliveryType</label>            
						<input type="text" name="deliverytype" value="<?php echo $delivery_data[
          "DeliveryType"
      ]; ?>" class="form-control">
					</div>
				</div>
			</div>
			<div class="clearfix"></div>
			<!--<div class="form-group col-md-6">
				<label for="delivered">Delivered</label>
				<select name="delivered" id="delivered" class="form-control" >
					<option value="0" <?php echo $account_data["Delivered"] == 0
         ? "selected"
         : ""; ?>>No</option>
					<option value="1" <?php echo $account_data["Delivered"] == 1
         ? "selected"
         : ""; ?>>Yes</option>
				</select>
			</div>-->
			<?php if ($delivery_data["DeliveredTime"]) { ?>
			<div class="col-lg-12 col-xs-12 col-sm-12  col-md-12 outer-cell">
				<div class="inner-cell">
					<div class="frm-item">
						<label for="deliveredtime">Delivery Address</label>            
						<input type="text" name="deliveredtime" value="<?php echo $delivery_data[
          "DeliveredTime"
      ]; ?>" class="form-control" disabled>
					</div>
				</div>
			</div>
			<?php } else { ?>
			<div class="form-group col-md-6 delivered-time-section">
				<div class="inner-cell">
					<div class="frm-item">
						<label for="deliveredtime">Deliverd Time</label>            
						<input type="datetime-local" name="deliveredtime" value="<?php echo $delivery_data[
          "DeliveredTime"
      ]; ?>" class="form-control">
					</div>
				</div>
			</div>
			<?php } ?>
			<div class="clearfix"></div> 
			<br />
			<div class="frm-btn">
				<input type="submit" name="update" value="Update Delievery" class="btn btn-primary btn-add">
			</div>
		</form>
		<br />
		<br />
		<?php if($delivery_data["DeliveredTime"]){ ?>
		<button type="button" name="add" id="add" class="btn btn-primary btn-add">Add Image</button>
		<br />
		<?php } ?>
		<br /><br />
	   <div id="image_data">

	   </div>
	</div> 
</div>

<?php
include "../../includes/footer.php";
include "../../includes/webfooter.php";
?>
<div id="imageModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">&times;</button>
    <h4 class="modal-title">Add Image</h4>
   </div>
   <div class="modal-body">
    <form id="image_form" method="post" enctype="multipart/form-data">
		<div class="form-group col-md-12">
			<label for="imgdesc">Image Description</label><br/>
			<select name="imgdesc" class="form-control imgdesc" required>
				<option value="">Please Select Description</option>
				<?php foreach (
        $delievery_image_desc_dropdowns
        as $delievery_image_desc_dropdown
    ) { ?>
				<option value="<?php echo $delievery_image_desc_dropdown; ?>"><?php echo $delievery_image_desc_dropdown; ?></option>
				<?php } ?>
			</select>
		</div>
		<div class="form-group col-md-12 img-other-desc">
			<label for="img_other_desc">Description</label><br/>
			<input type="text" name="img_other_desc" class="form-control img-other-desc-content">
		</div>
     <p><label>Select Image</label>
     <input type="file" name="image" id="image" /></p><br />
     <input type="hidden" name="action" id="action" value="insert" />
     <input type="hidden" name="delid" id="delid" value="<?php echo $delivery_id; ?>" />
     <input type="hidden" name="delivery_date" id="delivery_date" value="<?php echo !empty($_GET['deldate']) ? date('Y-m-d',strtotime($_GET['deldate'])) : ''; ?>" />
     <input type="hidden" name="image_id" id="image_id" />
     <input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
      
    </form>
   </div>
   <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
   </div>
  </div>
 </div>
</div>

<script>  
$(document).ready(function(){
 $('.img-other-desc').hide();
  $('.imgdesc').on('change', function(){
	var imgdesc = $(this).val();
	if(imgdesc=='Other'){
		$('.img-other-desc').show();
		$(".img-other-desc-content").attr("required","required");
	}
	else {
		$('.img-other-desc').hide();
		$(".img-other-desc-content").removeAttr("required");
	}
});
 
 fetch_data();

 function fetch_data()
 {
     
    $('#insert').prop("disabled", false);
  var action = "fetch";
  var delivery_id = <?php echo $delivery_id; ?>;
  $.ajax({
   url:"./templates/delivery/uploadimage.php",
   method:"POST",
   data:{delivery_id:delivery_id,action:action},
   success:function(data)
   {
    $('#image_data').html(data);
   }
  })
 }
 $('#add').click(function(){
  $('#imageModal').modal('show');
  $('#image_form')[0].reset();
  $('.modal-title').text("Add Image");
  $('#image_id').val('');
  $('#action').val('insert');
  $('#insert').val("Insert");
 });
 $('#image_form').submit(function(event){
  event.preventDefault();
  var image_name = $('#image').val();
  if(image_name == '')
  {
   alert("Please Select Image");
   return false;
  }
  else
  {
   var extension = $('#image').val().split('.').pop().toLowerCase();
   if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
   {
    alert("Invalid Image File");
    $('#image').val('');
    return false;
   }
   else
   {
       $('#insert').prop("disabled", true);
    $.ajax({
     url:"./templates/delivery/uploadimage.php",
     method:"POST",
     data:new FormData(this),
     contentType:false,
     processData:false,
     success:function(data)
     {
      alert(data);
      fetch_data();
      $('#image_form')[0].reset();
      $('#imageModal').modal('hide');
     }
    });
   }
  }
 });
 $(document).on('click', '.delete', function(){
  var image_id = $(this).attr("id");
  var action = "delete";
  if(confirm("Are you sure you want to remove this image from database?"))
  {
   $.ajax({
    url:"./templates/delivery/uploadimage.php",
    method:"POST",
    data:{image_id:image_id, action:action},
    success:function(data)
    {
     alert(data);
     fetch_data();
    }
   })
  }
  else
  {
   return false;
  }
 });
});  
</script>