<?php 
include "includes/header.php"; 
include "includes/Mdme-functions.php";
$mdme = getMdmePurchaseEntry($db,'');
include_once "includes/pagepermission.php";
include_once "common/dpselect-functions.php";
//check permission - START
if(!($res_modm_prm)){
	header("Location:".admin_public_url."error.php");
}
else if(trim($res_modm_prm['ViewPrm'])=="0") {
	header("Location:".admin_public_url."error.php");
}
//check permission - END

$Srch_FilterOptions = array( array('ID' => 'pdt_sku', 'Name' => 'Product SKU'), array('ID' => 'inv_no', 'Name' => 'Invoice No'));

?> 


<div class="wrapper">
    <div class="container">
        <!-- Page-Title - START -->
        <div class="row">
            <div class="col-sm-12">   
</br>
				<div class="btn-group pull-right m-t-15">									
					<?php if(trim($res_modm_prm['AddPrm'])=="1") { ?>
						<a href="purchase_form.php" class="btn btn-custom waves-effect waves-light"> Add Purchase <span class="m-l-5"><i class="fa fa-plus"></i></span> </a>
					<?php } ?>
                </div>
						
                <h4 class="page-title">Manage Purchase</h4>
				<input type="hidden" name="disptblname" id="disptblname" value="<?php echo "purchase"; ?>" />
				<input type="hidden" name="rmv_sort_clm" id="rmv_sort_clm" value="<?php echo "0"; ?>" />
            </div>
        </div>
		<!-- Page-Title - END -->	
		
        <form class="form-horizontal" id="jvalidate" action="#" method="post" >
			<input type="hidden" name="action" id="action" value="<?php echo "purchase_listing"; ?>" />	
			<div class="row">
				<div class="col-md-12"> 	
				
					<div class="card border-primary">
						<div class="card-header border-primary">
							Search Criteria 
						</div>
						<div class="card-body">
							<div class="row col-md-12" style="padding:10px;">
							
								<div class="col-md-2">
									<?php 
									echo getSelectBoxFinancialYearlist($db, 'srch_fin_year', 'jsrequired');
									?>							
								</div>
								
								<div class="col-md-2">
									<?php 
									echo getSelectBox_companylist($db, 'srch_company', 'jsrequired');
									?>							
								</div>
								
								<div class="col-md-2">
									<?php 
									echo getSelectBox_supplierlist($db, 'srch_supplier', 'jsrequired');
									?>							
								</div>
							
								<div class="col-md-2">
									<input type="text" name="txtsrch_fmdate" id="txtsrch_fmdate" placeholder="Start Date" class="form-control" />						
								</div>
								
								<div class="col-md-2">
									<input type="text" name="txtsrch_todate" id="txtsrch_todate" placeholder="End Date" class="form-control" />						
								</div>							
									
								
							</div>
							
							<div class="row" style="padding:10px;">
							
								<div class="col-md-2">
									<select class="form-control select2" id="SearchOption" name="SearchOption">
										<option value="">Search Option</option>
										<?php
										foreach($Srch_FilterOptions as $r) {
										?>
										<option value="<?php echo $r['ID']; ?>"><?php echo $r['Name']; ?></option>
										<?php
										}
										?>	
									</select>						
								</div>					
								<div class="col-md-2">	
                                    <input id="Srchvalautocomplete" name="Srchvalautocomplete" class="form-control autocmplte_srchkeyword" type="text" placeholder="Search Keywords" />
								</div>	
								<div class="col-md-5">								
									</div>						
									<div class="col-md-1">					
										<a href="javascript:;" class="btn btn-warning"  onclick="search_result();">Search</a> 							
									</div>						
									<div class="col-md-1">					
										<a href="javascript:;" class="btn btn-info"  onclick="reset_result();">Reset</a> 							
									</div>						
							</div>
							
						</div>
					</div>										
									
				</div>
			</div>
		</form>
		
		<div class="row">
            <div class="col-sm-12">
                <div class="card-box table-responsive">                         
                    <table id="tblresult" class="table table-striped table-bordered">
                        <thead>
                            <tr>
								<th>S.No</th>
								<th>Invoice No</th>
								<th>Invoice Date</th>
								<th>Company Name</th>
								<th>Supplier</th>
                                <th>Supplier Details</th>								
								<th >Qty & SKU</th>		
								<th>Total Amt</th>
                                <th>GST / IGST</th>
                                <th>Final Amt</th>
								<th>Status</th>
								<th>Actions</th>
                            </tr>
                        </thead>                       
                    </table>
                </div>
            </div>
        </div> <!-- end row -->		

<?php include "includes/footer.php";  ?> 
	</div> <!-- container -->
</div> <!-- End wrapper -->

<?php include "includes/footer_script.php";  ?> 

	
<script type="text/javascript" src="assets/plugins/autocomplete/jquery.autocomplete.min.js"></script>

<script type="text/javascript"> 
$(document).ready(function(){
    $("#tblresult").css("width", "100%"); // Set the width of the table
    $("#tblresult").DataTable(); // Initialize DataTable
});

$(function () {
    $('#srch_fin_year').change(function () {
        var selectedOption = $(this).find(':selected');
        var startDate = selectedOption.attr('data-start-date');
        var endDate = selectedOption.attr('data-end-date');
        
        // Set the start and end date attributes for validation
        $('#txtsrch_fmdate').attr('data-start-date', startDate);
        $('#txtsrch_todate').attr('data-end-date', endDate);

        // Set the datepicker options for the from and to date fields
        $('#txtsrch_fmdate').datepicker('setStartDate', startDate);
        $('#txtsrch_fmdate').datepicker('setEndDate', endDate);
        $('#txtsrch_todate').datepicker('setStartDate', startDate);
        $('#txtsrch_todate').datepicker('setEndDate', endDate);

        // Set the selected start and end dates in the input fields
        $('#txtsrch_fmdate').val(startDate);
        $('#txtsrch_todate').val(endDate);

        console.log('Start Date:', startDate);
        console.log('End Date:', endDate);
    });

    $('#txtsrch_fmdate').datepicker({
        format: 'yyyy-mm-dd',
        // Use the data attribute for minimum date
        startDate: $('#txtsrch_fmdate').attr('data-start-date'),
        // Use the data attribute for maximum date
        endDate: $('#txtsrch_todate').attr('data-end-date'),
    }).on('changeDate', function (ev) {
        var selectedStartDate = new Date($('#txtsrch_fmdate').val());
        $('#txtsrch_todate').datepicker('setStartDate', selectedStartDate);
    });

    $('#txtsrch_todate').datepicker({
        format: 'yyyy-mm-dd',
        // Use the data attribute for minimum date
        startDate: $('#txtsrch_fmdate').attr('data-start-date'),
        // Use the data attribute for maximum date
        endDate: $('#txtsrch_todate').attr('data-end-date'),
    }).on('changeDate', function (ev) {
        var selectedEndDate = new Date($('#txtsrch_todate').val());
        $('#txtsrch_fmdate').datepicker('setEndDate', selectedEndDate);
    });

    $('#txtsrch_fmdate, #txtsrch_todate').bind('keyup keydown keypress', function (evt) {
        return false;
    });
   
   disp_result();
    // datatblCal();
});



function disp_result() {
    if ($.fn.DataTable.isDataTable('#tblresult')) {
        $('#tblresult').DataTable().destroy();
    }
    
    $('#tblresult').dataTable( {
        
        initComplete: function () {
            unloading();
            
			// table.buttons().trigger();
        },
        
        bFilter: false,
        bSort: false,
        processing: true,
        serverSide: true,
        serverMethod: 'post',
        "stateSave": true,
        "bStateSave": false,
        "language": {
            "processing": loading()
        },
        "ajax": {
            url: "listingactivity_actions.php?pageaction=" + $('#action').val() + "&srch_type=" + $('#SearchOption').val() + "&srch_keyword=" + $('#Srchvalautocomplete').val() + "&srch_finyear=" + $('#srch_fin_year').val() + "&srch_company=" + $('#srch_company').val() + "&srch_supplier=" + $('#srch_supplier').val() + "&srch_fmdate=" + $('#txtsrch_fmdate').val() + "&srch_todate=" + $('#txtsrch_todate').val(),
            type: "post",
            error: function () {
                $("#tblresult").append('<tbody class="employee-grid-error"><tr><th colspan="4">No data found in the server</th></tr></tbody>');
                unloading();
            }
        },
        "dom": '<"pull-right custom-padding"B>frtip',
        buttons: [{
            filename: 'purchase_listing' + new Date().toISOString().slice(0, 10),
            extend: 'excelHtml5',
            text: 'Download <i class="fa fa-file-excel-o green-color"></i>',
            titleAttr: 'Excel',
            exportOptions: {
                columns: [0, 1, 2, 3, 4, 5, 6, 7, 8,9,10],
                modifier: {
					order : 'index', // 'current', 'applied','index', 'original'
                    page : 'all', // 'all', 'current'
                    search : 'none' // 'none', 'applied', 'removed'
                },
            },

        }],
        columnDefs: [{
            targets: 0,
            width: 20,
        },
        {
            targets: 1,
            width: 20,
        },
        {
            targets: 2,
            width: 80,
        },
        {
            targets: 6,
            width: 100,
            render: function (data, type, row) {
            var pdt_csv = row[6];
            var pdt_amt = row[12];
                return '<span class="product-tooltip hoverToolTip" data-toggle="tooltip" data-placement="auto" onclick="get_amt()" title="' + pdt_amt + '" data-pdt-amount="' + pdt_amt + '">' + pdt_csv + '</span>';
            },
        },
    ],

    });
   
    
    // debugger

}


function clear_result() {
    // Clear the DataTable and destroy it
    var table = $('#tblresult').DataTable();
    table.clear().destroy();
    
    // Optionally, reset any filters or search inputs
    $('#SearchOption').val('');
    $('#Srchvalautocomplete').val('');
    $('#srch_fin_year').val('');
    $('#srch_company').val('');
    $('#srch_supplier').val('');
    $('#txtsrch_fmdate').val('');
    $('#txtsrch_todate').val('');


    window.location.reload();
    // Call the display result function to reload the DataTable
    disp_result();
}

function search_result(){
	disp_result();
}
function reset_result(){
	clear_result();
}

</script>	



<!-- <script>
$(function () {   		
	datatblCal();		
});
$(document).ready(function(){
  $(document).ajaxComplete(function() {                 
               
		$(".hoverToolTip").popover({ trigger: "manual" , html: true, animation:false, placement: "bottom",title: purchaseDetails})
			    .on("click", function () {
			        var _this = this;
			        $(this).popover("show");
			        /*$(".popover").on("mouseleave", function () {
			            $(_this).popover('hide');
			        });*/
			    }).on("mouseleave", function () {
			        var _this = this;
			      /*  setTimeout(function () {
			            if (!$(".popover:hover").length) {
			                $(_this).popover("hide");
			            }
			        }, 300);*/
			});				  
   }); // Add tooltip
  
$('html').on('click', function(e) {
  if (typeof $(e.target).data('original-title') == 'undefined' &&
     !$(e.target).parents().is('.popover.in')) {
    $('[data-original-title]').popover('hide');
  }
});



});

function purchaseDetails(){	
  var id = this.id;
  
  var tooltipText = "Loading";
  $.ajax({
   url: 'ajax_actions.php',
   type: 'post',
   async: false,
   data: {product_sku:id},
   data: 'action=get_product_det_by_purchase&pdt_inv_no='+id,
   success: function(response){
     tooltipText = response;

   }
  });
  return tooltipText;
}
</script>	 -->
<style type="text/css">
.popover{
    max-width:500px;
    height:250px;    
    overflow-y:auto;
}
.hoverToolTip:hover{
	cursor:pointer;
}

    .custom-padding {
        padding-bottom: 10px; 
    }
	.green-color {
        color:green;
		font-size: 18px;
    }
</style>
</body>
</html>
