<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
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));


$filterReport = " WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryTo'  AND inv.status not in('Draft', 'Cancel') ";
if (isset($customer_name) && $customer_name != 'All') {
    $filterReport .= " AND inv.customer_id ='$customer_name'";
}
$filterReport .= " UNION SELECT 'payment' AS nameTable, pay.create_date, pay.customer_id, pay.amount,
'', '', '','', pay.status

 from " . TABLE_PAYMENT . " AS pay WHERE DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryTo' AND pay.status <> 'Cancel' ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReport .= " AND pay.customer_id ='$customer_name'";
}
$filterReport .= " ORDER BY customer_id";

//Opening Balance


//if (isset($customer_name) && $customer_name != 'All') {
//    $filterReportOpening .= " AND pay.customer_id ='$customer_name'";
//}
//$filterReportOpening .= " ORDER BY create_date";
//Opening Balance
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <style>
        .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td {
            border: none;
        }
    </style>
</head>
<body>
<section id="container">
    <?php include('../includes/inc_top.php'); ?>
    <section id="main-content">
        <section class="wrapper">
            <div class="panel">
                <div class="panel-body">
                    <div class="">
                        <div class="span12">
                            <div class="">
                                <h2>Customer Payment Report</h2>
                            </div>
                            <script>
                                $(function () {
                                    $("#datepicker").datepicker({dateFormat: 'dd-mm-yy'});
                                    $("#datepicker1").datepicker({dateFormat: 'dd-mm-yy'});
                                });
                            </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'";
//                                            $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 btn-primary btn-large"
                                                    style="float:left;">
                                                Search
                                            </button>
                                            <?php if (isset($_GET['view'])) { ?>
                                                <button
                                                    onclick="exportTableToCSV('payment-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                                    class="btn btn-primary btn-large"
                                                    style="float:left; margin-left: 15px;">
                                                    Export CSV
                                                </button>
                                                <button
                                                    id="print"
                                                    class="btn btn-primary btn-large"
                                                    style="float:left; margin-left: 15px;">
                                                    Print
                                                </button>
                                            <?php } ?>
                                        </td>
                                    </tr>
                                </table>
                            </form>
                            <hr><?php
                            if (isset($_GET['view'])) {
                                ?>
                                <div class="adv-table">
                                    <?php if ($customer_name != '' || $customer_name != 'All') {
                                        $customer = CustomerSetup::GetCustomerSetupById($customer_name);
                                        echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                                        echo "<h2>" . $customer->name . "</h2>";
                                        echo '</th></tr></table>';
                                    }
                                    ?>
                                    <table class="display table table-bordered table-striped">
                                        <tbody>
                                        <tr style="border: 1px solid #666;">
                                            <th>Customer</th>
                                            <th>Opening</th>
                                            <th>Debit</th>
                                            <th>Credit</th>
                                            <th>Balance</th>
                                        </tr>
                                        <?php
                                        $qry = Invoice::GetInvoicePaymentReportListsForOwner($filterReport);
                                        $previousbalanceAmounttotal = 0;
                                        if ($qry) {
                                            $counter = 0;
                                            foreach ($qry as $qery) {
                                                $counter++;
                                                $qryDatePrevious = date('Y-m-d', strtotime('-1 day', strtotime($qryDate)));

                                                $filterReportOpening = " WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryDatePrevious'  AND inv.status not in('Draft', 'Cancel') ";
                                                $filterReportOpening .= " AND inv.customer_id ='$qery->customer_id'";
                                                $filterReportOpening .= " UNION SELECT 'payment' AS nameTable, pay.create_date, pay.customer_id  AS customer_id, pay.amount,
'', '', '','', ''
 from " . TABLE_PAYMENT . " AS pay WHERE DATE_FORMAT(pay.create_date,'%Y-%m-%d')>='2016-01-01' and DATE_FORMAT(pay.create_date,'%Y-%m-%d')<='$qryDatePrevious' AND pay.status <> 'Cancel' ";
                                                $filterReportOpening .= " AND pay.customer_id ='$qery->customer_id'";
                                                $filterReportOpening .= " ORDER BY create_date";
                                                $qryOpening = Invoice::GetInvoicePaymentReportListsForOwner($filterReportOpening);
                                                if ($qryOpening) {
                                                    $previoustotalDebitAmount = '';
                                                    $previoustotalCreditAmount = '';
                                                    $previousbalanceAmount = '';
                                                    foreach ($qryOpening as $qeryOpening) {
                                                        if ($qeryOpening->nameTable == 'invoice') {
                                                            $previousbalanceAmount -= $qeryOpening->total_amount;
                                                            $previoustotalCreditAmount += $qeryOpening->total_amount;
                                                        } else {
                                                            $previousbalanceAmount += $qeryOpening->amount;
                                                            $previoustotalDebitAmount += $qeryOpening->amount;
                                                        }
                                                    }
                                                }
                                                if ($qery->nameTable == 'invoice') {
                                                    $balanceAmount -= $qery->total_amount;
                                                    $totalCreditAmount += $qery->total_amount;
                                                    $subbalanceAmount -= $qery->total_amount;
                                                    $subtotalCreditAmount += $qery->total_amount;
                                                }
                                                $balanceAmount += $qery->amount;
                                                $totalDebitAmount += $qery->amount;
                                                $subbalanceAmount += $qery->amount;
                                                $subtotalDebitAmount += $qery->amount;
                                                if (isset($qry[$counter]->customer_id) && $qry[$counter]->customer_id != $qery->customer_id) {
                                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                                    ?>
                                                    <tr style="border: 1px solid #666;">
                                                        <td style="background-color: #ddd;"><?= $customer->name; ?></td>
                                                        <td style="background-color: #ddd;"><?= $previousbalanceAmount; ?></td>
                                                        <td style="background-color: #ddd;"><?= $subtotalDebitAmount; ?></td>
                                                        <td style="background-color: #ddd;"><?= $subtotalCreditAmount; ?></td>
                                                        <td style="background-color: #ddd;"><?= ($subbalanceAmount+$previousbalanceAmount); ?></td>
                                                    </tr>
                                                    <?php
                                                    $previousbalanceAmounttotal += $previousbalanceAmount;
                                                    $subbalanceAmount = 0;
                                                    $subtotalCreditAmount = 0;
                                                    $subtotalDebitAmount = 0;
                                                }
                                            }

                                        } ?>
                                        <tr>
                                            <th style="text-align: right; border: 1px solid #000;">Total
                                            </th>
                                            <th style="border: 1px solid #000;"><?= $previousbalanceAmounttotal ?></th>
                                            <th style="border: 1px solid #000;"><?= $totalDebitAmount ?> Db</th>
                                            <th style="border: 1px solid #000;"><?= $totalCreditAmount ?> Cr</th>
                                            <th style="border: 1px solid #000;"><?= ($totalCreditAmount + $previousbalanceAmounttotal) - $totalDebitAmount ?>
                                                <?= $totalDebitAmount > $totalCreditAmount ? 'Db' : 'Cr' ?>
                                            </th>
                                        </tr>
                                        <tr style="border: 1px solid #666;">
                                            <th>Customer</th>
                                            <th>Opening</th>
                                            <th>Debit</th>
                                            <th>Credit</th>
                                            <th>Balance</th>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <?php

                            } // close view
                            ?>
                        </div>
                    </div>
                </div>
                <footer>
                    <?php include('../includes/inc_footer.php'); ?>
                </footer>
            </div>
        </section>
        <script type="text/javascript" src="<?= PROJECT_URL ?>js/download.js"></script>
        <?php include('../includes/inc_js.php'); ?>
        <style>
            @page {
                size: A4;
                margin: 5mm 0mm;
            }

            @media print {
                table {
                    page-break-inside: auto
                }

                tr {
                    page-break-inside: avoid;
                    page-break-after: auto
                }

                #container {
                    page-break-after: always;
                }

                header, aside, form, footer {
                    display: none;
                }

                .adv-table th, .adv-table td {
                    padding: 5px;
                }

                h2 {
                    font-size: 18px;
                    text-align: center;
                }

                hr {
                    margin-top: 5px;
                    margin-bottom: 5px;
                }
            }
        </style>
        <script type="application/javascript">
            $("#print").on("click", function (e) {
                var fewSeconds = 2;
                e.preventDefault();
                $('#searchfrm').prop('target', '_blank');
                $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/customerpayment.php?").submit();
                setTimeout(function () {
                    $('#searchfrm').prop('target', "");
                    $('#searchfrm').prop('action', "");
                }, fewSeconds * 1000);
            });
        </script>
</body>
</html>