<?php $_REQUEST['src'] = "ext2";
require('../../functions/global.php');
require('finance_functions.php');
$ds = strtotime($_REQUEST['start']);
$de = strtotime($_REQUEST['end']);

function counter($client, $type, $start, $end)
{

    if ($type == "paid") {
        $q = "AND `status`='3'";
        $paid = "_paid";
    }
    if ($type == "unpaid") {
        $q = "AND `status`='1'";
    }
    if ($type == "both") {
        $q = "AND (`status`='1' OR `status`='3')";
    }
    if ($_REQUEST['clientnumber'] == 0) {
        $clientD = "";
    } else {
        $clientD = "AND `client`='" . $client . "'";
    }
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `date" . $paid . "` BETWEEN '" . $start . "' AND '" . $end . "' $q $clientD ORDER BY abs(invno) DESC") or die(mysqli_error($GLOBALS['con']));
    $stmt->execute();
    $i = $stmt->get_result();
    $stmt->close();
    $check = mysqli_num_rows($i);
    return $check;
}


switch ($_REQUEST['mode']) {
    case "choose":
        if ($_REQUEST['clientnumber'] == 0) {
            $clientName = "ALL";
        } else {
            $clientName = getClientName($_REQUEST['clientnumber']);
        }
?>
<div class="col-12 mt-n5"><span class="badge badge-pill badge-info">2</span> Select Output Type for
    <strong><?= $clientName ?></strong></div>
<div class="row mt-4">
    <div class="col-12 col-md-4 text-center mb-3"><a href="javascript:void(0)" onclick="load('paid')"
            class="btn btn-secondary btn-block" data-toggle="tooltip" data-placement="top"
            data-original-title="Edit Client Details">Summary of paid
            invoices <span
                class="badge badge-info"><?= counter($_REQUEST['clientnumber'], 'paid', $ds, $de) ?></span></a></div>
    <div class="col-12 col-md-4 text-center mb-3"><a href="javascript:void(0)" onclick="load('unpaid')"
            class="btn btn-secondary btn-block" data-toggle="tooltip" data-placement="top"
            data-original-title="Edit Client Details">Summary of
            unpaid invoices <span
                class="badge badge-info"><?= counter($_REQUEST['clientnumber'], 'unpaid', $ds, $de) ?></span></a></div>
    <div class="col-12 col-md-4 text-center mb-3"><a href="javascript:void(0)" onclick="load('both')"
            class="btn btn-secondary btn-block" data-toggle="tooltip" data-placement="top"
            data-original-title="Edit Client Details">Balance Sheet
            <span class="badge badge-info"><?= counter($_REQUEST['clientnumber'], 'both', $ds, $de) ?></span>
        </a></div>
</div>
<div class="col-12 text-center mt-4"><a href="index.php?t=includes/finance&p=statements.php"
        class="btn btn-secondary">Cancel</a></div>

<div class="col-md-12 mt-3 mb-3">
    <hr>
</div>

<h2>Statements for <?= getClientName($_REQUEST['clientnumber']) ?></h2>
<?php
        $files = array();
        $docs = glob("../../output/reps/*.pdf");
        $docs = array_combine(array_map("filemtime", $docs), $docs);
        krsort($docs);
        foreach ($docs as $filename) {
            if (preg_match("/statement/", $filename) && preg_match("/" . $_REQUEST['clientnumber'] . "/", $filename)) {
                $files[] = $filename;
            }
        }
        ?>
<div class="card-deck">
    <?php foreach ($files as $file) {
                $doc = $file;
                $color = '';
                $file = str_replace('output/reps/' . $_REQUEST['clientnumber'] . '_', '', $file);
                $file = str_replace('.pdf', '', $file);
                $file = explode('_', $file);
                if ($file[1] == "unpaid") {
                    $color = "text-danger";
                    $title = "Summary of unpaid invoices";
                }
                if ($file[1] == "paid") {
                    $color = "text-success";
                    $title = "Summary of paid invoices";
                }
                if ($file[1] == "both") {
                    $color = "text-dark";
                    $title = "Balance Sheet";
                }
            ?>

    <div class="card">
        <div class="card-header <?= $color ?>"><?= strtoupper($title) ?></div>
        <div class="card-body"><a class="btn btn-block btn-secondary" href="javascript:void(0)" onClick="">Statement
                Generated<br><?= $file[2] ?></a></div>
        <div class="card-footer text-center">
            <a href="javascript:void(0)" class="btn btn-secondary noprint emailButton"
                data-values="<?= $_REQUEST['clientnumber'] ?>|||Emailing Statement|Please find attached your statement of account|<?= $doc ?>"
                data-href="includes/master/mailer.php" data-toggle="tooltip" data-placement="top"
                data-original-title="Email Client"><i class="fad fa-envelope"></i></a>
            <a href="index.php?t=includes/master&amp;p=items.php&amp;view=view&amp;repnumber=1575056643&amp;data=18|316|315"
                class="btn btn-secondary" data-toggle="tooltip" data-placement="bottom" title=""
                data-original-title="View  Report"><i class="fad fa-eye"></i></a>
            <a href="javascript:void(0)" class="btn btn-secondary delButton" data-values="<?= $doc ?>"
                data-toggle="tooltip" data-placement="top" data-original-title="Delete Statement"><i
                    class="fad fa-trash"></i></a>
        </div>
    </div>


    <?php } ?>
</div>

<?php break;

    case "result":
        if ($_REQUEST['type'] == "paid") {
            $q = "AND `status`='3'";
            $title = "Summary of paid invoices";
            $paid = "_paid";
        }
        if ($_REQUEST['type'] == "unpaid") {
            $q = "AND `status`='1'";
            $title = "Summary of unpaid invoices";
        }
        if ($_REQUEST['type'] == "both") {
            $q = "AND (`status`='1' OR `status`='3')";
            $title = "Balance Sheet";
        }
    ?>
<div class="col-12">
    <h2>Statement of accounts (<?= $title ?>) <span class="float-right"><?= $_REQUEST['start'] ?> <i
                class="fad fa-chevron-right"></i> <?= $_REQUEST['end'] ?></span></h2>
</div>
<?php
        if ($_REQUEST['clientnumber'] == 0) {
            $clientD = "";
        } else {
            $clientD = "AND `client`='" . $_REQUEST['clientnumber'] . "'";
        }
        $stmt = $GLOBALS['con']->prepare("SELECT * FROM `invoices` WHERE `date" . $paid . "` BETWEEN '" . $ds . "' AND '" . $de . "' $q $clientD  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;
        }
        if ($check == 0) { ?>
<div class="col-12 text-center mb-4">
    <h3 class="lead text-warning">No data available</h3>
</div>
<div class="col-12 text-center mt-4"><a href="index.php?t=includes/finance&p=statements.php"
        class="btn btn-secondary">Start Again</a></div>
<?php } else { ?>
<div id="last">
    <div id="pdfData">
        <table id="statementTable" 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>Status</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']);

                                if ($id['status'] == "3") {
                                    $status = '<span class="text-success">Paid</span>';
                                    $ptotal += $gtotal;
                                }
                                if ($id['status'] == "1") {
                                    $status = '<span class="text-danger">Unpaid</span>';
                                    $uptotal += $gtotal;
                                }
                            ?>
                <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><?= $status ?></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
    <div class="row">
        <hr>
        <?php
                    $sdata = '<strong>Account Summary</strong><br>Credits: £' . number_format($ptotal, 2) . '<br>Charges: £' . number_format($uptotal, 2) . '<br><strong>Total Balance Due:</strong> £' . number_format($uptotal, 2) . '
';

                    if ($_REQUEST['type'] == "paid") {
                        $totals = '<div class="col-12 text-center"><strong>Total Paid:</strong> &pound;' . number_format($ptotal, 2) . '</div>';
                    }
                    if ($_REQUEST['type'] == "unpaid") {
                        $totals = '<div class="col-12 text-center"><strong>Total Unpaid:</strong> &pound;' . number_format($uptotal, 2) . '</div>';
                    }
                    if ($_REQUEST['type'] == "both") {
                        $totals = '<div class="col-12 col-md-6 text-center"><strong>Total Paid:</strong> &pound;' . number_format($ptotal, 2) . '</div><div class="col-12 col-md-6 text-center"><strong>Total Unpaid:</strong> &pound;' . number_format($uptotal, 2) . '</div>';
                    }
                    echo $totals;
                    ?>
        <hr>
    </div>
    <div class="col-12 text-center mt-4">
        <a href="index.php?t=includes/finance&p=statements.php" class="btn btn-secondary">Start Again</a>
        <a href="javascript:void(0)" class="btn btn-info" onclick="gen()">Generate Statement</a>
    </div>
</div>

<div id="loader" class="col-md-12 text-center" style="display:none; color:#393939">
    <h1>
        <i class="fad fa-ring fa-spin fa-3x fa-fw"
            style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Generating
        Statement<br><small>Please wait</small>

    </h1>
</div>


<?php
            $table = "exportTable";
            require('../single_table.engine');
        }
        break;
}
?>



<script>
function load(i) {
    $('#data').load(
        'includes/finance/statement_data.php?clientnumber=<?= $_REQUEST['clientnumber'] ?>&start=<?= $_REQUEST['start'] ?>&end=<?= $_REQUEST['end'] ?>&type=' +
        i + '&mode=result').css('display', 'block')
    $('#loader').css('display', 'none')
}

function gen() {
    //alert('<?= $_REQUEST['clientnumber'] ?>')
    var data = $('#pdfData').html()
    $('#last').css('display', 'none')
    $('#loader').css('display', 'block')
    $.post('includes/engines/report.php', {
        content: data,
        clientnumber: '<?= $_REQUEST['clientnumber'] ?>',
        name: '<?= getClientName($_REQUEST['clientnumber']) ?>',
        type: 'statement',
        version: '<?= $_REQUEST['type'] ?>',
        format: 'P',
        addressBox: 'client',
        sdata: '<?= urlencode($sdata) ?>',
        total: '<?= number_format($uptotal, 2) ?>'
    }, function(ret) {
        //debug(ret)
        location.href =
            'index.php?t=includes/finance&p=statement_list.php&clientnumber=<?= $_REQUEST['clientnumber'] ?>'
    })
}
</script>