<?php
session_start();
$where 					= " WHERE 1=1  ";
$next_page_condition 	= "";
$paging ="";
if($_REQUEST['start']){
	$paging .="&start=".$_REQUEST['start'];
} 

##################################  STRAT FILTER CONITIONS    ###############################

$invoice_number 	= isset($_REQUEST['invoice_number']) ? $_REQUEST['invoice_number'] : "";
if($invoice_number) {
	$invoice_number = trim($invoice_number);
    $where	.= " AND invoice_number LIKE '%$invoice_number%' ";
    $next_page_condition.="&invoice_number=$invoice_number";
}
$supplier_id 	= isset($_REQUEST['supplier_id']) ? $_REQUEST['supplier_id'] : "";
if($supplier_id) {
	$supplier_id=trim($supplier_id);
    $where	.= " AND supplier_id = '$supplier_id' ";
    $next_page_condition.="&supplier_id=$supplier_id";
}
$restricted_groups = [13, 14];
$can_view = !in_array($_SESSION['admin_group_id'], $restricted_groups);
################################# END FILTER CONDITIONS ################################

###########################################  PAGING WITH PER PAGE  #####################################
$file_name		= "index"; // this is file name which is used during paging  , included at the bottom of the page
$table_name		= "sales_invoices";
$paging_table_name	= $table_name;
$paging_query		= $where;
$join_query_for_paging = "SELECT si.*, dn.note_number FROM $table_name si LEFT JOIN delivery_notes dn ON si.delivery_note_no = dn.id $where";

//$join_query_for_paging = "SELECT supplier_management.id as main_supplier_id,$table_name.* FROM $table_name LEFT JOIN supplier_management ON $table_name.supplier_id = supplier_management.id $where ";
$page_header = "Sales Invoices";
include("paging/paging_query.inc.php");
################################## END PAGING WITH PER PAGE  ################################
$query = "SELECT si.*, dn.note_number FROM $table_name si LEFT JOIN delivery_notes dn ON si.delivery_note_no = dn.id $where ORDER BY si.id DESC LIMIT $eu, $limit";
//$query = "SELECT supplier_management.id as main_supplier_id,$table_name.* FROM $table_name LEFT JOIN supplier_management ON $table_name.supplier_id = supplier_management.id $where $orderby LIMIT $eu, $limit";

$sql=mysqli_query($conn,$query);
$result=mysqli_num_rows($sql);

$total_no_of_sales_invoice = mysqli_num_rows(mysqli_query($conn,$join_query_for_paging));
#################################   DELETE    #########################################
// when we click on delete this area of php code will execute
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete')
{
	mysqli_query($conn,"DELETE FROM $table_name WHERE id = '".$_REQUEST['id']."' ");
	
	mysqli_query($conn,"DELETE FROM sales_invoice_mapping WHERE sales_id = '".$_REQUEST['id']."' "); 
	
	$_SESSION['info_message'] = "Sales Invoice deleted successfully";
	header("location: $file_name?page=view".$next_page_condition.$paging);
	exit();
}
#################################  END DELETE    #########################################
#################################  Export CSV    #########################################
if(isset($_REQUEST['action']) && $_REQUEST['action']=='export_to_sales_invoice_csv'){
  include("export_to_sales_invoice_csv.inc.php");
} 
###################################### END CSV #############################################
?>


<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-12">
                <h1 class="m-0"><?=$page_header;?></h1>
            </div>
        </div>
        <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
</div>
<section class="content">
	<div class="container-fluid">
	<div class="row">
		<div class="col-lg-12">
		<div class="">
			<!----------------------- Message ------------------------------->
			<? if(isset($_SESSION['info_message'])){ ?>
			  <div class="alert alert-info alert-dismissable">
				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
				<? echo $_SESSION['info_message']; unset($_SESSION['info_message']);?>
			  </div>
			  <? } ?>
			<!----------------------- End Message ------------------------------->
			<div class="card">
				<div class="card-body">
				<!-- search form -->
				<?php include_once('sales_invoice_search_options.inc.php');?>
				<!-- /.search form -->
				Total No. of Sales Invoices: <?=$total_no_of_sales_invoice;?>
				<!--<div style="float:right;margin-bottom:4px;">Export sites Details &nbsp;&nbsp;<a href="index?page=view&action=export_job_details<?=$next_page_condition;?>"><i class="fa fa-download" style="font-size:20px;"></i></a></div>-->
				<div style="float:right;margin-bottom:4px;"><a href="index?page=view&action=export_to_sales_invoice_csv<?=$next_page_condition;?>">Export to CSV&nbsp;&nbsp;<i class="fa fa-download" style="font-size:20px;"></i></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
					   </div>
					<form action="index?page=add" method="post" name="form1" id="form1">
					<?php if($can_view){ ?>
					<div class="card-footer">
					   <button type="submit" name="add" class="btn btn-primary">Add Sales Invoice</button>
					</div>
					<?php } ?>
					<? if($result>0){?>
					<div class="table-responsive">
					 <table id="example1" class="table table-bordered table-striped">
						<thead>
						  <tr>
							<!--<th>#</th>-->
							<th>Invoice Number</th>
							<th class="text-center">Delivery Note Number </th>
							<th class="text-center">Customer Name </th>
							<th class="text-center">Invoice Date</th>
							<th class="text-center">Delivery Date</th>
							<th  class="text-center">Invoice PDF</th>
							<?php if($can_view){ ?>
							<th class="text-center">Edit</th>
							<th class="text-center">Delete</th>
							<?php } ?>
							<!--<th class="no-sort" style="text-align:center;">
								<div class="icheck-primary d-inline">
									<input type="checkbox" name="check_all" id="check_all">
									<label for="check_all"></label>
								</div>
							</th>-->
						  </tr>
						</thead>
						<tbody>
							<?
								while($row =mysqli_fetch_array($sql)){ 
								$row=utility::validate_crypt_data($row);
								
					
							?>
						  <tr>			
							<td ><?php echo $row["invoice_number"];?></td>
							<td class="text-center"><?php echo htmlspecialchars($row['note_number'] ?? '—'); ?></td>
							<td class="text-center"><?php echo $gsi->getCustomerById($row["customer_id"]);?></td>
							<td class="text-center"><?php echo utility::getFormatedDateReturn($row["invoice_date"]);?></td>
							<td class="text-center"><?php echo utility::getFormatedDateReturn($row["delivery_date"]);?></td>
							
							<td class="text-center">
								<?php if ($_SERVER['HTTP_HOST'] == "localhost") { ?>                            
									<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#pdfModal" data-sales-id="<?=$row['id'];?>">
										Generate PDFs
									</button>
								<?php } else { ?>
									<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#pdfModal" data-sales-id="<?=$row['id'];?>">
										Download PDFs
									</button>
								<?php } ?>
							</td>
															  
							
                            <?php if($can_view){ ?>
							<td class="text-center"><a href="index?page=add&action=edit&po_id=<?=urlencode(utility::app_crypt($row['id'],'e'));?>&id=<?=$row['id'].$next_page_condition.$paging;?>" <?=$edit_delete_display;?>> <i class="fa fa-fw fa-edit text-primary"></i> </a></td>
							<td class="text-center"><a href="index?page=view&action=delete&id=<?=$row['id'].$next_page_condition.$paging; ?>"onclick=" javascript:return confirm('Are you sure you want to delete?');" <?=$edit_delete_display;?>><i class="fa fa-fw fa-trash text-danger"></i> </a></td>
							<?php } ?>
							<!--<td align="center">
								<div class="icheck-primary d-inline">
									<input class="checkbox" type="checkbox" name="site_ids[<?=$row['id']?>]" value="<?=$row['id']?>" id="primary">
									<label for="primary"></label>
								</div>
							</td>-->
						  </tr>
							<? } ?>
							
						</tbody>
					 </table>
					 </div>
					 <? }else{ ?>
						No Sales Invoice found...
					 <? } ?>
					 <div class="box-footer clearfix">
						<!-- Paging starts here  -->
						<? 
							$next_page_condition .="&page=view";
							include("paging/paging_row.inc.php") 
						?>
						<!-- Paging ends starts here  -->
					</div>
				</div>
				<?php if($can_view){ ?>
				<div class="card-footer hide">
                   <button type="submit" name="add" class="btn btn-primary">Add Sales Invoice</button>
                </div>
				<?php } ?>
				</form>
			</div>
		</div>
		</div>
	</div>
	</div>
</section>

<!-- Modal -->
<div class="modal fade" id="pdfModal" tabindex="-1" role="dialog" aria-labelledby="pdfModalLabel" aria-hidden="true">
	<div class="modal-dialog" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="pdfModalLabel">Select PDF to Generate</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<form id="pdfForm">
					 <input type="hidden" name="sales_id" id="salesIdInput">
					<div class="form-check"> <?$default_set=1;?>
						<input class="form-check-input" type="checkbox" id="salesInvoice" name="pdfType[]" value="1"<? echo ($default_set ==1) ? 'checked':''; ?>>
						<label class="form-check-label" for="salesInvoice">&nbsp;&nbsp;Sales Invoice</label>
					</div>
					<div class="form-check">
						<input class="form-check-input" type="checkbox" id="deliveryInvoice" name="pdfType[]" value="1"<? echo ($default_set ==1) ? 'checked':''; ?>>
						<label class="form-check-label" for="deliveryInvoice">&nbsp;&nbsp;Delivery Invoice</label>
					</div>
				</form>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
				<button type="button" class="btn btn-primary" id="generatePDF">Download PDF(s)</button>
			</div>
		</div>
	</div>
</div>
<script type="text/javascript">

$(function () {
	$('#pdfModal').on('show.bs.modal', function (event) {
		const button = $(event.relatedTarget);
		const salesId = button.data('sales-id');
		const modal = $(this);
		modal.find('#salesIdInput').val(salesId);
	});

	document.getElementById('generatePDF').addEventListener('click', function () {
    const form = document.getElementById('pdfForm');
    const formData = new FormData(form);
    const salesId = formData.get('sales_id');
    const salesInvoiceChecked = document.getElementById('salesInvoice').checked;
    const deliveryInvoiceChecked = document.getElementById('deliveryInvoice').checked;

    let url = '';
	<?php if ($_SERVER['HTTP_HOST'] == "localhost") { ?> 
		if (salesInvoiceChecked && !deliveryInvoiceChecked) {
			url = `<?=$config->frontEndURL;?>/admin/sales_invoice/index?page=view_sales_invoice_pdf&sales_id=${salesId}&hide_top=1&hide_left=1`;
		} else if (!salesInvoiceChecked && deliveryInvoiceChecked) {
			url = `<?=$config->frontEndURL;?>/admin/sales_invoice/index?page=view_delivery_invoice_pdf&sales_id=${salesId}&hide_top=1&hide_left=1`;
		} else if (salesInvoiceChecked && deliveryInvoiceChecked) {
			// Both selected
			url = `<?=$config->frontEndURL;?>/admin/sales_invoice/index?page=view_delivery_and_sales_pdf&sales_id=${salesId}&hide_top=1&hide_left=1`;
		} else {
			alert('Please select at least one option.');
			return;
		}
	<?}else{?>
	 if (salesInvoiceChecked && !deliveryInvoiceChecked) {
			url = `<?=$config->frontEndURL;?>/sales_invoice_pdf.php?sales_id=${salesId}&pdf_name=sales_invoice`;
		} else if (!salesInvoiceChecked && deliveryInvoiceChecked) {
			url = `<?=$config->frontEndURL;?>/delivery_invoice_pdf.php?sales_id=${salesId}&pdf_name=delivery_invoice`;
		} else if (salesInvoiceChecked && deliveryInvoiceChecked) {
			url = `<?=$config->frontEndURL;?>/sales_and_delivery_invoice_pdf.php?sales_id=${salesId}&pdf_name=delivery_sales_invoice`;
		} else {
			alert('Please select at least one option.');
			return;
		}
	<?}?>
		window.open(url, '_blank');

		$('#pdfModal').modal('hide');
	});

	$(".close_button").click(function(){
		$(".modal_iframe").attr("src","");
		location.reload();
	});
	
	$(".add_po_document").click(function(){
		var purchase = $(this).attr("data-purchase");
		$("#myModalLabel").html("Purchase Documents  <span style='color:Tomato'>"+purchase+"</span>");
		var hide_top_left = "&hide_top=1&hide_left=1";
		var sales_invoice_id = $(this).attr("alt");	
		//alert(equipment_id);
		$('.modal-dialog').css({"max-width":"76%"});		
		$(".modal_iframe").attr("src","<?=$config->frontEndURL?>/admin/modules/fileuploads/image-files.php?sales_invoice_id="+sales_invoice_id+"&page=view&source=po"+hide_top_left);
	});
	$(".Mail_send").click(function(){
		var order_ref = $(this).attr("data-order_ref");
		$("#myModalLabel").html("Send to Supplier for <span style='color:Tomato'>"+order_ref+"</span>");
		var hide_top_left = "&hide_top=1&hide_left=1";
		var sales_invoice_id = $(this).attr("alt");
		$('.modal-dialog').css({"max-width":"80%"});
		$(".modal_iframe").addClass("jspopup").attr("src","<?=$config->frontEndURL?>/admin/sales_invoice/index?page=send_mail_to_client_for_po&sales_invoice_id="+sales_invoice_id+hide_top_left);
	});
});
</script>