<?php require('../../includes/connection.php');

if(empty($_REQUEST['start']) && empty($_REQUEST['end'])){
$d=date('t');
$m=date('m');
$y=date('Y');

$monthStart="01-".$m."-".$y;
$monthEnd=$d."-".$m."-".$y;
//WHERE `date`>='".$_REQUEST['start']."' AND `date`<='".$_REQUEST['end']."'
$_REQUEST['start']=strtotime($monthStart);
$_REQUEST['end']=strtotime($monthEnd);
}
else{
$_REQUEST['start']=strtotime($_REQUEST['start']);
$_REQUEST['end']=strtotime($_REQUEST['end']);

}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `receipts` WHERE  `date`>='".$_REQUEST['start']."' AND `date`<='".$_REQUEST['end']."' ORDER BY abs(date) DESC")or die(mysqli_error("listClient B: ".$GLOBALS['con']));
$stmt->execute();$cc=$stmt->get_result();$stmt->close();

?>
<div class="row">
    <div class="col-md-4 input-group"><input class="form-control" type="text" name="date" id="date1" value="<?= date('d-m-Y',$_REQUEST['start'])?>"></div>
    <div class="col-md-1 text-center">
        <p style="font-size: 30px"><i id="toIcon" class="fad fa-arrow-alt-circle-right"></i></p>
    </div>
    <div class="col-md-4 input-group mb-4">
        <input class="form-control" type="text" name="date" id="date2" value="<?= date('d-m-Y',$_REQUEST['end'])?>" aria-describedby="filterDate">
        <div class="input-group-append">
            <button class="btn btn-md btn-secondary m-0 px-3 py-2 z-depth-0 waves-effect border" type="button" id="filterDate"><i class="fad fa-filter"></i> Filter results</button>
        </div>
    </div>
</div>


<div id="expenseData">
    <p class="lead reportHeader">Receipts for the period <b><?= date('d-m-Y',$_REQUEST['start'])?></b> to <b><?= date('d-m-Y',$_REQUEST['end'])?></b></p>
    <table id="expenseTable" class="table table-striped table-bordered">
        <thead>
            <tr class="headCell">
                <th class="c1">DATE</th>
                <th class="c1">PAYEE</th>
                <th class="c2">DETAILS</th>
                <th class="c6">NET</th>
                <th class="c7">VAT</th>
                <th class="c8">GROSS</th>
                <th class="c10">COM</th>
                <th class="c9">NETCOM</th>
                <th style="width:140px" class="no-sort"></th>
            </tr>
        </thead>
        <tbody>
            <?php 
        while($d=mysqli_fetch_array($cc)){
        $t=explode("|",$d['totals']);
        $t[0]=str_replace(',','',$t[0]);
        $t[1]=str_replace(',','',$t[1]);
        $t[2]=str_replace(',','',$t[2]);
        $nTotal=$nTotal+$t[0];
        $vTotal=$vTotal+$t[1];
        $pVat=$pVat+$t[1];
        $inv=ltrim( $d['invoice'], "0");
        
        $sub=str_replace(',','',$t[0]);
        $vat=str_replace(',','',$t[1]);
        $com=str_replace(',','',$d['commission']);
        if(empty($d['commission'])){$com="0.00";}
        $gtotal=$sub+$vat;
        $netCom=$gtotal-$com;
        $netCT=$netCT+$netCom;
        $totalCT=$totalCT+$com
        ?>
            <tr id="R<?= $d['id']?>" class="bodyCell">
                <td class="c1" width="100"><?= date('d-m-Y',$d['date'])?></td>
                <td class=" c2"><?= $d['payee']?></td>
                <td class="c3"><?= $d['details']?></td>
                <td class="c6">&pound;<?= number_format($t[0],2);?></td>

                <td class="c7">&pound;<?= number_format($t[1],2);?></td>
                <td class="c8">&pound;<?= number_format($t[0] + $t[1],2);?></td>
                <td class="c9">&pound;<?= number_format($com,2);?></td>
                <td class="c10">&pound;<?= number_format($netCom,2);?></td>
                <?php if(!empty($d['invoice']) && ($d['pType']=="A" || $d['pType']=="B" || $d['pType']=="C")){$ino = ltrim($d['invoice'], "0"); ?>
                <td class="text-center" width="150"><a class="btn btn-info btn-sm m-0 px-3 py-2 z-depth-0 mr-2" data-toggle="tooltip" data-placement="top" data-original-title="Edit details"
                       onclick="editEntry('R<?= $d['id']?>','<?= $d['id']?>')"><i
                           class="fad fa-pencil"></i></a> <a class="btn btn-danger btn-sm m-0 px-3 py-2 z-depth-0" data-toggle="tooltip" data-placement="top" data-original-title="Reset to unpaid"
                       onclick="removeEntryInvoice('R<?= $d['id']?>','<?= $d['id']?>','<?= $inv?>')"><i
                           class="fad fa-repeat"></i></a></td>
                <?php }
            else{?>
                <td class="text-center"><a class="btn btn-info btn-sm m-0 px-3 py-2 z-depth-0 mr-2" data-toggle="tooltip" data-placement="top" data-original-title="Edit details" onclick="editEntry('R<?= $d['id']?>','<?= $d['id']?>')"><i
                           class="fad fa-pencil"></i></a> <a class="btn btn-danger btn-sm m-0 px-3 py-2 z-depth-0" data-toggle="tooltip" data-placement="top" data-original-title="Remove Entry"
                       onclick="removeEntry('R<?= $d['id']?>','<?= $d['id']?>')"><i
                           class="fad fa-trash"></i></a></td>
                <?php }?>
            </tr>
            <?php }?>
        </tbody>
        <tfoot>
            <tr class="footCell">
                <th class="c1 footCell grey lighten-2">Totals</th>
                <th class="c2 grey lighten-2"></th>
                <th class="c2 grey lighten-2"></th>
                <th class="c6 grey lighten-2">&pound;<?= number_format($nTotal,2)?></th>
                <th class="c7 grey lighten-2">&pound;<?= number_format($vTotal,2)?></th>
                <th class="c8 grey lighten-2">&pound;<?= number_format($nTotal + $vTotal,2)?></th>
                <th class="c2 grey lighten-2">&pound;<?= number_format($totalCT,2)?></th>
                <th class="c2 grey lighten-2">&pound;<?= number_format($netCT,2)?></th>
                <th class="c2 grey lighten-2"></th>
            </tr>
        </tfoot>
    </table>


    <table class="vatBox table table-bordered table-sm" style="width:50%; display: none">
        <tr>
            <th colspan="2">VAT Analysis</th>
        </tr>
        <tr>
            <td>VAT FROM PURCHASES</td>
            <td>&pound;<?= number_format($pVat,2)?></td>
        </tr>
        <?php if($_REQUEST['payment_type']=="Expenses"){?>
        <tr>
            <td>VAT ELEMENT FROM FUEL</td>
            <td>&pound;<?= number_format($fVat,2)?></td>
        </tr>
        <?php }?>
        <tr>
            <th>TOTAL VAT INPUT</th>
            <th>&pound;<?= number_format($fVat+$pVat,2)?></th>
        </tr>
        <tr>
            <td>CLAIM EXCLUDING VAT</td>
            <td>&pound;<?= number_format($gTotal,2)?></td>
        </tr>
    </table>
    <?php 
    $table='expenseTable';
    $dateTarget='0';
    require('../finance_table.engine');?>

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

    <script>
    $('#filterDate').click(function() {
        var start = $('#date1').val()
        var end = $('#date2').val()
        $('#expenseList').load('includes/finance/finance_rcp_data.php?start=' + start + '&end=' + end)
    })

    $(document).ready(function() {
        $("#date1,#date2").pickadate({
            format: "dd-mm-yyyy",
            formatSubmit: "dd-mm-yyyy",
            selectMonths: true,
        });

    })

    $(window).resize(function() {
        if ($(window).width() < input) {
            $('#toIcon').removeClass('fa-arrow-alt-circle-right')
            $('#toIcon').addClass('fa-arrow-alt-circle-down')
        } else {
            $('#toIcon').removeClass('fa-arrow-alt-circle-down')
            $('#toIcon').addClass('fa-arrow-alt-circle-right')
        }
    })

    $('#expenseReport').click(function() {
        var start = $('#date1').val()
        var end = $('#date2').val()
        data = $('#expenseData').html()
        $.post('includes/engines/report.php', {
            'clientnumber': '000',
            type: 'receipts_' + start + '_' + end,
            content: data,
            format: 'L'
        }, function(ret) {
            //debug(ret)
            $('#genRow').html('<a href="output/reps/000_receipts_' + start + '_' + end + '.pdf" target="blank" class="btn btn-info"><i class="fal fa-file-pdf"></i> VIEW REPORT</a>')
            genFiles()
        })
    })

    function removeEntry(row, id) {
        confirmBox('Remove Entry', 'remove this registered receipt?', 'confirmRemove(\'' + row + '\',\'' + id + '\')')
    }

    function confirmRemove(row, id) {
        $.post('includes/finance/finance_receipts_functions.php', {
            FUNCTION: 'remove',
            id: id
        }, function(data) {
            $('#confirmBox').modal('hide');
            response('success', 'Entry removed successfully');
            regenData()
        })
    }


    function removeEntryInvoice(row, id, invoice) {
        confirmBox('Remove Entry', 'remove this registered receipt and reset invoice to unpaid?', 'confirmRemoveInvoice(\'' + row + '\',\'' + id + '\',\'' + invoice + '\')')
    }

    function confirmRemoveInvoice(row, id, invoice) {
        $.post('includes/finance/finance_receipts_functions.php', {
            FUNCTION: 'removeInvoice',
            id: id,
            invoice: invoice
        }, function(data) {
            $('#confirmBox').modal('hide');
            //debug(data)
            response('success', 'Entry removed and invoice reset successfully');
            regenData()
        })
    }

    function editEntry(row, id) {
        var dt = $('#' + row + ' .c1').text();
        var p = $('#' + row + ' .c2').text();
        var d = $('#' + row + ' .c3').text();
        var a = $('#' + row + ' .c6').text().replace('£', '');
        var v = $('#' + row + ' .c7').text().replace('£', '');
        var t = $('#' + row + ' .c8').text().replace('£', '');
        var com = $('#' + row + ' .c9').text().replace('£', '');
        if (v != '0.00') {
            var check = "checked"
        }
        var bodyData = '';
        bodyData += '<div class="row">';
        bodyData += '<div class="col col-md-6"><label>Date</label><input id="theDate' + id + '" class="form-control datepicker" value="' + dt + '" /></div>';
        bodyData += '<div class="col col-md-6"><label>Payee</label><input id="thePayee' + id + '" class="form-control" value="' + p + '" /></div>';
        bodyData += '</div>';
        bodyData += '<div class="row">';
        bodyData += '<div class="col col-md-6"><label>Details</label><input id="theDetails' + id + '" class="form-control" value="' + d + '" /></div>';
        bodyData += '<div class="col col-md-6"><label>Amount</label><input id="theAmount' + id + '" class="form-control" value="' + t + '" /></div>';
        bodyData += '<div class="col col-md-6"><label>Commission</label><input id="theCommission' + id + '" class="form-control" value="' + com + '" /></div>';
        bodyData += '<div class="col col-md-6"><label>&nbsp;</label><div class="form-check"><input type="checkbox" class="form-check-input" id="theVAT' + id + '" ' + check +
            '><label class="form-check-label" for="theVAT">VAT</label></div></div>';
        bodyData += '</div>';
        bodyData += '<input id="theId' + id + '" type="hidden" value="' + id + '" />';
        $("#popupBox .modal-header").html('<a href="javascript:void(0)" class="sa">Edit Entry</a>');
        $("#popupBox .modal-body").html(bodyData);
        $("#popupBox .modal-footer").html(
            '<div class="col-md-12"><div id="setButton" class="float-left"></div><div class="text-center float-right"><button class="btn btn-info" onclick="saveEdit(\'' + id + '\')"> Save </button></div></div>'
        );
        $("#popupBox").modal("show");
        $("#theDate" + id).pickadate({
            format: 'dd-mm-yyyy'
        });
    }

    function saveEdit(id) {
        var dta = $('#theDate' + id).val();
        var pa = $('#thePayee' + id).val();
        var da = $('#theDetails' + id).val();
        var ia = $('#theId' + id).val();
        var aa = $('#theAmount' + id).val();
        var co = $('#theCommission' + id).val();
        var va = $('#theVAT' + id)
        if (va.prop("checked")) {
            va = 1
        } else {
            va = 0;
        }
        $.post('includes/finance/finance_receipts_functions.php', {
            FUNCTION: 'edit',
            date: dta,
            payee: pa,
            details: da,
            amount: aa,
            commission: co,
            vat: va,
            id: ia
        }, function(ret) {
            //debug(ret)
            $("#popupBox").modal("hide");
            regenData();
        })
    }


    $('[data-toggle="tooltip"]').tooltip({
        trigger: "hover",
        container: "body"
    });
    </script>