<?php session_start();
include ('../inc/dbcon.php');
include ('../inc/functions.php');
if(isset($_SESSION["axeslogin"]) && $_SESSION["axeslogin"] == true){
$_SESSION['cuPages']='sel_sinvlist.php';   
$cuPage='sel_sinvlist.php';    
$aid=$_SESSION['uid'];
$brid=$_SESSION['abrid'];
$uty=$_SESSION['utype'];    
}else{
header('Location:../index.php');
exit;    
}
$mhead='sales';
$menuh='Sales';
$phead='sinvlist';
$page='Sales Invoice';
$print='print';
$dtnow = date("Y-m-d h:i:s", time());
$today = strftime("%Y-%m-%d", time());
?>
<?php
function check_desales($invno){
$flage=0;
global $con;
$sql="SELECT * FROM tbl_trarecord WHERE invno!='$invno' AND refinv='$invno'";    
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
if($query->num_rows > 0) {
$flage=1;    
}else{
$flage=0;    
}

if($flage>0){
return $flage;
exit;    
}    

$sql="SELECT * FROM tbl_pdlirecord WHERE refinv='$invno'";    
$rquery=mysqli_query($con,$sql)or die(mysqli_error($con));
if($rquery->num_rows > 0) {
$flage=1;    
}else{
$flage=0;    
}

if($flage>0){
return $flage;
exit;    
}    

$sql="SELECT * FROM tbl_traproduct WHERE invno='$invno' AND rbclno IS NOT NULL";    
$rquery=mysqli_query($con,$sql)or die(mysqli_error($con));
if($rquery->num_rows > 0) {
$flage=1;    
}else{
$flage=0;    
}

if($flage>0){
return $flage;
exit;    
}    
    
$sql="SELECT * FROM tbl_waranty WHERE refinv='$invno'";    
$rquery=mysqli_query($con,$sql)or die(mysqli_error($con));
if($rquery->num_rows > 0) {
$flage=1;    
}else{
$flage=0;    
}

if($flage>0){
return $flage;
exit;    
}    
    
$sql="SELECT * FROM tbl_sreturn WHERE refinv='$invno'";    
$rquery=mysqli_query($con,$sql)or die(mysqli_error($con));
if($rquery->num_rows > 0) {
$flage=1;    
}else{
$flage=0;    
}

return $flage;    
}

if(isset($_POST['delsel'])){
$id=$_POST['delsel'];

$sql="SELECT * FROM tbl_sales WHERE id='$id' LIMIT 1";
$dsales=mysqli_query($con,$sql) or die(mysqli_error($con));    
$dsel=mysqli_fetch_array($dsales);     

$invno=$dsel['invno'];    
    
if(check_desales($invno)){
save_msg('w','Sales Depend on others data!!!');
echo "<script>window.location='sel_sinvlist.php'</script>";
return;    
}    

$sql="SELECT * FROM tbl_serialsale WHERE invno='$invno'";
$query=mysqli_query($con,$sql)or die(mysqli_error($con));
if($query->num_rows > 0) {
while ($row=mysqli_fetch_array($query)){
$serial=$row['serial'];    
$sql="UPDATE tbl_serial SET status='0' WHERE serial='$serial'";
mysqli_query($con,$sql)or die(mysqli_error($con));    
}
$sql="DELETE FROM tbl_serialsale WHERE invno='$invno'";
mysqli_query($con,$sql)or die(mysqli_error($con));    
}    
    
$sql="DELETE FROM tbl_trarecord WHERE invno='$invno'";
mysqli_query($con,$sql)or die(mysqli_error($con));

$sql="DELETE FROM tbl_traproduct WHERE invno='$invno'";
mysqli_query($con,$sql)or die(mysqli_error($con));

$sql="DELETE FROM tbl_cheqman WHERE refinv='$invno'";
$query=mysqli_query($con,$sql)or die(mysqli_error($con));

$sql="DELETE FROM tbl_sales WHERE id='$id'";
$fdel=mysqli_query($con,$sql)or die(mysqli_error($con));    
$efid=mysqli_affected_rows($con);
if($efid>0){
$act =remove_junk(escape('Sales invoice: '.$invno));    
write_activity($aid,'SEL','Sales has been deleted',$act);        
save_msg('s','Sales Successfully Deleted!!!');
}else{
save_msg('s','Sales Fail to Delete!!!');    
}
echo "<script>window.location='sel_sinvlist.php'</script>";    
}
?>
<?php
include('../layout/head.php');
include('../layout/header.php');
include('../layout/side_nav.php');
?>
<div class="content-wrapper">
<?php include('../layout/page_head.php'); ?>
<!-- Main content -->
<section class="content">

<div class="row">
<div class="col-md-9">
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">Sales Record</h3>
</div>
<div class="box-body">
<?php echo display_msg();?>    
<div class="col-md-12 table-responsive">
<table class="table table-bordered table-striped" id="datarec">
<thead>
<tr>
<th style="width:40px; text-align:center;">SN</th>   
<th>Date</th>
<?php if($uty=='1'){ ?>
<th>Branch</th>    
<?php } ?>   
<th>Customer</th>
<th>Invoice</th>
<th>Total</th>    
<!--<th>Received</th>
<th>Due</th>-->
<th>Note</th>    
<!--<th>Status</th>-->    
<th style="width:40px; text-align:center;">Action</th>    
</tr>
</thead>    
<tbody>
   
</tbody>   
</table>
</div>
<div class="clearfix" ></div>  
<div class="row"style="margin-top: 15px" >
<div class="col-md-12 table-responsive">    
<div class="col-md-8"></div>
<div class="col-md-4 text-right" >
<a href="sel_sinvcteate.php" class="btn btn-flat bg-purple">Create Sales</a>
</div>
</div>    
</div>    
</div>
</div>
</div>
<div class="col-md-3">
<div class="row">
<div class="col-md-12">
<div class="box box-solid">
<div class="box-header">
<!-- tools box -->
<div class="pull-right box-tools">
<a class=" pull-right" data-widget="collapse" style="margin-right: 5px;">
<i class="fa fa-minus"></i></a>
</div>
<!-- /. tools -->
<i class="fa fa-filter" aria-hidden="true"></i>    
<h3 class="box-title">Date Range Filter</h3>
</div>
<!-- /.box-header -->
<div class="box-body" >

<form action="#" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="col-md-12 popup_details_div">    
<div class="row">
<div class="col-md-12">
<div class="col-md-1"></div>
<div class="col-md-10">    

<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Date From</label>
<div class="input-group date datetimepicker">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" name="tfdate" id="tfdate" value="<?php if(isset($_POST['tfdate'])){echo $_POST['tfdate']; }else{echo date('Y-m-d', strtotime('-15 days', time()));} ?>"  class="form-control" placeholder="Date From" readonly="true">
</div>
</div>        
</div>
<div class="col-md-6">
<div class="form-group" >
<label>Date To</label>
<div class="input-group date datetimepicker">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input type="text" name="ttdate" id="tdate" value="<?php if(isset($_POST['ttdate'])){echo $_POST['ttdate']; }else{echo $today;} ?>"  class="form-control" placeholder="Date To" readonly="true">
</div>    
</div>    
</div>    
</div>     
    
</div>   
<div class="col-md-1"></div>    
</div>    
</div>    
</div>
    
<div class="clearfix" ></div>
<div class="col-md-12 nopadding widgets_area"></div>    
<div class="row"style="margin-top: 15px" >
<div class="col-md-2" >
    
</div>       
<div class="col-md-10 text-right" >    
<input type="button" id="csvexp" class="btn btn-flat bg-purple btn-sm " value="Exp->CSV"/>   
</div> 
</div>     
</form>    
    
</div>
</div>
</div>

</div>    
<div class="row">
<div class="col-md-12">
<div class="box box-solid">
<div class="box-header">
<h3 class="box-title">History </h3>
</div>
<!-- /.box-header -->
<div class="box-body" >
<?php if($_SESSION['access']=='1'){echo read_activity($aid,'SEL','A');}else{echo read_activity($aid,'SEL','U');}?>
</div>
</div>
</div>
</div>
</div>
</div>    

<?php include('../layout/quick.php');?>
<div style="display: none;">
<table id="expcsv"></table>
</div>    
</section>
<!-- /.main content -->
<?php include('../layout/print.php'); ?>
<?php include('../layout/details.php'); ?>    
</div>
<?php
include('../layout/footer.php');
?>
<!-- page script -->
<script type="text/javascript">
$(document).ready(function() {
//$('#datarec').DataTable({stateSave: true});
var dataTable=$('#datarec').DataTable({
"processing": true,
"serverSide":true,
"stateSave": true,    
"aoColumns": [
    { "sWidth": "40px", "sClass": "text-center" },
    <?php if($uty=='1'){ ?>
    null,
    <?php } ?>
    null,
    null,
    null,
    null,
    null,
    { "sWidth": "120px", "sClass": "text-center" }
],    
"ajax":{
url:"sel_listdata.php",
type:"post"
}
});    
});
    
function take_action(id) {
document.getElementById(id).submit(); 
}
    
function remove_item(id) {
bootbox.confirm({
title: "Confirm",
message: "Are you sure to delete ?",
buttons: {
confirm: {
label: 'Yes',
className: 'btn-flat bg-purple'
},
cancel: {
label: 'Cancel',
className: 'btn-flat bg-gray'
}
},
callback: function (result) {
if (result == true) {
document.getElementById(id).submit();
}
}
});
}

function callPrintType(){
var ptype = $('#prtype').val();
invid = $("li.invpiv.active").attr('id');
inv = invid.split("_");

$.ajax({
url: 'sel_viewinv.php',
method: "POST",
data:{ 
print: inv[1], key: ptype 
},
beforeSend: function() {
//$("#invhold").fadeOut('slow');
},    
success: function(data){    
$('#invhold').html(data);
$("#invhold").fadeIn('slow');    
sethead();    
}
});   
}    
    
$(document).on('click','.details-invoice',function(e) {      
id_arr = $(this).attr('id');
id = id_arr.split("_");

$.ajax({
url: 'sel_viewlist.php',
method: "POST",
data:{ 
invid: id[1],cusid: id[2],type:id[3]
},
success: function(data){
$('#listitem').html(data);
pagelist();    
}
});    
    
$.ajax({
url: 'sel_viewinv.php',
method: "POST",
data:{ 
print: id[1], key: 'invonly'
},
success: function(data){
$('#invhold').html(data);
sethead();    
}
});
    
$('.right-side').toggle('slide', { direction: 'right' }, 300);    

e.preventDefault();
});

$(document).on('click', '#closepop', function() {
if($('.right-side').is(':visible')) { $('.right-side').toggle('slide', { direction: 'right' }, 300); }   
});    

$(document).on('click', '.detailsrec', function(e) { 
id_arr = $(this).attr('id');
id = id_arr.split("_");
if(id[1]==0)return;

$.ajax({
url: 'axe_details.php',
method: "POST",
data:{ 
cusdet: 1,cusid: id[1],type:id[0]
},
success: function(data){
$('#profile').html(data);    
}
});    
    
$.ajax({
url: 'axe_details.php',
method: "POST",
data:{ 
tradet: 1,cusid: id[1],type:id[0]
},
success: function(data){
$('#details').html(data);   
}
});    
    
$('.right-side-details').toggle('slide', { direction: 'right' }, 300);    
e.preventDefault();    
});
    
$(document).on('click', '#closedet', function() {
$('#profile').html('');
$('#details').html('');    
if($('.right-side-details').is(':visible')) {
$('.right-side-details').toggle('slide', { direction: 'right' }, 300);
}    
});    
    
$('#listitem').on('click','li', function(){
   $(this).addClass('active').siblings().removeClass('active');
});
    
$(document).on('click', '.invpiv', function() {
var ptype = $('#prtype').val();    
id_arr = $(this).attr('id');
id = id_arr.split("_");
var ids = id[1];
$.ajax({
url: 'sel_viewinv.php',
method: "POST",
data:{ 
print: ids, key: ptype
},
beforeSend: function() {
//$("#invhold").fadeOut('slow');
},    
success: function(data){    
$('#invhold').html(data);
$("#invhold").fadeIn('slow');    
sethead();    
}
});     
});
    
$(document).on('click', '#csvexp', function() {
var tfdate=$('#tfdate').val();
var tdate=$('#tdate').val();	
$.ajax({
url: 'sel_cart.php',
method: "POST",
data:{ 
expcsv: 1, fdate: tfdate, tdate: tdate
},
success: function(data){
$('#expcsv').html(data);
const dataTable = document.getElementById("expcsv");
const exporter = new TableCSVExporter(dataTable);
const csvOutput = exporter.convertToCSV();
const csvBlob = new Blob([csvOutput], { type: "text/csv" });
const blobUrl = URL.createObjectURL(csvBlob);
const anchorElement = document.createElement("a");

anchorElement.href = blobUrl;
anchorElement.download = "Axes_sold_invoice.csv";
anchorElement.click();

setTimeout(() => {
URL.revokeObjectURL(blobUrl);
}, 500);
}
});
$('#expcsv').html('');	
});
     
class TableCSVExporter {
constructor (table, includeHeaders = true) {
this.table = table;
this.rows = Array.from(table.querySelectorAll("tr"));

if (!includeHeaders && this.rows[0].querySelectorAll("th").length) {
this.rows.shift();
}
}

convertToCSV () {
const lines = [];
const numCols = this._findLongestRowLength();

for (const row of this.rows) {
let line = "";

for (let i = 0; i < numCols; i++) {
if (row.children[i] !== undefined) {
line += TableCSVExporter.parseCell(row.children[i]);
}

line += (i !== (numCols - 1)) ? "," : "";
}

lines.push(line);
}

return lines.join("\n");
}

_findLongestRowLength () {
return this.rows.reduce((l, row) => row.childElementCount > l ? row.childElementCount : l, 0);
}

static parseCell (tableCell) {
let parsedValue = tableCell.textContent;

// Replace all double quotes with two double quotes
parsedValue = parsedValue.replace(/"/g, `""`);

// If value contains comma, new-line or double-quote, enclose in double quotes
parsedValue = /[",\n]/.test(parsedValue) ? `"${parsedValue}"` : parsedValue;

return parsedValue;
}
}    
</script>    
<!-- /page script -->
</html>    