<?php require('includes/finance/finance_functions.php');
$stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `invNo`='".$_REQUEST['invNo']."'")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$i=$stmt->get_result();$stmt->close();
$cd=mysqli_fetch_array($i);
$address = unserialize($cd['address']);

switch ($cd['target']){
default:break;
  case "blank":
    $brokerCom=0;
    $agentCom=0;
    $target="client";
    $showCom=0;
    $name=$address['billing_name'];
  break;
  case "client":
    $clientCall = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`='".$cd['client']."'")or die(mysqli_error($GLOBALS['con']));
    $clientCall->execute();$b=$clientCall->get_result();$clientCall->close();
    $brokerCom=0;
    $agentCom=0;
    $target="client";
    $showCom=0;
    $clientData=mysqli_fetch_array($b);
    $name=getClientDetails($cd['client']);
    $address['billing_name'] = $clientData['billing_name'];
    $address['billing1'] = $clientData['billing1'];
    $address['billing2'] = $clientData['billing2'];
    $address['billing_town'] = $clientData['billing_town'];
    $address['billing_county'] = $clientData['billing_county'];
    $address['billing_postcode'] = $clientData['billing_postcode'];
  break;

  case "broker":
    $clientCall = $GLOBALS['con']->prepare("SELECT * FROM `clientdetails` WHERE `clientnumber`='".$cd['client']."'")or die(mysqli_error($GLOBALS['con']));
    $clientCall->execute();$b=$clientCall->get_result();$clientCall->close();
    $clientData=mysqli_fetch_array($b);

    if($clientData['comType']==0){$ccom='1.'.$clientData['commission'];}
    else{$ccom=$clientData['commission'];}
   
    $brokerCall = $GLOBALS['con']->prepare("SELECT * FROM `brokers` WHERE `broker_number`='".$cd['broker']."'")or die(mysqli_error($GLOBALS['con']));
    $brokerCall->execute();$b=$brokerCall->get_result();$brokerCall->close();
    $broker=mysqli_fetch_array($b);
    $brokerCom=1;
    $agentCom=0;
    $target="broker";
    $showCom=1;
    $name=getClientDetails($cd['client']);
    $address['billing_name'] = $broker['billing_name'];
    $address['billing1'] = $broker['billing1'];
    $address['billing2'] = $broker['billing2'];
    $address['billing_town'] = $broker['billing_town'];
    $address['billing_county'] = $broker['billing_county'];
    $address['billing_postcode'] = $broker['billing_postcode'];
  break;

  case "agent":
    $agentCall = $GLOBALS['con']->prepare("SELECT * FROM `agents` WHERE `agent_number`='".$cd['agent']."'")or die(mysqli_error($GLOBALS['con']));
    $agentCall->execute();$a=$agentCall->get_result();$agentCall->close();
    $agent=mysqli_fetch_array($a);
    $brokerCom=0;
    $agentCom=1;
    $target="agent";
    $showCom=0;
    $name=getClientDetails($cd['client']);
    $address['billing_name'] = $agent['billing_name'];
    $address['billing1'] = $agent['billing1'];
    $address['billing2'] = $agent['billing2'];
    $address['billing_town'] = $agent['billing_town'];
    $address['billing_county'] = $agent['billing_county'];
    $address['billing_postcode'] = $agent['billing_postcode'];
  break;

}


$items = unserialize($cd['items']);
$totals=explode('|',$cd['totals']);
//print_r($items );
$c=0;
foreach($items as $item){
  $c++;
$rate=str_replace(',','',$item['rate']);
$net=$rate*$item['quantity'];
$comm = ($clientData['commission'] / 100) * $item['rate'];
$itemRow.='
<tr id="R'.$c.'">
<td>'.$item['service'].'<input type="hidden" name="itemService'.$c.'" value="'.$item['service'].'"></td>
<td>'.$item['notes'].'<input type="hidden" name="itemNotes'.$c.'" value="'.$item['notes'].'"></td>
<td class="priceCol">'.$item['rate'].'<input type="hidden" name="itemPrice'.$c.'" value="'.$item['rate'].'"><input class="comCol" type="hidden" name="itemCom'.$c.'" value="'.$comm.'">

</td>
<td class="quanCol">1<input type="hidden" name="itemQuantity'.$c.'" value="'.$item['quantity'].'"></td>
<td><a href="javascript:void(0)" class="btn btn-danger btn-sm" onclick="removeItem(\'R'.$c.'\')"><i class="fal fa-trash"></i></a></td>
</tr>';

}

$sub=str_replace(',','',$totals[0]);
$vat=str_replace(',','',$totals[1]);
$gtotal=$sub+$vat;

$invoiceCode=sprintf("%06d", $_REQUEST['invNo']);
$date=date('d-m-Y');
?>
<form name="invoiceForm" id="invoiceForm">
    <div class="row">

        <div class="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 $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 $name?></div>
            </div>
        </div>

    </div>

    <div class="row">
        <div class="col-12 col-md-3 ">
            <div class="card">
                <div class="card-header">Billing Information</div>
                <div class="card-body">
                    <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-9 font-weight-bold" id="billing_name"><?= $address['billing_name']?></div>
                        <input type="hidden" name="billing_name" value="<?= $address['billing_name']?>">
                    </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-9 font-weight-bold" id="billing1"><?= $address['billing1']?></div>
                        <input type="hidden" name="billing1" value="<?= $address['billing1']?>">
                    </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-9 font-weight-bold" id="billing2"><?= $address['billing2']?></div>
                        <input type="hidden" name="billing2" value="<?= $address['billing2']?>">
                    </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-9 font-weight-bold" id="billing_town"><?= $address['billing_town']?></div>
                        <input type="hidden" name="billing_town" value="<?= $address['billing_town']?>">
                    </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-9 font-weight-bold" id="billing_county"><?= $address['billing_county']?></div>
                        <input type="hidden" name="billing_county" value="<?= $address['billing_county']?>">
                    </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-9 font-weight-bold" id="billing_postcode"><?= $address['billing_postcode']?></div>
                        <input type="hidden" name="billing_postcode" value="<?= $address['billing_postcode']?>">
                    </div>
                </div>
            </div>
        </div>


        <div class="col-12 col-md-6 col-xl-3">
            <div class="card">
                <div class="card-header">Account Information</div>
                <div class="card-body">
                    <div class="form-group row">
                        <label class="col-12 col-md-4 control-label" for="contract_number">Contract Number</label>
                        <div class="col-12 col-md-8 font-weight-bold" id="contract_number"><?= $address['contract_number']?></div>
                        <input type="hidden" name="contract_number" value="<?= $address['contract_number']?>">
                    </div>
                    <?php if($target=="broker"){?>
                    <div id="brokerRow" class="form-group row">
                        <label class="col-12 col-md-4 control-label" for="brokerage">Brokerage</label>
                        <div class="col-12 col-md-8" id="brokerage"><?php echo $broker['broker_name']?></div>
                    </div>

                    <div id="comRow" class="form-group row">
                        <label class="col-12 col-md-4 control-label" for="commission">Commission</label>
                        <div class="col-12 col-md-8" id="commission"><input id="comVal" type="hidden" name="commission" value="<?php echo $cd['commission']?>"><input type="hidden" name="comType" value="0"><input type="hidden" id="vatRate"
                                   value="<?php echo $cd['vatrate']?>"></div>
                    </div>
                    <?php }?>
                    <?php if($target=="agent"){?>
                    <div id="agentRow" class="form-group row">
                        <label class="col-12 col-md-4 control-label" for="agency">Agency</label>
                        <div class="col-12 col-md-8" id="agency"><?php echo $agent['agent_name']?></div>
                    </div>
                    <?php }?>
                    <div id="dp" class="form-group row" style="display: none">
                        <label class="col-12 col-md-4 control-label" for="date_paid">Date Paid</label>
                        <div class="col-12 col-md-8 input-group"><input class="form-control datepicker" type="text" name="date_paid" id="date_paid" value="<?php if($cd['date_paid']==""){}else{ echo date('d-m-Y',$cd['date_paid']);}?>"
                                   placeholder="DD-MM-YYYY">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12 col-md-6 col-xl-6">
            <div class="card">
                <div class="card-header">Invoice Items</div>
                <div class="card-body">
                    <table id="feeTable" class="table">
                        <thead>
                            <tr>
                                <th>Service</th>
                                <th>Notes</th>
                                <th>Fee</th>
                                <th>Quantity</th>
                                <th><span class="float-right"><a id="addButton" href="javascript:void(0)" class="btn btn-secondary btn-sm" onClick="addItem()" style="display: none"><i class="fal fa-plus"></i></a></span></th>
                            </tr>

                        </thead>
                        <tbody>
                            <?php echo $itemRow?>
                        </tbody>

                    </table>

                </div>
            </div>
        </div>

    </div>
    <input id="emailPlaceholder" type="hidden" name="email" value="<?php echo $address['email']?>">
    <?php /////////////////////////////////////////////////////////////////////////////////?>
    <div class="spacer"></div>

    <div class="row">
        <div class="col-12 col-md-8 text-center ">
            <a id="invButtonProforma" class="btn btn-secondary d-none" onClick="loadInvoice('invoice','<?php echo $_REQUEST['invNo']?>')" href="javascript:void(0)">View Client Proforma</a>
            <a id="invButtonClient" class="btn btn-secondary d-none" onClick="loadInvoice('invoice','<?php echo $_REQUEST['invNo']?>')" href="javascript:void(0)">View Client Invoice</a>
            <a id="invButtonBroker" class="btn btn-secondary d-none" onClick="loadInvoice('broker','<?php echo $_REQUEST['invNo']?>')" href="javascript:void(0)">View Broker Invoice</a>
            <a id="invButtonAgent" class="btn btn-secondary d-none" onClick="loadInvoice('agent','<?php echo $_REQUEST['invNo']?>')" href="javascript:void(0)">View Agent Invoice</a>
            <a id="remitButton" class="btn btn-secondary d-none" onClick="loadInvoice('remit','<?php echo $_REQUEST['invNo']?>')" href="javascript:void(0)">View Remittance Advice</a>
            <a id="remindButton" class="btn btn-secondary d-none" onClick="loadInvoice('remind','<?php echo $_REQUEST['invNo']?>')" href="javascript:void(0)">View Reminder</a>

            <a id="emProforma" class="btn btn-secondary emailButton d-none" href="javascript:void(0)" data-values="proforma" data-href="includes/master/financeMailer.php" data-toggle="tooltip" data-placement="top"
               data-original-title="Email Proforma"><i class="fal fa-envelope"></i> eMail Client Proforma</a>
            <a id="emClient" class="btn btn-secondary emailButton d-none" href="javascript:void(0)" data-values="invoice" data-href="includes/master/financeMailer.php" data-toggle="tooltip" data-placement="top"
               data-original-title="Email Client"><i class="fal fa-envelope"></i> eMail Client Invoice</a>
            <a id="emBroker" class="btn btn-secondary emailButton d-none" href="javascript:void(0)" data-values="broker" data-href="includes/master/financeMailer.php" data-toggle="tooltip" data-placement="top"
               data-original-title="Email Broker"><i class="fal fa-envelope"></i> eMail Broker Invoice</a>
            <a id="emAgent" class="btn btn-secondary emailButton d-none" href="javascript:void(0)" data-values="agent" data-href="includes/master/financeMailer.php" data-toggle="tooltip" data-placement="top"
               data-original-title="Email Agent"> <i class="fal fa-envelope"></i> eMail Agent Invoice</a>
            <a id="emRemit" class="btn btn-secondary emailButton d-none" href="javascript:void(0)" data-values="remit" data-href="includes/master/financeMailer.php" data-toggle="tooltip" data-placement="top"
               data-original-title="Email Remittance"> <i class="fal fa-envelope"></i> eMail Remittance Advice</a>
            <a id="emReminder" class="btn btn-secondary emailButton d-none" href="javascript:void(0)" data-values="remind" data-href="includes/master/financeMailer.php" data-toggle="tooltip" data-placement="top"
               data-original-title="Email Reminder"> <i class="fal fa-envelope"></i> eMail Reminder</a>

        </div>

        <div class="col-12 col-md-4 float-right">
            <?php if($showCom==1){?>
            <div id="commissionGroup" class="mb-2">
                <div class="input-group row"><span class="input-group-addon secondary" style="width:180px" id="comAmount">Commission Amount</small></span><input col-md-4 col-sm-6 id="comTotal" name="comTotal" type="text"
                           class="form-control" placeholder="0.00" aria-describedby="comAmount" readonly value="<?php echo $cd['commission']?>"></div>
            </div>
            <?php }?>
            <div class="input-group">
                <span class="input-group-addon col-md-4 secondary" id="RunningTotal">Invoice Total <small>(ex VAT)</small></span>
                <input 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 col-md-4 secondary" id="RunningVatTotal">Vat</span>
                <input 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 type="submit" class="btn btn-info" style="display: none">Commit Invoice</button>
            </div>
        </div>
    </div>
    </div>


    <input id="itemCount" name="itemCount" type="hidden" value="<?php echo $c?>">
    <input id="clientID" name="clientID" type="hidden" value="">
    <input id="agentID" name="agentID" type="hidden" value="<?php echo $agent['agent_number']?>">
    <input id="brokerID" name="brokerID" type="hidden" value="<?php echo $broker['broker_number']?>">
    <input id="FUNCTION" name="FUNCTION" type="hidden" value="updateRecord">
    <input type="hidden" id="filter" name="filter">
    <input type="hidden" id="brokerCom" name="brokerCom" value="<?php echo $brokerCom?>">
    <input type="hidden" id="agentCom" name="agentCom" value="<?php echo $agentCom?>">

    <input type="hidden" id="renewal_notice" name="renewal_notice" value="<?php echo $target?>">
    <input type="hidden" id="renewal_attach_schedule" name="renewal_attach_schedule">
    <input type="hidden" id="renewal_attach_plant" name="renewal_attach_plant">
    <input type="hidden" id="renewal_attach_inspection" name="renewal_attach_inspection">
    <input type="hidden" id="target" name="target">
</form>

<form id="pdfGen" action="includes/engines/invoice.php" method="post" target="_blank">
    <input type="hidden" id="params" name="invNo" value="<?php echo $_REQUEST['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">
<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>


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 applyInvoice() {
    $('#invoiceForm').trigger('submit')
    $('#confirmBox').modal('hide')
}

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

}

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

$('#calandarToday').click(function() {
    $('#date').val('<?php echo date('d-m-Y')?>')
})

function loadInvoice(type) {
    $('#rtype').val(type)
    //$('#pdfGen').submit()
    window.open('invoices/<?php echo $_REQUEST['invNo']?>_' + type + '.pdf');
}

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 rcom = $('#rcom').val();
    var quantity = $('#quantity').val()

    if (rate == '') {
        response('danger', 'You must add a value and description')
    } else {
        var ran = itemCounter()
        if ($('#rcom').is(":checked")) {
            var comm = sortVat('in', rate)
        } else {
            var comm = '0.00'
        }
        if ($('#filter').val() == "") {
            $('#filter').val(service)
        }
        var val = parseFloat(rate).toFixed(2).replace(/\d(?=(?:\d{3})+\.)/g, '$&,')
        $('#feeTable').append('<tr id="R' + ran + '"><td>' + service + '<input type="hidden" name="itemService' + ran + '" value="' + service + '"></td><td>' + notes + '<input type="hidden" name="itemNotes' + ran + '" value="' + notes +
            '"></td><td class="priceCol">' + val + '<input type="hidden" name="itemPrice' + ran + '" value="' + val + '"><input class="comCol" type="hidden" name="itemCom' + ran + '" value="' + comm + '"></td><td class="quanCol">' +
            quantity + '<input type="hidden" name="itemQuantity' + ran + '" value="' + quantity + '"></td><td><a href="javascript: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 sortVat(m, r) {
    var comm = ''
    var vat = $('#vatRate').val()
    var commission = $('#comVal').val()
    commission = parseInt(commission)
    // alert(commission)
    if (m == "in") {
        var v = '1.' + commission;
        var rem = r / v
        comm = r - rem;
        //alert(v)
        //alert(rem)
        var vElim = comm * vat
        comm = comm + vElim
        comm = comm.toFixed(2)
        return comm;
    }
    if (m == "out") {
        var v = '0.' + commission;
        var rem = r / v
        comm = r - rem;
        var vElim = comm * vat
        comm = comm + vElim
        comm = comm.toFixed(2)
        return comm;
    }
}

function calculateSum() {
    var sum = 0;
    var vat = 0;
    var csn = 0;
    // iterate through each td based on class and add the values
    $(".priceCol").each(function() {
        var quan = $(this).closest('tr').find('.quanCol').text()
        var com = $(this).closest('tr').find('.comCol').val()
        var value = $(this).text().replace(/,/g, '');
        if (!isNaN(value) && value.length != 0) {
            var rTotal = parseFloat(value) * quan
            var vatValue = parseFloat(rTotal) * <?php echo getCompanyDetails('vatrate')?>;
            sum += rTotal;
            vat += vatValue;
        }
        if ($('#comVal').val() != '') {
            var comTotal = parseFloat(com) * quan
            csn += comTotal;
        }
        $('#commitBtn').css('display', 'block')
    });


    $('#sumTotal').val(sum.toFixed(2).replace(/\d(?=(?:\d{3})+\.)/g, '$&,'))
    $('#vatTotal').val(vat.toFixed(2).replace(/\d(?=(?:\d{3})+\.)/g, '$&,'))
    $('#comTotal').val(csn.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();
    var systemMode = $('#renewal_notice').val();

    $('#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 updated successfully');
                $.post('includes/engines/invoice.php', {
                    invNo: '<?php echo $_REQUEST['invNo']?>',
                    rtype: 'client',
                    brokerCom: $('#brokerCom').val(),
                    agentCom: $('#agentCom').val()
                }, function(gen) {
                    //debug(gen)
                    location.href = "index.php?t=includes/finance&p=finance_unpaid.php";
                })


            }

        }
    });
});


$(document).ready(function() {
    var id = '<?php echo $cd['client']?>'
    $.post('includes/finance/finance_functions.php', {
        FUNCTION: 'getClientRecords',
        clientnumber: id
    }, function(ret) { //debug(ret)
        if ($.trim(ret) !== "error") { //debug(ret)
            //alert('<?=$cd['target']?>')
            r = JSON.parse(ret);
            var notice = '<?php echo $cd['target']?>';
            switch (notice) {
                case "blank":
                    rn = 'blank';
                    $('#emailPlaceholder').val(r.billing_email);
                    $('#emailContactPlaceholder').val(r.billing_name);
                    $('#target').val('blank');
                    break;
                case "client":
                    rn = 'client';
                    $('#emailPlaceholder').val(r.billing_email);
                    $('#emailContactPlaceholder').val(r.billing_name);
                    $('#target').val('client');
                    break;
                case "agent":
                    rn = 'agent';
                    $('#agentID').val(r.agent_number);
                    $('#emailPlaceholder').val(r.agent_billing_email);
                    $('#emailContactPlaceholder').val(r.agent_billing_name);
                    $('#target').val('agent');
                    $('#agentCom').val('1');
                    $('#brokerCom').val('0');
                    $("#agency").html(r.agent_name + '<input type="hidden" id="agent_name" name="agent_name" value="' + r.agent_name + '">');
                    $("#brokerRow").css('display', 'none');
                    $("#comRow").css('display', 'none');
                    break;
                case "broker":
                    rn = 'broker';
                    $('#brokerID').val(r.broker_number);
                    $('#emailPlaceholder').val(r.broker_billing_email);
                    $('#emailContactPlaceholder').val(r.broker_billing_name);
                    $('#target').val('broker');
                    $('#brokerCom').val('1');
                    $('#agentCom').val('0');
                    $("#brokerage").html(r.broker_name + '<input type="hidden" id="broker_name" name="broker_name" value="' + r.broker_name + '">');
                    $("#agentRow").css('display', 'none');
                    break;
            }



            if (r.comType == 0) {
                $("#commission").html(r.commission + '%<input id="comVal" type="hidden" name="commission" value="' + r.commission + '"><input type="hidden" name="comType" value="' + r.comType +
                    '"><input type="hidden" id="vatRate" value="' + r.vat_rate + '">')
            }
            if (r.comType == 1) {
                $("#commission").html('&pound;' + parseFloat(r.commission).toFixed(2) + '<input id="comVal" type="hidden" name="commission" value="' + r.commission + '"><input type="hidden" name="comType" value="' + r
                    .comType + '"><input type="hidden" id="vatRate" value="' + r.vat_rate + '">')
            }
            $("#date_paid").val(r[10])
            $("#invButtonProforma").attr("onclick", "loadInvoice('proforma','" + id + "')")
            $("#invButtonClient").attr("onclick", "loadInvoice('invoice','" + id + "')")
            $("#invButtonBroker").attr("onclick", "loadInvoice('broker','" + id + "')")
            $("#invButtonAgent").attr("onclick", "loadInvoice('agent','" + id + "')")
            $("#remitButton").attr("onclick", "loadInvoice('remit','" + id + "')")
            $("#remindButton").attr("onclick", "loadInvoice('remind','" + id + "')")
            $('#commitBtn').attr('onClick', 'confirmBox(\'Invoice Actions\',\'Are you sure this invoice is complete and ready to submit?\',\'applyInvoice()\')').text('Commit Invoice')
            $("#mailer").css('display', 'none')
            if (r.pri_contact_email == "" || r.pri_contact_email == "null") {} else {
                var icode = $('#invNo').val().replace(/^[0|\D]*/, '')

                $(".emailButton").each(function() {
                    var type = $(this).data('values')
                    $(this).attr('data-values', '')
                    switch (r.invoice_notice) {
                        case "0":
                            rn = 'client';
                            var string = id + "|" + r.billing_name + "|" + r.billing_email + "|<?php echo getCompanyDetails('name_short')?> Invoice |Your invoice number " + $('#invNo').val() + "|invoices|" + icode +
                                "_" + type + ".pdf";
                            break;
                        case "1":
                            rn = 'agent';
                            var string = id + "|" + r.agent_billing_name + "|" + r.agent_billing_email + "|<?php echo getCompanyDetails('name_short')?> Invoice |Your invoice number " + $('#invNo').val() +
                                "|invoices|" + icode + "_" + type + ".pdf|" + r.agent_email + "|" + icode;
                            break;
                        case "2":
                            rn = 'broker';
                            var string = id + "|" + r.broker_billing_name + "|" + r.broker_billing_email + "|<?php echo getCompanyDetails('name_short')?> Invoice |Your invoice number " + $('#invNo').val() +
                                "|invoices|" + icode + "_" + type + ".zip";
                            break;
                            break;
                    }

                    $(this).attr('data-string', string)
                })
            }

            $("#optionButtons").css('display', 'block')
            $("#addButton").css('display', 'block')
            $('#clientID').val(id)
            $('#agentID').val(r.agent_number)
            $('#brokerID').val(r.broker_number)

        }
    })
});

$('.emailButton').click(function() {
    $('#popupBox .modal-body').html('');
    var target = $(this).data('href');
    var string = $(this).data('string');
    var dest = encodeURI(target + "?mode=popup&data=" + string)
    $('#popupBox').modal('show');
    $('#popupBox .modal-body').load(dest);
})

calculateSum();

$(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">Update Invoice</button>')
})

</script>
<div id="result"></div>

<script>
$('#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"><a href="index.php?t=includes/finance&p=finance_unpaid.php">Outstanding 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>