<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_name = "";
$totalProfitPrevious = 0;
$totalPaymentsPrevious = 0;
$costPriceTotal = 0;
$unitPriceTotal = 0;
$totalDiscount = 0;
$totalProfit = 0;
$productQtyTotal = 0;
$totalPayments = 0;
$openingBalance = 0;
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);
if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-30 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}
if ($dateto == "") {
    $dateto = date('Y-m-d');
} else {
    $dateto = date("Y-m-d", strtotime($dateto));
}
$datefrom = date("d-m-Y", strtotime($datefrom));
$dateto = date("d-m-Y", strtotime($dateto));

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo = date("Y-m-d", strtotime($dateto));

if (isset($customer_name) && $customer_name != 'All') {
    $filterReport = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust ON pay.customer_id = cust.id
WHERE DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryTo'  AND pay.status not in('Draft', 'Cancel') ";
    $filterReport .= " AND pay.customer_id ='$customer_name'";
    $filterReport .= " GROUP BY pay.code ";
}else{
    $filterReport = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust ON pay.customer_id = cust.id WHERE DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryTo'  AND pay.status not in('Draft', 'Cancel') ";
    $filterReport .= " GROUP BY pay.customer_id ";
}
$filterReport .= " ORDER BY cust.name, customer_id, create_date, code ";
//echo $filterReport;
//echo "<br>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>
<!-- Start Page Loading 
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Monthly Payment Report</h3>
            </div>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                      selectYears: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                      selectYears: true,
                    });
                });
            </script>
            <form action="" method="get" name="search"
                  id="searchfrm">
                <table class="table">
                    <tr>
                        <td class="col-lg-4">Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col-lg-4"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="col-lg-4">Customer<br>
                            <?php
                            $customersfilter = " WHERE status = 'active' ORDER BY name";
                            $customers = CustomerSetup::GetCustomerSetupList($customersfilter);
                            ?>
                            <select class="form-control" required id="customer_name"
                                    name="customer_name">
                                <option>All</option>
                                <?php
                                if ($customers) {
                                    foreach ($customers AS $customersRow) {
                                        echo '<option ';
                                        if ($customersRow->id == $customer_name) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $customersRow->id . '" >' . $customersRow->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" class="col-lg-4">
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                            <?php if (isset($_GET['view'])) { ?>
                                <button type="button"
                                        onclick="exportTableToCSV('monthly-payment-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                        class="btn waves-effect waves-light"
                                        style="float:left; margin-left: 15px;">
                                    Export CSV
                                </button>
                                <button
                                    id="print"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Print
                                </button>
                            <?php } ?>
                        </td>
                    </tr>
                </table>
            </form>
            <hr>
            <?php
            if (isset($_GET['view'])) {
                if ($customer_name != '' || $customer_name != 'All') {
                    $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                    if (!empty($customer)) {
                        echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                        echo "<h2 style='text-align: center;'>" . $customer->name . "</h2>";
                        echo '</th></tr></table>';
                    }
                }
                ?>
                <div id="floatThead" class="adv-table section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <?php if ($customer_name == '' || $customer_name == 'All') { ?>
                                <th>Customer</th>
                                <th>No. of Payments</th>
                            <?php }else{ ?>
                                <th>Date</th>
                                <th>Invoice #</th>
                                <th>Payment Type</th>
                            <?php } ?>
                            <th>Total</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                    if ($customer_name != '' && $customer_name != 'All') {
                        $qry = Invoice::GetInvoiceCustomerReportListMonthlyPayment($filterReport);
                        $counter = 0;
                        if ($qry) {
                            foreach ($qry as $qery) {
                                $counter++;
                                ?>
                                <tr style="border: 1px solid #666;">
                                    <td><?= $counter ?></td>
                                    <td><?php echo date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                    <td><?php echo $qery->code; ?></td>           
                                    <td><?php echo $qery->payment_type; ?></td>
                                    <td><?php echo number_format(($qery->amount), 2, '.', ''); ?></td>
                                </tr>
                                <?php
                                $totalProfit += $qery->amount;
                            }
                        }
                    }else{
                        $qry = Invoice::GetInvoiceCustomerReportListMonthlyPaymentCustomers($filterReport);
                        $counter = 0;
                        if ($qry) {
                            foreach ($qry as $qery) {
                                $counter++;
                                ?>
                                <tr style="border: 1px solid #666;">
                                    <td><?= $counter ?></td>
                                    <?php $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id); ?>
                                    <td><a target="_blank" href="/sales/admin/report/monthly_payment.php?datefrom=<?=$datefrom?>&view=&dateto=<?=$dateto?>&customer_name=<?=$qery->customer_id?>"><?php echo $customer->name; ?></a></td>
                                    <td><?php echo $qery->total_invoices; ?></td>
                                    <td><?php echo number_format($qery->total_amount, 2, '.', ''); ?></td>
                                </tr>
                                <?php
                                $totalProfit += $qery->total_amount;
                            }
                        }
                    }
                        ?>
                        <tr>
                            <?php if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 4;
                            } ?>
                            <th colspan="<?= $num ?>"
                                style="text-align: right; border: 1px solid #000;">
                                Total
                            </th>
                            <th style="border: 1px solid #000;"><?= number_format(($totalProfit), 2, '.', '') ?></th>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <?php

            } // close view
            ?>
        </div>
    </div>
</div>
</div>
<?php include('../includes/inc_footer.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/download.js"></script>
<?php include('../includes/inc_js.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead.min.js"></script>
<script type="text/javascript"
        src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead-slim.min.js"></script>
<script type="application/javascript">
    $(document).ready(function () {
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/monthly_payment.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, fewSeconds * 1000);
        });
        $('table.demo1').floatThead({
            position: 'fixed',
            scrollingTop: 65
        });
        $('table.demo1 thead').css('background', '#ECEFF1');
    });
</script>
</body>
</html>