<?php 
//////////////////////////
/// PAYMENT STATUS     ///
/// 1 - Unpaid         ///
/// 2 - Reminder       ///
/// 3 - Paid           ///
/// 4 - Refund         ///
//////////////////////////
function listClient($n){

$stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1'  ORDER BY `clientname` ASC")or die(mysqli_error("listClient B: ".$GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();	

$ret='<select class="form-control form-control-sm autocomplete" id="'.$n.'" name="'.$n.'" data-placeholder="Select Client (optional)"><option value="">Select Client (optional)</option>'; 
while($pd=mysqli_fetch_array($cc)){
$ret.='<option value="'.$pd['clientnumber'].'" '.$s.'>'.$pd['clientname'].'</option>';//.PHP_EOL;
}
$ret.='</select>';
return($ret.$error);
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` ORDER BY abs(invNo) DESC LIMIT 1")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$i=$stmt->get_result();$stmt->close();
$d=mysqli_fetch_array($i);

$invoiceCode=$d['invNo']+1;
?>

<h2 class="lead mt-n5">Blank Invoice</h2>
<form id="invoiceForm">
   <div class="row">
      <div class="col-12 col-md-4">
         <div class="form-group row">
         <div class="col-md-4"><label class="lead control-label " for="invNo">Invoice Number</label></div>
         <div class="col-md-6 input-group"><input class="form-control" type="text" name="invNo" id="invNo" value="<?php echo sprintf("%06d", $invoiceCode)?>" readonly/></div>
         </div>
      </div>

      <div class="col-12 col-md-4">
         <div class="row">
            <div class="col-md-3"><label class="lead control-label" for="date">Invoice date</label></div>
            <div class="col-md-6">
            <div class="input-group mb-3">  
            <input type="text" class="form-control datepicker" type="text" name="date" id="date" value="<?php echo $date?>" placeholder="DD-MM-YYYY" aria-label="DD-MM-YYYY"
            aria-describedby="button-addon1">
            <div class="input-group-append">
               <button class="btn btn-md btn-info border m-0 px-3 py-2 z-depth-0 waves-effect" type="button" id="button-addon1"><i class="fal fa-calendar"></i></button>
            </div>
            </div>
            </div>
         </div>
      </div>

      <div class="col-12 col-md-4">
         <div class="form-group row">
         <div class="col-md-3"><label class="lead control-label" for="number">Client</label></div>
         <div class="col-md-6 input-group"><?php echo listClient('clientnumber')?></div>
         </div>
      </div>
   </div>

   <div class="row">
      <div class="col-12 col-md-4">
         <div class="form-group row">
         <label class="col-12 col-md-3 control-label" for="billing_name">Name</label>
         <div class="col-12 col-md-8 font-weight-bold" id="billing_name"><input type="text" class="form-control" name="billing_name" value=""></div>
         </div>
         <div class="form-group row">
         <label class="col-12 col-md-3 control-label" for="billing1">Billing1</label>
         <div class="col-12 col-md-8 font-weight-bold" id="billing1"><input type="text" class="form-control" name="billing1" value=""></div>
         </div>
         <div class="form-group row">
         <label class="col-12 col-md-3 control-label" for="billing2">Billing2</label>
         <div class="col-12 col-md-8 font-weight-bold" id="billing2"><input type="text" class="form-control" name="billing2" value=""></div>
         </div>
         <div class="form-group row">
         <label class="col-12 col-md-3 control-label" for="billing_town">Town</label>
         <div class="col-12 col-md-8 font-weight-bold" id="billing_town"><input type="text" class="form-control" name="billing_town" value=""></div>
         </div>
         <div class="form-group row">
         <label class="col-12 col-md-3 control-label" for="billing_county">County</label>
         <div class="col-12 col-md-8 font-weight-bold" id="billing_county"><input type="text" class="form-control" name="billing_county" value=""></div>
         </div>
         <div class="form-group row">
         <label class="col-12 col-md-3 control-label" for="billing_postcode">Postcode</label>
         <div class="col-12 col-md-4 font-weight-bold" id="billing_postcode"><input type="text" class="form-control" name="billing_postcode" value=""></div>
         </div>
         <div class="form-group row">
         <label class="col-12 col-md-3 control-label" for="email">Contact Email <small>(For sending invoice)</small></label>
         <div class="col-12 col-md-8 font-weight-bold" id="email"><input type="text" class="form-control" name="email" value=""></div>
         </div>
      </div>

      <div class="col-12 col-md-8">

         <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" class="text-center"><a id="addButton" href="javascript:void(0)" class="btn btn-secondary btn-sm remove" onClick="addItem()" ><i class="fal fa-plus"></i> Add item</a></th>
               </tr>
            </thead>

            <tbody>
            </tbody>
            </table>
   </div>   
</div> 

<div class="row">
   <div class="col-12 col-md-6">
      <div id="qr" style="display: none" ></div>
   </div>
   <div class="col-12 col-md-6">
      <table id="feeTable" class="totalTable table table-sm">
         <tr>
            <td class="text-right">
               <div class="float-right mt-3">
               <div class="input-group mb-2">
               <div class="input-group-prepend" style="width:180px">         
               <span class="input-group-text bg-white" id="RunningTotal" style="width:180px">Invoice Total <small>(ex VAT)</small></span></div>
                        <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">
                     <div class="input-group-prepend" style="width:180px">
                        <span class="input-group-text bg-white" id="RunningVatTotal" style="width:180px">Vat</span></div>
                        <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="col-12" >
                        <button id="btn_recalc" type="button" class="btn btn-info float-right mr-n2">Update Totals</button>
                        <button id="btn_create" type="submit" style="display: none">Update Invoice</button>
                     </div>

               </div>
            </td>
         </tr>
      </table>
   </div>
</div>

<input type="hidden" id="vatrate" name="vatrate" value="<?php echo getCompanyDetails('vatrate')?>">
<input id="itemCount" name="itemCount" type="text" value="0">
<input id="clientID" name="clientID" type="hidden" value="">
<input id="FUNCTION" name="FUNCTION" type="hidden" value="genRecord">
<input type="hidden" id="filter" name="filter" value="blank">
<input type="hidden" id="target" name="target" value="blank">
</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>


<?php /////////////////////////////////////////////////////////////////////////////////?>
<img src="images/logo_payment.png" id="logo" style="display: none">
<div id="loadingObject" style="position: fixed; top:50%; width:100%; display:none"><h1 class="text-center"><i class="fad fa-file-invoice fa-spin fa-3x fa-fw" style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Generating Invoice <br><small>Please wait</small><span class="sr-only">generating...</span></h1></div>
<script src="packages/qr/jquery-qrcode-0.14.0.min.js"></script>

<script>
$('#btn_recalc').click(function(){calculateSum()})


$("#clientnumber").change(function() {
var id=$(this).val();
$.post('includes/finance/finance_functions.php',{FUNCTION:'getClientRecords',clientnumber:id},function(ret){
if($.trim(ret)!=="error"){
r=JSON.parse(ret);
$("#clientID").val(id)
$("#client_name").text(r.client_name)
$("#client_name").removeClass('text-danger').addClass('text-info-title')
$("#billing_name").html(r.billing_name+'<input type="hidden" name="billing_name" value="'+r.billing_name+'">')
$("#billing1").html(r.billing1+'<input type="hidden" name="billing1" value="'+r.billing1+'">')
$("#billing2").html(r.billing2+'<input type="hidden" name="billing2" value="'+r.billing2+'">')
$("#billing3").html(r.billing3+'<input type="hidden" name="billing3" value="'+r.billing3+'">')
$("#billing_town").html(r.billing_town+'<input type="hidden" name="billing_town" value="'+r.billing_town+'">')
$("#billing_county").html(r.billing_county+'<input type="hidden" name="billing_county" value="'+r.billing_county+'">')
$("#billing_postcode").html(r.billing_postcode+'<input type="hidden" name="billing_postcode" value="'+r.billing_postcode+'">')
}
})
})


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')
}


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 class="text-center"><a href="javasctipt:void(0)" class="btn btn-outline-danger py-2" 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();
   if($('#date').val()==''){
      response('warning','Please set a date');
   }
   else{
   $('#loadingObject').css('display','block');
      $.ajax({
         url:'includes/finance/finance_functions.php',
         type:'POST',
         data:$('#invoiceForm').serialize(),
         success:function(result){
         //debug(result)
            if($.trim(result)=="insert_success"){
               response('success','Your invoice has been saved successfully');
               $.post('includes/engines/invoice.php',{invNo:$('#invNo').val().replace(/^[0|\D]*/,''),rtype:'blank',brokerCom:'0',agentCom:'0'},function(ret){
               //debug(ret)
               $.post('includes/finance/finance_functions.php',{FUNCTION:'genInvoiceCode'},function(ret){
               $('#invNo').val($.trim(ret))
               })
               })
            }
            if($.trim(result)=="insert_success"){
               document.location.href = "index.php?t=includes/finance&p=finance_unpaid.php"
            }
         }
      });
   }
});


$('#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">Blank Invoice</li>')

$( document ).ready(function() {
$('#footerControls').html('<button id="commitBtn" type="button" onClick="confirmBox(\'Invoice Actions\',\'Are you sure this invoice is complete and ready to submit?\',\'applyInvoice()\')" class="btn btn-secondary">Create Invoice</button>')
})
</script>