<?php require('includes/finance/finance_functions.php');
//////////////////////////
/// PAYMENT STATUS     ///
/// 1 - Unpaid         ///
/// 2 - Reminder       ///
/// 3 - Paid           ///
/// 4 - Refund         ///
//////////////////////////


$stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `invNo`=?")or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i',$_REQUEST['invNo']);$stmt->execute();$i=$stmt->get_result();$stmt->close();
$d=mysqli_fetch_array($i);
$address = unserialize($d['address']);
$items = unserialize($d['items']);
$totals=explode('|',$d['totals']);

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `finance_reports` WHERE `invNo`=?")or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i',$_REQUEST['invNo']);$stmt->execute();$r=$stmt->get_result();$stmt->close();
$da=mysqli_fetch_array($r);

?>

<p class="lead">Edit Invoice</p>
<form id="invoiceForm" >
<div class="row">
<div class="col-12 col-md-6">

<div class="form-group">
<div class="col-12"><label for="client">Client</label></div>
<div class="col-12"><input disabled class="text-primary" value="<?php echo getClientName($address['client_name'])?>">
<input type="hidden" name="clientnumber" value="<?php echo $address['client_name']?>"></div>
</div>

<div class="form-group">
<div class="col-12"><label for="client">Invoice Number</label></div>
<div class="col-12"><input disabled class="text-primary" value="<?php echo sprintf("%06d", $_REQUEST['invNo'])?>">
<input type="hidden" id="invNo" name="invNo" value="<?php echo $_REQUEST['invNo']?>"></div>
</div>

</div>

<div class="col-12 col-md-6">
<div class="form-group">
<div class="col-12"><label for="date">Date</label></div>
<div class="col-12"><input disabled class="text-primary" value="<?php echo date('d-m-Y',$d['date'])?>">
<input type="hidden" name="clientnumber" value="<?php echo $address['client_name']?>"></div>
</div>
</div>
</div>
<div class="clearfix"></div>
<table id="feeTable" class="invtable table table-sm"><thead>
<tr>
<th style="background-color:#2a3f54!important; color:#ffffff!important">SERVICE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">REFERENCE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">RATE</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important">QUANTITY</th>
<th style="background-color:#2a3f54!important; color:#ffffff!important"></th>
</tr></thead>
<tbody>

<?php $c=1;
foreach($items as $item){?>
<tr id="R<?php echo $c?>">
<td class="itemCol"><input type="text" class="form-control" name="itemService<?php echo $c?>" value="<?php echo $item['service']?>"></td>
<td><input type="text" class="form-control" name="itemNotes<?php echo $c?>" value="<?php echo $item['notes']?>"></td>
<td><input type="text" class="form-control priceCol" name="itemPrice<?php echo $c?>" value="<?php echo $item['rate']?>"></td>
<td><input type="text" class="form-control quanCol" name="itemQuantity<?php echo $c?>" value="<?php echo $item['quantity']?>"></td>
<td><a href="javasctipt:void(0)" class="btn btn-danger btn-sm " onclick="removeItem('R<?php echo $c?>')"><i class="fal fa-trash"></i></a></td>
</tr>

<?php $c++; }?>

</tbody>
<tfoot>
<tr><td colspan="5"><a id="addButton" href="javascript:void(0)" class="btn btn-secondary btn-sm" onClick="addItem()" ><i class="fal fa-plus"></i></a></td></tr>
<tr><td colspan="3"></td><td><div class="col-sm-12 col-md-12">
<div class="input-group" >
<span class="input-group-addon secondary" id="RunningTotal">Invoice Total <small>(ex VAT)</small></span>
<input col-md-4 col-sm-6 id="sumTotal" name="sumTotal" type="text" class="form-control" placeholder="0.00" aria-describedby="RunningTotal" readonly value="<?php echo $totals[0]?>">
</div>
<div class="input-group">
<span class="input-group-addon secondary" id="RunningVatTotal">Vat</span>
<input col-md-4 col-sm-6 id="vatTotal" name="vatTotal" type="text" class="form-control" placeholder="0.00" aria-describedby="RunningVatTotal" readonly value="<?php echo $totals[1]?>"></div>
<div class="input-group" ><button id="commitBtn" type="button" onClick="confirmBox('Invoice Actions','Are you sure this invoice is complete and ready to submit?','applyInvoice()')" class="btn btn-info">Update Invoice</button>
<button type="submit" class="btn btn-info" style="display: none">Update Invoice</button></div>
</div></td></tr>

</tfoot>
</table>


<input type="hidden" id="vatrate" name="vatrate" value="<?php echo getCompanyDetails('vatrate')?>">
<input id="itemCount" name="itemCount" type="hidden" value="<?php echo $c?>">
<input id="clientID" name="clientID" type="hidden" value="<?php echo $_REQUEST['clientnumber']?>">
<input id="FUNCTION" name="FUNCTION" type="hidden" value="updateRecord">
<input type="hidden" id="filter" name="filter">
</form>



<form id="pdfGen" action="includes/engines/invoice.php" method="post" target="_blank">
<input type="hidden" id="params" name="invNo">
<input type="hidden" id="rtype" name="rtype">
<input type="hidden" id="mode" name="loader">

</form>

<div id="qr" style="display: none" ></div>
<?php /////////////////////////////////////////////////////////////////////////////////?>
<img src="images/logo_payment.png" id="logo" style="display: none">

<script src="packages/qr/jquery-qrcode-0.14.0.min.js"></script>

<script>
function getImage(){
var icode=$('#invNo').val().replace(/^[0|\D]*/,'')
var imageData=$('#rgen').attr('src')
$.ajax({ 
type: "POST", 
url: 'functions/qr_generator.php',
dataType: 'text',
data: {
image : imageData,
FUNCTION : 'saveimage',
invoiceCode : icode
}
});

}

function applyInvoice(){
$('#invoiceForm').trigger('submit')
$('#confirmBox').modal('hide')
loader()
}


function renderQR(i){
$.post('functions/qr_generator.php',{code:'ENREP PAYMENT',invoice:'Invoice <?php echo $invoiceCode?>',amount:i},function(data){var url=$.trim(data); //debug(data);
$('#qr').qrcode({render: 'image',minVersion: 6,maxVersion: 40,ecLevel: 'H',left: 0,top: 0,size: 200,fill: '#000',background: null,text: url,radius: 0,quiet: 0,mode: 4,mSize: 0.2,mPosX: 0.5,mPosY: 0.5,label: 'daso',fontname: 'sans',fontcolor: '#000',image: $("#logo")[0]});})
setTimeout(getImage, 2000);
}
function itemCounter(){
var current=$('#itemCount').val()
var updated=parseInt(current)+1
$('#itemCount').val(updated)
return updated
}



function addItem(){
var itemData=$.trim($('#itemData').html())
showPop('New Item','includes/finance/invoice_item.php')
}

function addtoInvoice(){
var service=$('#service').val();
var notes=$('#notes').val();
var rate=$('#rate').val();
var quantity=$('#quantity').val()
var ran=itemCounter()
if($('#filter').val()==""){$('#filter').val(service)}
var val=parseFloat(rate).toFixed(2).replace(/\d(?=(?:\d{3})+\.)/g,'$&,')
$('#feeTable').append('<tr id="R'+ran+'"><td class="itemCol"><input type="text" class="form-control" name="itemService'+ran+'" value="'+service+'"></td><td><input type="text" class="form-control" name="itemNotes'+ran+'" value="'+notes+'"></td><td><input type="text" class="form-control priceCol" name="itemPrice'+ran+'" value="'+val+'"></td><td><input type="text" class="form-control quanCol" name="itemQuantity'+ran+'" value="'+quantity+'"></td><td><a href="javasctipt:void(0)" class="btn btn-danger btn-sm " onclick="removeItem(\'R'+ran+'\')"><i class="fal fa-trash"></i></a></td></tr>');
$('#qr').html('')
$(calculateSum);
$('#service').val('')
$('#notes').val('')
$('#rate').val('')
$('#quantity').val('')
response('success','Item added to Invoice successfully')
$('#popupBox').modal('hide');
}

function calculateSum(){
var sum = 0;
var vat = 0;
// iterate through each td based on class and add the values
$(".itemCol").each(function() {
var quan=$(this).closest('tr').find('.quanCol').val()
var value=$(this).closest('tr').find('.priceCol').val();
if(!isNaN(value) && value.length != 0) {
var rTotal=parseFloat(value)*quan
var vatValue =parseFloat(rTotal)*<?php echo getCompanyDetails('vatrate')?> 
sum += rTotal;
vat += vatValue;
}	
});

if(sum===0){$('.functionButtons').each(function (){$(this).attr('disabled',true)}); }
else{<?php if($bMode=="locked"){?>$('#dp').css('display','none')<?php }else{?>$('.functionButtons').each(function (){$(this).attr('disabled',false)});<?php }?> }
$('#sumTotal').val(sum.toFixed(2).replace(/\d(?=(?:\d{3})+\.)/g,'$&,'))
$('#vatTotal').val(vat.toFixed(2).replace(/\d(?=(?:\d{3})+\.)/g,'$&,'))
var total=sum+vat;
if(total===0){$('#qr').html('')}
else{
$('#qr').html('')
renderQR(total.toFixed(2))
}
}

function removeConfirm(i){
$('#confirmBox').modal('hide');
$('#'+i).fadeOut(800, function(){ 
$('#'+i).remove();
$(calculateSum);
});

}

function removeItem(i){
confirmBox("Remove Item","Are you sure you wish to this item from the invoice?","removeConfirm('"+i+"')")
};

$("#invoiceForm").submit(function(event){
event.preventDefault();
$('#loadingObject').css('display','block');
$.ajax({
url:'includes/finance/finance_functions.php',
type:'POST',
data:$('#invoiceForm').serialize(),
success:function(result){//debug(result)
if($.trim(result)=="update_success"){
response('success','Your invoice has been saved successfully');
$.post('includes/engines/invoice.php',{invNo:$('#invNo').val().replace(/^[0|\D]*/,''),rtype:'client'},function(ret){//debug(ret)
})

$.post('includes/finance/finance_functions.php',{FUNCTION:'genInvoiceCode'},function(ret){
$('.functionButtons').each(function (){$(this).attr('disabled',false)});
if($('#agent_name').val()=="" || $('#agent_name').val()=="null"){$('#invButtonAgent').attr('disabled',true)}
if($('#emailPlaceholder').val()==""){$('#mailer').css('display','none')}
else{$('#mailer').css('display','block')}
$('#invNo').val($.trim(ret))
$('#params').val($.trim(ret).replace(/^[0|\D]*/,'')-1)
$('#commitBtn').attr('onClick','').text('Invoice Saved')
$('#loadingObject').css('display','none');
})
}
if($.trim(result)=="update_success"){
setTimeout(function(){document.location.href = "index.php?t=includes/finance&p=client.php&clientnumber=<?php echo $_REQUEST['clientnumber']?>"},500);
}
}
});
});


$('#navBox').html('<li class="breadrumb-item"><a href="index.php?t=includes/finance&p=finance_invoices.php">Finance - Invoices</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadrumb-item active">Edit Invoice</li>');
</script>