<?php
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php'); }
if(file_exists('/config.php')){require_once('/config.php'); }
?>
<div class="row mt-0 mt-md-n5">
    <div class="col-12">
        <p class="lead">Agent Finances - <strong><?php echo getAgentName($_REQUEST['agent_number'])?></strong></p>
    </div>
</div>

<?php 
function getPaymentStatus($s){
if($s==1){return '<span class="badge badge-warning d-block" style="font-size:12px">Unpaid</span>';}
if($s==3){return '<span class="badge badge-success d-block" style="font-size:12px">Paid</span>';}
}

function getPaymentStatusB($s){
if($s==1){return 'Unpaid';}
if($s==3){return 'Paid';}
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `agent`=?  AND `status`!='5' AND `status`!='3' ")or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i',$_REQUEST['agent_number']);$stmt->execute();$iv=$stmt->get_result();$stmt->close();
$tdata='';
$sdata='';
$tTotal=0;
$vTotal=0;
$gTotal=0;
$mTotal=0;
while($d=mysqli_fetch_array($iv)){
    $rowGross=0;
    $rowTotal=0;
$m=explode('|',$d['totals']);
$m[0]=str_replace(',','',$m[0]);
$m[1]=str_replace(',','',$m[1]);
$rowGross=($m[0]+$m[1]);
$rowTotal=($rowGross-$d['commission']);


$vTotal=$tTotal+$m[0];
$tTotal=$tTotal+$d['commission'];
$gTotal=$tTotal+$rowTotal;
$mTotal=$mTotal+$rowTotal;
    




$tdata.='<tr valign="middle">
<td>'.sprintf("%06d", $d['invNo']).'</td>
<td>'.getClientName($d['client']).'</td>
<td>'.getPaymentStatus($d['status']).'</td>
<td>'.date('d-m-Y',$d['date']).'</td>
<td>'.$m[0].'</td>
<td>'.$m[1].'</td>

<td><span style="display:inline-block">&pound;</span> <span style="display:inline-block">'.number_format($rowTotal,2).'</span></td>
</tr>
';

$sdata.='<tr valign="middle">
<td>'.sprintf("%06d", $d['invNo']).'</td>
<td>'.getClientName($d['client']).'</td>
<td>'.getPaymentStatusB($d['status']).'</td>
<td>'.date('d-m-Y',$d['date']).'</td>
<td>'.$m[0].'</td>
<td>'.$m[1].'</td>

<td><span style="display:inline-block">&pound;</span> <span style="display:inline-block">'.number_format($rowTotal,2).'</span></t
</tr>
';
}?>


<div id="pdfData">

    <table id="statementTable" class="table table-striped table-sm responsive" width="100%">
        <thead>
            <tr class="headCell">
                <th>Invoice Number</th>
                <th>Client</th>
                <th width="100px">Status</th>
                <th width="100px">Date Issued</th>
                <th>Net Fee</th>
                <th>VAT</th>
                <th>Total</th>
            </tr>
        </thead>
        <tbody>
            <?php echo $tdata?>
        </tbody>
    </table>

    <div id="reportData" style="display: none">
        <div id="exportTitle" class="reportHeader"><?php echo getAgentName($_REQUEST['agent_number'])?> Statement - <?php echo date('d-m-Y')?></div>
        <table class="table table-striped table-sm responsive" width="100%">
            <thead>
                <tr>
                    <th>Invoice Number</th>
                    <th>Client</th>
                    <th>Status</th>
                    <th>Date Issued</th>
                    <th>Net Fee</th>
                    <th>VAT</th>
                    <th>Total <small></small></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <th colspan="8">&nbsp;</th>
                </tr>
                <?php echo $sdata?>
                <tr>
                    <th colspan="8">&nbsp;</th>
                </tr>
            </tbody>
            <tfoot>
                <tr class="footCell">
                    <th colspan="7">
                    <th>£<?php echo number_format($mTotal,2)?> <small>Outstanding</small></th>
                </tr>
            </tfoot>
        </table>
    </div>
    <?php
$table="statementTable";
require($link.'includes/single_table.engine');
?>
    <?php if($_REQUEST['mode']=="popup"){?>
    <div class="col-md-12 text-center">
        <button id="gsend" type="button" class="btn btn-secondary" onclick="sendStatement()"><i class="fal fa-file-chart-line"></i> SEND REPORT</button>
    </div>

    <?php }
else{?>
    <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>
    <?php }?>
    <div class="alert alert-info float-right">Total Outstanding:&nbsp;<span class="float-right">£<?php echo number_format($mTotal,2)?></span></div>

</div>

<div class="spacer"></div>

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

})

$('#navBox').html(
    '<li class="breadrumb-item"><a href="index.php?t=includes/master&p=agent.php&view=list">Agent List</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/master&p=agent.php&agent_number=<?php echo $_REQUEST['agent_number']?>&view=edit"><?php echo getAgentName($_REQUEST['agent_number'])?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li><li class="breadrumb-item active">Agent Finances</li>'
    )


function setPaid(ino) {
    $.post('includes/finance/finance_functions.php', {
        FUNCTION: 'setAgentPaid',
        inv: ino
    }, function(data) {
        if ($.trim(data) == "success") {
            response('success', 'The commission payment status has been updated')
        }
    })

}

function sendStatement() {
    $.post('includes/finance/finance_functions.php', {
        FUNCTION: 'sendStatement',
        number: '<?php echo $_REQUEST['agent_number']?>',
        mode: 'agent'
    }, function(ret) {
        data = $.trim(ret)
        data = data.split('|');

        var contentData = $('#reportData').html()
        $.post('includes/engines/report.php', {
            content: contentData,
            name: data[1],
            type: 'statement',
            number: '<?php echo $_REQUEST['agent_number']?>',
            version: 'unpaid',
            format: 'L',
            addressBox: 'agent',
            sdata: '<?php echo urlencode($sdata)?>',
            total: '<?php echo number_format($mTotal,2)?>'
        }, function(ret) {
            var destFile = $.trim(ret);

            $('#popupBox .modal-body').html('');
            var target = 'includes/master/financeMailer.php';
            $emailString = '0|' + data[2] + '|' + data[3] + '|' + data[0] + ' Statement |Your Statement|' + destFile + '|output/reps/|' + destFile;

            var string = data[1] + '|' + data[2] + '|' + data[3] + '|Your Statement|Attached is your statement|output/reps/|' + destFile;

            var dest = encodeURI(target + "?mode=popup&data=" + string)
            $('#popupBox').modal('show');
            $('#popupBox .modal-body').load(dest);

        })



    })
}
</script>