<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_name = "";
$balanceAmount = 0;
$totalCreditAmount = 0;
$totalDebitAmount = 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));
$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.code, pay.customer_id, pay.invoice_reference_code, pay.payment_type, pay.amount,
pay.cheque_bank_name, pay.cheque_number, pay.cheque_payee_name, pay.cheque_date, pay.bank_name, pay.bank_account_number, pay.party_name, pay.from_bank_name,
'', '', '','', '', ''

 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 create_date";

//Opening Balance
$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') ";
if (isset($customer_name) && $customer_name != 'All') {
    $filterReportOpening .= " AND inv.customer_id ='$customer_name'";
}
$filterReportOpening .= " UNION SELECT 'payment' AS nameTable, pay.create_date, pay.code, pay.customer_id, pay.invoice_reference_code, pay.payment_type, pay.amount,
pay.cheque_bank_name, pay.cheque_number, pay.cheque_payee_name, pay.cheque_date, pay.bank_name, pay.bank_account_number, pay.party_name, pay.from_bank_name,
'', '', '','', '', ''
 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' ";

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'); ?>
</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>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 s6">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 s6"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="col s6">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 s12">
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                            <?php if (isset($_GET['view'])) { ?>
                                <button
                                    onclick="exportTableToCSV('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>" . $customer->name . "</h2>";
                        echo '</th></tr></table>';
                    }
                }
                ?>
                <div id="floatThead" class="section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Head</th>
                            <th>Invoice Date</th>
                            <th>Invoice / Payment #</th>
                            <th>Customer</th>
                            <th>Sales Person</th>
                            <th>Status</th>
                            <th>Payment Type</th>
                            <th>Bank / Party Name</th>
                            <th>Payment Date</th>
                            <th>Debit</th>
                            <th>Credit</th>
                            <th>Balance</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        $qryOpening = Invoice::GetInvoicePaymentReportLists($filterReportOpening);
                        if ($qryOpening) {
                            foreach ($qryOpening as $qeryOpening) {
                                if ($qeryOpening->nameTable == 'invoice') {
                                    $balanceAmount -= $qeryOpening->total_amount;
                                    $totalCreditAmount += $qeryOpening->total_amount;
                                } else {
                                    $balanceAmount += $qeryOpening->amount;
                                    $totalDebitAmount += $qeryOpening->amount;
                                }
                            }
                        } ?>
                        <tr style="border: 1px solid #666;">
                            <td>Opening</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td><?= $totalDebitAmount ?></td>
                            <td><?= $totalCreditAmount ?></td>
                            <td><?= $balanceAmount ?></td>
                        </tr>
                        <?php
                        $qry = Invoice::GetInvoicePaymentReportLists($filterReport);
                        if ($qry) {
                            $invoiceNumber = '0';
                            foreach ($qry as $qery) {
                                if ($qery->nameTable == 'invoice') {
                                    $invoiceNumber = $qery->code;
                                    $balanceAmount -= $qery->total_amount;
                                    $totalCreditAmount += $qery->total_amount;
                                    ?>
                                    <tr style="border: 1px solid #666;">
                                        <td>Invoice</td>
                                        <td><?php echo date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                        <?php
                                        $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                        $salesPerson = User_setup::GetUserSetupId($qery->sales_person_id);
                                        ?>
                                        <td><?php echo $qery->code; ?></td>
                                        <td><?php echo $customer->name; ?></td>
                                        <?php
                                        $bank = BankSetup::GetBankSetupById($qery->bank_name);
                                        ?>
                                        <td><?php echo $salesPerson->username; ?></td>
                                        <td><?php echo $qery->status; ?></td>
                                        <td>-</td>
                                        <td>-</td>
                                        <td>-</td>
                                        <td>0</td>
                                        <td><?php echo $qery->total_amount; ?></td>
                                        <td><?php echo $balanceAmount; ?></td>
                                    </tr>
                                    <?php
                                }
                                $balanceAmount += intval($qery->amount);
                                $totalDebitAmount += intval($qery->amount);
                                if ($qery->nameTable == 'payment') {
                                    ?>
                                    <tr style="border: 1px solid #666;">
                                        <td>Payment</td>
                                        <td>-</td>
                                        <?php
                                        $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                        //$salesPerson = User_setup::GetUserSetupId($qery->sales_person_id);
                                        ?>
                                        <td><?php echo $qery->code; ?></td>
                                        <td><?php echo $customer->name; ?></td>
                                        <?php
                                        $bank = BankSetup::GetBankSetupById($qery->bank_name);
                                        ?>
                                        <td><?php //echo $salesPerson->username; ?></td>
                                        <td>-</td>
                                        <td><?php echo $qery->payment_type; ?></td>
                                        <td><?php
                                            if ($qery->payment_type == 'party') {
                                                echo 'Party: ' . $qery->party_name . " - " . $qery->cheque_number . "<br>";
                                                echo 'Cheque Details: ' . $qery->cheque_payee_name . " (" . $qery->cheque_bank_name . " - " . date('d-m-Y', strtotime($qery->cheque_date)) . ")";
                                            } else if ($qery->payment_type == 'online') {
                                                echo "From: " . $qery->from_bank_name . "<br>";
                                                echo 'To: ' . $bank->bank_name;
                                            } else {
                                                echo $bank->bank_name;
                                                if ($qery->payment_type == 'bank') {
                                                    echo " - " . $qery->cheque_number . "<br>";
                                                    echo 'Cheque Details: ' . $qery->cheque_payee_name . " (" . $qery->cheque_bank_name . " - " . date('d-m-Y', strtotime($qery->cheque_date)) . ")";
                                                }
                                            } ?></td>
                                        <td><?php echo date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                        <td><?php echo $qery->amount; ?></td>
                                        <td>0</td>
                                        <td><?php echo $balanceAmount; ?></td>
                                    </tr>
                                    <?php
                                }
                            }
                        } ?>
                        <tr>
                            <th colspan="9"
                                style="text-align: right; border: 1px solid #000!important;">Total
                            </th>
                            <th style="border: 1px solid #000!important;"><?= $totalDebitAmount ?>
                                Db
                            </th>
                            <th style="border: 1px solid #000!important;"><?= $totalCreditAmount ?>
                                Cr
                            </th>
                            <th style="border: 1px solid #000!important;"><?= $totalCreditAmount - $totalDebitAmount ?>
                                <?= $totalDebitAmount > $totalCreditAmount ? 'Db' : 'Cr' ?>
                            </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/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>