<?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']);

}

if(strtolower($_REQUEST['payment_type'])=="expenses"){
    $_REQUEST['payment_type']="Expenses";
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `expenses` WHERE `payment_type`='".$_REQUEST['payment_type']."' AND `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="<?php echo 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="<?php echo 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"><?php echo $_REQUEST['payment_type']?> for the period <b><?php echo date('d-m-Y',$_REQUEST['start'])?></b> to <b><?php echo date('d-m-Y',$_REQUEST['end'])?></b></p>

    <table id="expenseTable" class="table table-striped table-bordered table-responsive-sm" style="width:100%" width="100%">
        <thead width="100%">
            <tr class="headCell" width="100%">
                <th class="c1" style="width:120px">DATE</th>
                <th class="c1">PAYEE</th>
                <th class="c2">DETAILS</th>
                <?php if($_REQUEST['payment_type']=="Expenses"){?>
                <th class="c3">MILES</th>
                <th class="c4">RATE</th>
                <th class="c5">CLAIM</th>
                <?php }?>

                <th class="c6">NET</th>
                <th class="c7">VAT</th>
                <th class="c8">GROSS</th>
                <th></th>
            </tr>
        </thead>
        <tbody width="100%">
            <?php 
            while($d=mysqli_fetch_array($cc)){
            $t=explode("|",$d['totals']);
            $net=str_replace(',','',$t[0]);
            $vat=str_replace(',','',$t[1]);

            $d['amount']=str_replace(',','',$d['amount']);
            
            $nTotal=$nTotal+$net;
            $vTotal=$vTotal+$vat;
            $mTotal=$mTotal+$d['vMileage'];

            if(!empty($d['vMileage'])){
            $mileage=$d['vMileage'];
            $fVat=$fVat+$t[1];
            }
            else{
            $mileage="";
            $pVat=$pVat+$t[1];
            }
           
            if(!empty($d['vRate'])){$rate="&pound;".number_format($d['vRate'],2);}else{$rate="";}
            if(!empty($d['amount']) && !empty($d['vMileage'])){$amount=number_format($d['amount'],2);}else{$amount="0.00";}
            if(!empty($net)){}else{$net="0.00";}
            if(!empty($vat)){}else{$vat="0.00";}
            $rowTotal=$d['amount'];
            $gTotal=$gTotal+$net;
             $matotal=$matotal+$rowTotal;
            ?>
            <tr id="R<?php echo $d['id']?>" class="bodyCell" width="100%">
                <td class="c1"><?php echo date('d-m-Y',$d['date'])?></td>
                <?php if($_REQUEST['payment_type']=="Expenses"){?>
                <td class="c2"><?php echo $d['employee']?></td>
                <?php $t="employee";}
                    else{?>
                <td class="c2"><?php echo $d['payee']?></td>
                <?php $t="payee";}?>
                <td class="c3"><?php echo $d['desc']?></td>
                <?php if($_REQUEST['payment_type']=="Expenses"){?>
                <td class="c3"><?php echo $mileage?></td>
                <td class="c4"><?php echo $rate?></td>
                <td class="c8">&pound;<?= number_format($rowTotal,2);?></td>
                <?php }?>
                <td class="c6">&pound;<?= number_format($net,2);?></td>
                <td class="c7">&pound;<?= number_format($vat,2);?></td>
                <td class="c8">&pound;<?= number_format($rowTotal,2);?></td>
                <td class="text-center" style="max-width:80px"><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<?php echo $d['id']?>','<?php echo $d['id']?>','<?php echo $t?>')"><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<?php echo $d['id']?>','<?php echo $d['id']?>')"><i class="fad fa-trash"></i></a></td>
            </tr>
            <?php }?>
        </tbody>
        <tfoot>
            <tr class="footCell">
                <th class="c1 grey lighten-2">Totals</th>
                <td class="c2 grey lighten-2"></td>
                <td class="c2 grey lighten-2"></td>
                <?php if($_REQUEST['payment_type']=="Expenses"){?>
                <td class="c3 grey lighten-2"><?php echo $mTotal?></td>
                <td class="c4 grey lighten-2"></td>
                <th class="c5 grey lighten-2">&pound;<?php echo number_format($gTotal,2)?></th>
                <?php }?>
                <th class="c6 grey lighten-2">&pound;<?php echo number_format($nTotal,2)?></th>
                <th class="c7 grey lighten-2">&pound;<?php echo number_format($vTotal,2)?></th>
                <th class="c8 grey lighten-2">&pound;<?php echo number_format($matotal,2)?></th>
                <th class="c8 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;<?php echo number_format($pVat,2)?></td>
        </tr>
        <?php if($_REQUEST['payment_type']=="Expenses"){?>
        <tr>
            <td>VAT ELEMENT FROM FUEL</td>
            <td>&pound;<?php echo number_format($fVat,2)?></td>
        </tr>
        <?php }?>
        <tr>
            <th>TOTAL VAT INPUT</th>
            <th>&pound;<?php echo number_format($fVat+$pVat,2)?></th>
        </tr>
        <tr>
            <td>CLAIM EXCLUDING VAT</td>
            <td>&pound;<?php echo number_format($gTotal,2)?></td>
        </tr>
    </table>

</div>
<?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="fad 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_exp_data.php?payment_type=<?php echo $_REQUEST['payment_type']?>&start=' + start + '&end=' + end, function() {

    })
})

$(window).resize(function() {
    if ($(window).width() < 760) {
        $('#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: '<?php echo $_REQUEST['payment_type']?>_' + start + '_' + end,
        content: data,
        format: 'L'
    }, function(ret) { //debug(ret)
        $('#genRow').html('<a href="output/reps/000_<?php echo $_REQUEST['payment_type']?>_' + start + '_' + end + '.pdf" target="blank" class="btn btn-info"><i class="fad fa-file-pdf"></i> VIEW REPORT</a>')
        genFiles()
    })

})

$(document).ready(function() {

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

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

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


function editEntry(row, id, type) {
    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('£', '');
    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" class="form-control datepicker" value="' + dt + '" /></div>';
    bodyData += '<div class="col col-md-6"><label>Payee</label><input id="thePayee" 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" class="form-control" value="' + d + '" /></div>';
    bodyData += '<div class="col col-md-6"><label>Amount</label><input id="theAmount" class="form-control" value="' + t + '" /></div>';
    bodyData += '<div class="col col-md-6"><label>&nbsp;</label><div class="form-check"><input type="checkbox" class="form-check-input" id="theVAT" ' + check + '><label class="form-check-label" for="theVAT">VAT</label></div></div>';
    bodyData += '</div>';
    bodyData += '<input id="theId" type="hidden" value="' + id + '" /><input id="theType" type="hidden" value="' + type + '" />';

    $("#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()"> Confirm Changes </button></div></div>');
    $("#popupBox").modal("show");
    $("#theDate").pickadate({
        format: 'dd-mm-yyyy'
    });
}

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