<?php

include_once 'inc/functions.php';
include_once 'inc/database.php';
	
include_once 'requestFunctions.php';
	
require_once __DIR__ . '/vendor/autoload.php';
use Bigcommerce\Api\Client as Bigcommerce;
include_once 'header.php';


if(isset($_GET['hash']) )
{
	$store_hash=$_GET['hash'];	
}

?>

<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">

<!-- date picker  -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<style>
	
#promotion_pagination span	{
	  background: white;
    width: 30px;
    height: 30xp;
    height: 30px;
    border: 1px;
    border-radius: 5px;
    text-align: center;
    line-height: 30px;	
    margin: 0px 10px;
    cursor: pointer;
	}
	#promotion_pagination span.active{
		background: #337AB7;
		color: white;
	}
	#promotion_table button{
		background: #337AB7;
		color: white;

	}

	/*loader css*/
	#overlay{	
  position: fixed;
  top: 0;
  z-index: 100;
  width: 100%;
  height:100%;
  display: none;
  background: rgba(0,0,0,0.6);
}
.cv-spinner {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;  
}
.spinner {
  width: 40px;
  height: 40px;
  border: 4px #ddd solid;
  border-top: 4px #2e93e6 solid;
  border-radius: 50%;
  animation: sp-anime 0.8s infinite linear;
}
@keyframes sp-anime {
  100% { 
    transform: rotate(360deg); 
  }
}
.is-hide{
  display:none;
}

/*loader css end*/

#response-msg-parent{
	background: #337AB7!important;
	color: white;
}
#promotion_table td,th{
	text-align: center;
}
</style>


</head>

<?php  include_once("subscription/header.php"); ?>

		<div id="overlay">
		  <div class="cv-spinner">
		    <span class="spinner"></span>
		  </div>
		</div>
        
    <div class="d-flex justify-content-center" style="width:100%; display: none; padding: 25px;" id="all_promotion_table">

        <form id="promotion_form" style="width: 100%;">

         		<div class="alert  alert-dismissible fade show" role="alert" id="response-msg-parent" style="margin-top:10px;">
         			<span id="response-msg"></span>
         			<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
         		</div>

         		<h4 style="text-align: center;margin-top: 30px;">
         			<?php
         			 echo $_GET['channel']," ";
         			 if($_GET["redemption_type"]=="AUTOMATIC")
         			 {
         			 	echo " Promotions";
         			 }
         			 else{
         			 	echo " Coupon";
         			 }

         		  ?>


         		</h4>

         		<button class="btn btn-primary" id="promotions-delete-button" style="margin-top: 10px;background-color: #337AB7;">Bulk Delete</button>

		    		<table class="table table-striped mt-3" style="width:100%;"  id="promotion_table">
						  <thead>
						    <tr>
						     <th>Bulk Delete</th>
						      <th scope="col">Name</th>
						      <th scope="col">Start Date</th>
						      <th scope="col">End Date</th>
						      <th scope="col">Status</th>
						      <th scope="col">Action</th>
						    </tr>
						  </thead>
						  <tbody id="all_promotion">
						  	
						  </tbody>
				  </table>
				  <div id="promotion_pagination" class="d-flex">
					</div>
			  </form>

	  </div>

<div  class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Update Promotion</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="updateForm">
				    <!-- Add form fields here -->
				    <input type="hidden" name="promotions_id" value="" id="promotions_ids">
				    <div class="form-group">
				        <label for="name">Name</label>
				        <input type="text" class="form-control" id="name" name="name">
				    </div>
				    <div class="form-group">
				        <label for="start_date">Start Date</label>
				        <input type="text" class="form-control" id="start_date" name="start_date">
				    </div>
				    <div class="form-group" id="update_end_date">
				        <label for="end_date">End Date</label>
				        <input type="text" class="form-control" id="end_date" name="end_date">
				    </div>
				    <div id="add_append_form">
				    </div>
				
		      </div>
		      <div class="modal-footer">
		        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="form_close_btn">Close</button>
		        <button type="button" class="btn btn-primary" id="model-save-btn">Save changes</button>
		      </div>

       </form>

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



<!-- Modal -->


<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>

<script>

$(document).ready(function() {

	$(document).on("click", ".update-button", function(event) {
    event.preventDefault();
    // Rest of your code for updating the promotion
   });


	//$('#promotion_table').DataTable();

	  $('#promotions-loader').show();
	  $("#overlay").fadeIn(300);

		// handle pagination
		 $("#promotion_pagination").on("click","span", function() {
	     var pageNo = $(this).data("page");
	     all_promotions(pageNo);
	    
	   });
		//end pagination

	// Function to  and populate data
	  $("#response-msg-parent").hide();
	
     $(document).on('click', '.update-button', function() {

		    var $row = $(this).closest('tr'); // Get the table row
		    	var add_fields=$row.find('td:nth-child(1)').html();
     	$("#add_append_form").html(add_fields);
     	console.log(add_fields);
		    
		    // Get data from the table row
		    var promotions_ids = $row.find('td:nth-child(2)').text();
		    var name = $row.find('td:nth-child(4)').text();
		    var start_date = $row.find('td:nth-child(5)').text();
		    var end_date = $row.find('td:nth-child(6)').text();
		    //var status = $row.find('td:nth-child(6)').text();

		    // Convert the date strings to Date objects
		    var startDateObj = new Date(start_date);
		    var endDateObj = new Date(end_date);

		   
		    var formattedStartDate = $.datepicker.formatDate('yy-mm-dd', startDateObj);
		    var formattedEndDate = $.datepicker.formatDate('yy-mm-dd', endDateObj);

		    $('#start_date').datepicker({
			    dateFormat: 'yy-mm-dd'
			  });

			  $('#end_date').datepicker({
			    dateFormat: 'yy-mm-dd'
		  	});
		    
		    // Populate modal form fields
		    $('#name').val(name);
		    $('#start_date').val(start_date);
		    $('#end_date').val(end_date);
		    $("#promotions_ids").val(promotions_ids);

		   
		    $('#start_date').datepicker();
		    $('#end_date').datepicker();

		    // Set the date values for the Datepicker fields
		    $('#start_date').datepicker('setDate', formattedStartDate);
		    $('#end_date').datepicker('setDate', formattedEndDate);
		 });

	// end model functionality

	
		// get all promotions
		all_promotions(1);
		  $(document).ajaxSend(function() {
	    $("#overlay").fadeIn(300);　
	  });

		function all_promotions(page)
		{
			var store_hash="<?php echo $_GET['hash']; ?>";
			var redemption_type="<?php echo $_GET['redemption_type']; ?>";
			var channel_id="<?php echo $_GET['channel_id']; ?>";
			
		   $.ajax({
		          type: 'get',
		          url: 'list-promotions.php', 
		          dataType:'json',
		          data: {store_hash:store_hash,redemption_type:redemption_type,channel_id:channel_id,page:page},
		          success: function(response) {
		          	 
		          	
		          	
		             $('#all_promotion').html(response.all_promotions);
		             $("#promotion_pagination").html(response.pagination);
		             $("#all_promotion_table").css("display", "block");
		               
		          }
		      }).done(function() {
	      setTimeout(function(){
	        $("#overlay").fadeOut(300);
	      },500);
	    });

		}

		$(document).on("change", "#channel", function(){
			var channel_name=$("#channel :selected").text();
	        var channel_id = $("#channel :selected").val();
	        var menu_item = $("#menu :selected").val();
	        var redemption_type="<?php echo $_GET['redemption_type']; ?>";
	        window.location.href = "?redemption_type="+redemption_type+"&hash=<?echo $store_hash;?>&channel_id="+channel_id+"&channel="+channel_name;
	    });

		// delete promotions
		 $("#promotions-delete-button").click(function(event) {
		 	
		 	 event.preventDefault();
		 	 var store_hash="<?php echo $store_hash; ?>";

		 	  var selectedPromotions = $('input[name="promtion_ids[]"]:checked').map(function() {
	            return $(this).val();
	        }).get();
		       
		        $.ajax({
		            type: 'POST',
		            url: 'bulk_delete_promotions.php',
		            dataType:'json',
		            data: {promotions_ids:selectedPromotions,store_hash:store_hash},
		            success: function(response) {
		                //$('#result').html(response);
		                $("#response-msg").text(response.msg);

		                all_promotions(1);
		                $("#response-msg-parent").show();
		            }
		        });
		    
		});
	 // delete promotions end
	
	 	// update promotions
		 $("#model-save-btn").click(function(event) {

		 	  
		    event.preventDefault();

		    var store_hash="<?php echo $_GET['hash']; ?>";

		    var promotion_name = $('#name').val();
		    var start_date = $('#start_date').val(); // Get the value of the start_date field
		    var end_date = $('#end_date').val(); // Get the value of the end_date field
		    var promotions_ids = $('#promotions_ids').val(); // Get the value of the promotions_ids field

		    
		    var currency_code=$("#updateModal #currency_code").val();
		    
		    var stop=$("#updateModal #stop").val();
		    var Fixed_discount=$("#updateModal #Fixed-Discount").val();
		    var Percentage_Discount=$("#updateModal #Percentage-Discount").val();
		    var target_product_id =$("#updateModal #targets_product_ids").val();
		    var target_minimum_quantity =$("#updateModal #target_minimum_quantity").val();

		    var Promotion_product_ids =$("#updateModal #Promotion_product_ids").val();
		    var promotion_minimum_quantity =$("#updateModal #promotion_minimum_quantity").val();

		    var product_minimum_spend =$("#updateModal #product_minimum_spend").val();
		    var Category_ids =$("#updateModal #Category_ids").val();

		    var promotion_product_quantity =$("#updateModal #promotion_product_quantity").val();
		    var target_product_quantity =$("#updateModal #target_product_quantity").val();
		    var gift_product_id =$("#updateModal #gift_product_id").val();
		    var customer_group_ids =$("#updateModal #customer_group_ids").val();
		    var minimum_order_count =$("#updateModal #minimum_order_count").val();
		    

		    if ($("#updateModal #Percentage-Discount").length > 0) {
				  
				  var discount = $("#updateModal #Percentage-Discount").val();
				  discount=discount+"per";
				  
				} else {
					var discount=$("#updateModal #Fixed-Discount").val();
					discount=discount+"fixed";
				  
				}

		  

		    /*console.log(promotion_name);
		    console.log(start_date);
		    console.log(end_date);
		    console.log(promotions_ids);*/
		    $("#updateModal").modal("hide");

		    $.ajax({
		        type: 'POST',
		        url: 'update_promotions.php',
		        dataType:'json',
		        data: {
		            promotion_name: promotion_name,
		            start_date: start_date,
		            end_date: end_date,
		            promotions_ids: promotions_ids,currency_code:currency_code,stop:stop,discount:discount,target_product_id:target_product_id,target_minimum_quantity:target_minimum_quantity,Promotion_product_ids:Promotion_product_ids,promotion_minimum_quantity:promotion_minimum_quantity,product_minimum_spend:product_minimum_spend,Category_ids:Category_ids,promotion_product_quantity:promotion_product_quantity,target_product_quantity:target_product_quantity,gift_product_id:gift_product_id,minimum_order_count:minimum_order_count,customer_group_ids:customer_group_ids,
		            store_hash:store_hash
		        },
		        success: function(response) {
		        	//console.log(response.msg);
		            $("#response-msg").text(response.msg);
		            all_promotions(1);
		            $("#updateModal").modal("hide");
		            $("#response-msg-parent").show();

		        }
		    });
		});

	 // update promotions end

	 $("#form_close_btn").on("click",function(){
		$("#add_append_form").html();
		console.log("close click");
	})

});

</script>    