<?php
$collapse_add_area = "collapse";
$where 	= " WHERE 1=1 ";

$query_string = "";

$button_value 	= "Add";
$table_name		= "post_out";
$page_action 	= "add";
$page_name		= "Document Template";	
################################################## START EDIT ##################################################
if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
	$collapse_add_area = "";
	
	$page_action 	= "update";
	$button_value 	= "Update";
	$page_name		= "Edit Post Out";	
		
    $id = $_REQUEST['id'];
    $sql= "SELECT * FROM $table_name WHERE id = $id";
    $result_edit = mysqli_query($conn,$sql);
    $row_edit = mysqli_fetch_array($result_edit);

    $id= $row_edit['id'];
    $job_id= $row_edit['job_id'];
    $post_type= $row_edit['post_type'];
    $post_out_date= $row_edit['post_out_date'];
    $posting_method= $row_edit['posting_method'];
    $recipient= $row_edit['recipient'];
    $post_out_notes= $row_edit['post_out_notes'];
}
################################################# END EDIT ################################################# 

###########################################  PAGING WITH PER PAGE  #####################################
$query = "SELECT * FROM post_out ORDER BY post_out_date DESC ";
$sql=mysqli_query($conn,$query);
$total_no_of_timesheets=mysqli_num_rows($sql);
?>
<section class="content">
      <div class="container-fluid">
	  <div class="row">
	  <div class="col-12">
	  <div id="" class="card">
	  <div class="card-header">
			<h3 class="card-title"><? echo $page_name; ?></h3>

			<div class="card-tools">
				<div class="input-group input-group-sm" style="width: 150px;">
					
				</div>
			</div>
		</div>


	<div class="content-header">
					<div class="container-fluid">
						<div class="row mb-2">
							<div class="col-sm-6">
								<?php include_once('add_template_for_client.inc.php');?>
							</div>
							<div class="col-sm-6">
								<input type="text" name="search_for_document_template" id="search_for_document_template" class="pull-right" style="float:right;">
							</div>
						</div>
						<!-- /.row -->
					</div>
					<!-- /.container-fluid -->
				</div>
		
			<div class="card-body table-responsive" style="height: auto;">
				
					
						
						<table id="template_document_table" class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>Client</th>
									<th>Doc. Template</th>
									<th>Section</th>
									<th>Document</th>
									<th>Edit</th>
									<th>Delete</th>
								</tr>
							</thead>
						</table>
				
			</div>
		
	

</div>
</div>
</div>
</div>
</section>
	
<script type="text/javascript">
$(document).ready(function(){
	$('#add_document_template').click(function(){
		$('#document_template_area').slideToggle();
		var blank = "";	
		$("#document_template_id").select2("val", blank);
		var jb_id = "<?= $_REQUEST['id'];?>";
		$("#job_id").val(jb_id);
		$("#page_action").val("add");
		$("#submit_form").html("Add");
	});
	
	$('#template_document_table').DataTable({
        "processing": true,
        "serverSide": true,
		"paging": false,
		"lengthChange": false,
		"searching": false,
		"ordering": false,
		"info": false,
		"autoWidth": false,
        "ajax": "<?php echo $siteURL?>/template_document/index?page=ajax_template_document_for_admin&id=<?= $_REQUEST['id'];?>",
        "columns": [
            { "data": "client" },
			{ "data": "document_template" },
            { "data": "section_ids" },
			{
				sortable: false,
                 "render": function ( data, type, full, meta ){
                     var buttonID = full.id;
                     return '<a href="../../invoice/template_document.php?id='+buttonID+'" target="_blank"><i class="fa fa-file-text-o" style="font-size:20px;color:#333;"></i></a>';
                 }
            },
			{
				sortable: false,
                 "render": function ( data, type, full, meta ){
                     var buttonID = full.id;
                     return '<span style="cursor:pointer;" class="template_document_edit" alt="'+buttonID+'"><i class="fa fa-edit" style="font-size:20px;"></i></span><i class="fa fa-refresh fa-spin" style="display:none;" id="edit_doc'+buttonID+'"></i>';
                 }
            },
			{
				sortable: false,
                 "render": function ( data, type, full, meta ){
                     var buttonID = full.id;
                     return '<span style="cursor:pointer;" class="template_document_remove" alt="'+buttonID+'"><i class="fa fa-trash-o" style="font-size:20px;"></i></span>';
                 }
            }
        ],
		"drawCallback": function( settings ) {
			//alert( 'DataTables has redrawn the table' );
			//// Filtering 
			if($('#search_for_document_template').val() !=""){
				var value = $('#search_for_document_template').val().toLowerCase();
				//alert($("#telephone_message_table tr").text().toLowerCase().indexOf(value));
				//$("#telephone_message_table tr").filter(function() {
					setTimeout(function(){
						$("#template_document_table tbody tr").filter(function(){
							$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
						});
					},1000);
				//});
			}
		}
    });
	
	var template_document_t = $('#template_document_table').DataTable();
	$('#template_document_table tbody').on('click', '.template_document_edit',function(){
		/*$("html,body").animate({
			scrollTop: $("#document_template_area").offset().top - 110},
		'slow');*/
		
		var template_document_id = $(this).attr("alt");
		$("#edit_doc"+template_document_id).show();
		var form_data   = {'template_document_id':template_document_id};
		$.ajax({
			async: true,
			type: "POST",
			url: "<?php echo $siteURL?>/template_document/index?page=ajax_template_document_for_admin&action=edit_template_document",
			data: form_data,
			success: function(result){
				var resultObj = jQuery.parseJSON(result); 
				console.log(resultObj);
				if(resultObj.status == "success"){
					$('#document_template_area').slideDown();
					$.each(resultObj.data_array,function(data_array_key,data_array_val){
						if(data_array_key == "document_template_id"){
							$("#"+data_array_key).select2("val",data_array_val);
						}else if(data_array_key == "section_ids"){
							var section_array = data_array_val.split(",");
							$('#section_div').children().find("input[type='checkbox']").each(function(){
								//alert($(this).val());
								if(section_array.indexOf($(this).val()) != -1){
									$(this).iCheck('check');
								}
							});
						}else{
							$("#"+data_array_key).val(data_array_val);
						}
					});
					$("#edit_doc"+template_document_id).hide();
					$("#page_action").val("update");
					$("#submit_form").html("Update");
				}
			}
		});
	});
	
	$('#template_document_table tbody').on('click', '.template_document_remove',function(){
		var template_document_edit_id = $("#id").val();
		var template_document_id = $(this).attr("alt");
		if(template_document_edit_id == template_document_id){
			alert("This Id open in edit mode so you can not delete it.");
			return false;
		}
		if(confirm("Do you want to delete.")){
			var form_data   = {'template_document_id':template_document_id};
			$.ajax({
				async: true,
				type: "POST",
				url: "<?php echo $siteURL?>/template_document/index?page=ajax_template_document_for_admin&action=delete_template_document",
				data: form_data,
				success: function(result){
					var resultObj = jQuery.parseJSON(result); 
					if(resultObj.status == "success"){
						template_document_t.draw( false );
					}
				}
			});	
		}
	});
	
	$(document).on('submit','form#add_document_template_form',function(e){
		$(this).find('#document_template_done').hide();
		$(this).find('#page_load_div_for_document_template').show();
		$(this).find("#add_master_data").attr("disabled", true);
		
		e.preventDefault(); //prevent Default functionality
		var page_action = $("#page_action").val();
		var flag = 0;
		if(page_action == "add"){
			flag = 1;
		}
		
		var form_data = $('#add_document_template_form').serialize();     
		$.ajax({
			async: true,
			type: "POST",
			url: site_url+"/modules/template_document/index.php?page=ajax_template_document_for_admin&action=add_template_document",
			data: form_data,
			success: function(result){ 
				if(flag == 0){
					$("#page_action").val("add");
					$("#submit_form").html("Add");
					//$('#document_template_area').slideToggle();
				}
				$("#id").val("");
				$("#job_id").val("");
				var frm = document.getElementsByName('add_document_template_form')[0];
				for (var i=0; i < frm.length; i++){
					if (frm[i].getAttribute('id') == 'document_template_id'){
						$("#"+frm[i].getAttribute('id')).select2("val","");
					}else if(frm[i].getAttribute('class') == 'checkbox_div flat-red section_checkbox'){
						$(".section_checkbox").iCheck('uncheck');
					}
				}
				frm.reset();  // Reset all form data	
					
				$('#document_template_done').show();
				$('#page_load_div_for_document_template').hide();
				$("#add_master_data").attr("disabled", false);
				
				var resultObj = jQuery.parseJSON(result); 
				if(resultObj.status == "success"){
					template_document_t.draw( false );
				}
				setTimeout(function() {
					$('#document_template_done').hide();
				},1000);
				setTimeout(function() {
					$('#add_document_template').trigger("click");
				},1000);
			}
		});
	});
	
	$("#search_for_document_template").on("keyup", function() {
		var value = $(this).val().toLowerCase();
		$("#template_document_table tbody tr").filter(function() {
		  $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
		});
	});
});	
</script>