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


$stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices_temp`  ORDER BY abs(invno) DESC")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$i=$stmt->get_result();$stmt->close();
$check=mysqli_num_rows($i);
while($id=mysqli_fetch_array($i)){$data[]=$id;}
?>

<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 active">Pending renewal invoices</li>'
)
</script>
<div id="invoiceData" class="mt-0 mt-md-n5">

    <p class="blockquote reportHeader"><span class="float-right remove"><a class="btn btn-secondary" href="index.php?t=includes/finance&p=invoicePaid_reports.php"><i class="fad fa-file-invoice"></i> View Reports </a></span>All paid invoices
        listed by invoice number<br><small class="remove">To filter the results, use the search function</small>

    </p>
    <?php if($check==0){?>

    <h3 class="lead text-center text-warning">There are no items to display</h3>
    <?php }
else{?>
    <table id="expenseTable" class="table table-striped table-sm responsive" width="100%">
        <thead>
            <tr>
                <th>Invoice Number</th>
                <th>Client</th>
                <th>Agent</th>
                <th>Contract Number</th>
                <th>Amount</th>
                <th>Date Generated</th>
                <th>Renewal Date</th>
                <th class="noExport noprint"></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($data as $id){
                
    $address = unserialize($id['address']);
    $items = unserialize($id['items']);
    $totals=explode('|',$id['totals']);

    $sub=str_replace(',','',$totals[0]);
    $vat=str_replace(',','',$totals[1]);
    $gtotal=$sub+$vat;
    $invno="";
    $invno=sprintf("%06d", $id['invNo']);

    $stmt = $GLOBALS['con']->prepare("SELECT `renewal_date` FROM `clientdetails` WHERE `clientnumber`='".$address['client_name']."'")or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();$i=$stmt->get_result();$stmt->close();
    $cn=mysqli_fetch_array($i);
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `renewals` WHERE `renewalNumber`='".$id['invNo']."'")or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();$i=$stmt->get_result();$stmt->close();
    $rn=mysqli_fetch_array($i);
?>
            <tr id="R<?= $invno?>">
                <td><?= $invno?></td>
                <td><?= getClientName($address['client_name'])?></td>
                <td><?= $address['agent_name']?></td>
                <td><?= $address['contract_number']?></td>
                <td>£<?= number_format($gtotal,2)?></td>
                <td><?= date('d-m-Y',$rn['date'])?></td>
                <td>
                    <?php if($id['status']==8){echo '<span class="text-success">RENEWED</span> ';}else{echo date('d-m-Y',$cn['renewal_date']);}?>
                </td>
                <div class="noprint">
                    <td class="noprint text-right">

                        <?php if($id['status']==8){?>
                        <a href="javascript:void(0)" class="sentButton btn btn-secondary btn-sm m-0 px-2 py-2 mr-2 waves-effect" data-toggle="tooltip" data-placement="top"
                           data-original-title="Send Invoice" data-id="<?= $id['invNo']?>"><i class="fad fa-file-arrow-up"></i> Issue invoice</a>
                        <?php }?>


                        <a href="index.php?t=includes/finance&p=finance_preview.php&invNo=<?= $id['invNo']?>&type=paid" class="btn btn-secondary btn-sm m-0 px-2 py-2 mr-2 waves-effect" data-toggle="tooltip" data-placement="top"
                           data-original-title="View Invoice"><i class="fad fa-eye"></i></a>

                        <button type="button" id="removeButton" class="btn btn-outline-danger btn-sm  m-0 px-2 py-2 mr-2 waves-effect removeButton functionButtons noprint" data-toggle="tooltip" data-placement="top"
                                data-original-title="Void Invoice" data-values="<?= $id['invNo']?>|£<?= number_format($gtotal,2)?>"><i class="fad fa-ban"></i></button>
                    </td>
                </div>
            </tr>

            <?php 
$mTotal=$mTotal+$gtotal;
}?>
        </tbody>

    </table>




    <div id="genRow" class="col-md-12 text-center remove">
        <button id="expenseReport" type="button" class="btn btn-secondary"><i class="fad fa-file-chart-line"></i> GENERATE REPORT</button>
    </div>
</div>

<div id="exportDiv" style="display: none">
    <div id="exportTitle">Invoices Paid - <small>Generated <?= date('d-m-Y')?></div>
    <table id="exportTable" class="table table-striped table-sm responsive" width="100%">
        <thead>
            <tr>
                <th>Invoice Number</th>
                <th>Client</th>
                <th>Agent</th>
                <th>Contract Number</th>
                <th>Amount</th>
                <th>Date of Invoice</th>
                <th>Date Paid</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($data as $id){
$address = unserialize($id['address']);
$items = unserialize($id['items']);
$totals=explode('|',$id['totals']);

$sub=str_replace(',','',$totals[0]);
$vat=str_replace(',','',$totals[1]);
$gtotal=$sub+$vat;
$invno="";
$invno=sprintf("%06d", $id['invNo']);
?>
            <tr id="R<?= $invno?>">
                <td><?= $invno?></td>
                <td><?= getClientName($address['client_name'])?></td>
                <td><?= $address['agent_name']?></td>
                <td><?= $address['contract_number']?></td>
                <td>£<?= number_format($gtotal,2)?></td>
                <td><?= date('d-m-Y',$id['date'])?></td>
                <td><?= date('d-m-Y',$id['date_paid'])?></td>
            </tr>
            <?php }?>
        </tbody>
    </table>
</div>


<?php
$table="expenseTable";
require('includes/single_table.engine');
?>

<div class="spacer"></div>
<div class="alert alert-info float-right lead">Total Paid:&nbsp;<span class="float-right"> £<?= number_format($mTotal,2)?></span></div>
<div id="loading"></div>
<?php }?>

<script>
function loadInvoice(type, inv) {
    window.open('invoices/' + inv + '_' + type + '.pdf');
}

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



$('#expenseTable').on('click', '.paidButton', function() {
    var str = $(this).data('values');
    var d = str.split("|");
    confirmBox('Confirm Payment', 'Are you sure this invoice for <b>' + d[1] + '</b> has been paid?', 'setPaid(\'' + d[0] + '\')')
})



$('#expenseTable').on('click', '.removeButton', function() {
    var str = $(this).data('values');
    var d = str.split("|");
    confirmBox('Void Invoice', 'Are you sure this invoice is to be voided?', 'setArchive(\'' + d[0] + '\')')
})

function setPaid(i) {
    $.post('includes/finance/finance_functions.php', {
        FUNCTION: 'setPaid',
        inv: i
    }, function(data) {
        if ($.trim(data) == "success") {
            var inv = pad(i, 6);
            $('#R' + inv).css({
                'background-color': '#82e7d2',
                'border': '1px solid #169f85'
            });
            response('success', 'The invoice has been set to Paid')
            $('#confirmBox').modal('hide')
            setTimeout(function() {
                $('#R' + inv).fadeOut();
            }, 3000);
        }
    })
}

function setArchive(i) {
    $.post('includes/finance/finance_functions.php', {
        FUNCTION: 'setArchive',
        inv: i
    }, function(data) {
        if ($.trim(data) == "success") {
            var inv = pad(i, 6);
            $('#R' + inv).css({
                'background-color': '#82e7d2',
                'border': '1px solid #169f85'
            });
            response('success', 'The invoice has been voided')
            $('#confirmBox').modal('hide')
            setTimeout(function() {
                $('#R' + inv).fadeOut();
            }, 3000);
        }
    })
}

$('#expenseReport').click(function() {
    var start = $('#sdate').val()
    var end = $('#edate').val()
    data = $('#exportDiv').html()
    $.post('includes/engines/report.php', {
        'clientnumber': '000',
        type: 'invoicesPaid_generated_<?= date('d-m-Y')?>',
        content: data,
        format: 'L'
    }, function(ret) { //debug(ret)
        $('#genRow').html('<a href="output/reps/000_invoicesPaid_generated_<?= date('d-m-Y')?>.pdf" target="blank" class="btn btn-info"><i class="fad fa-file-pdf"></i> VIEW REPORT</a>')
    })

})

$(document).on('click', '.sentButton', function() {
    var id = $(this).data('id');
    var target = $(this).data('target');
    confirmBox('Send Invoice',
        '<div style="position:relative">' +

        '<div id="loadingObject2" style="position: absolute; top:50%; width:100%; z-index:9999; 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 Renewal documents <br><small>Please wait</small><span class="sr-only">generating...</span></h1></div>' +

        '<div class="row mb-5">' +
        '<div class="col-12"><p>Are you sure you wish to send this invoice?</p></div>' +
        '</div>' +

        '</div>',
        'invocieConfirm(\'' + id + '\',\'' + target + '\')');

    $(".datepicker").pickadate({
        format: "dd-mm-yyyy",
        formatSubmit: "dd-mm-yyyy",
        selectMonths: true,
        max: new Date(),
    });
})

function invocieConfirm(id, target) {
    $('#loadingObject2').css('display', 'block');
    $.post('includes/finance/finance_functions.php', {
        FUNCTION: 'sendInvoice',
        id: id
    }, function(ret) {
        var data = $.parseJSON(ret);
        if (data.target === "broker") {
            var brokercom = 1
        } else {
            var brokercom = 0
        };
        if (data.target === "agent") {
            var agentcom = 1
        } else {
            var agentcom = 0
        };

        $.post('includes/engines/invoice.php', {
            invNo: data.invoice,
            brokerCom: brokercom,
            agentCom: agentcom
        }, function(ret) {
            $('#confirmBox').modal('hide');
            $('#popupBox .modal-body').html('');
            var eTarget = $(this).data('target');
            var target = 'includes/master/financeMailer.php';
            var string = data.email;
            var dest = encodeURI(target + "?mode=popup&data=" + string)
            $('#popupBox').modal('show');
            $('#popupBox .modal-body').load(dest);

        })

    })

}
</script>