<?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' ";
if (isset($cat_name) && $cat_name != 'All') {
    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND inv.customer_id ='$customer_name'";
    }else{
        $cat = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
        $filterCat = " WHERE category_id = '$cat->id'";
        $cust = CustomerSetup::GetCustomerSetupList($filterCat);
        $custArray = array();
        foreach($cust AS $custRow){
            $custArray[] = $custRow->id;
        }
        $customers = implode(',', $custArray);
        $filterReport .= " AND inv.customer_id IN (".$customers.")";
    }
}
if (isset($invoice_status) && $invoice_status != 'All') {
    $filterReport .= " AND inv.status = '$invoice_status'";
}else{
    $filterReport .= " AND inv.status not in('Draft', 'Cancel')";
}
$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($cat_name) && $cat_name != 'All') {
    if (isset($customer_name) && $customer_name != 'All') {
        $filterReport .= " AND pay.customer_id ='$customer_name'";
    }else{
        $filterReport .= " AND pay.customer_id IN (".$customers.")";
    }
}

$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' ";

if (isset($cat_name) && $cat_name != 'All') {
    if (isset($customer_name) && $customer_name != 'All') {
        $filterReportOpening .= " AND inv.customer_id ='$customer_name'";
    }else{
        $filterReportOpening .= " AND inv.customer_id IN (".$customers.")";
    }
}
if (isset($invoice_status) && $invoice_status != 'All') {
    $filterReportOpening .= " AND inv.status = '$invoice_status'";
}else{
    $filterReportOpening .= " AND inv.status not in('Draft', 'Cancel')";
}
$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($cat_name) && $cat_name != 'All') {
    if (isset($customer_name) && $customer_name != 'All') {
        $filterReportOpening .= " AND pay.customer_id ='$customer_name'";
    }else{
        $filterReportOpening .= " AND pay.customer_id IN (".$customers.")";
    }
}
$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>Category Customer Ledger 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 s4">Category<br>
                            <?php
                            $catFilter = " JOIN customer_setup ON customer_category.id = customer_setup.category_id GROUP BY catid ORDER BY customer_category.name";
                            $categories = CustomerCategorySetup::GetCustomerCategorySetupList($catFilter);
                            ?>
                            <select class="form-control" required id="cat_name"
                                    name="cat_name">
                                <option>All</option>
                                <?php
                                if ($categories) {
                                    foreach ($categories AS $categoriesRow) {
                                        echo '<option ';
                                        if ($categoriesRow->catid == $cat_name) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $categoriesRow->catid . '" >' . $categoriesRow->catname . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                        <td class="col s4">Customer<br>
                            <?php
                            //$customersfilter = " WHERE status = 'active' AND is_mart = 0";
                            $customersfilter = " WHERE status = 'active' WHERE 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>
                        <td class="col s4">Invoice Status<br>
                            <select class="form-control" required id="invoice_status"
                                    name="invoice_status">
                                <option>All</option>
                                <option value="Paid" <?= ($invoice_status == 'Paid'?'selected':'') ?>>Paid</option>
                                <option value="Pending" <?= ($invoice_status == 'Pending'?'selected':'') ?>>Pending</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'])) {
                $opBalance = 0;
                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>';
                    }
                    $opBalance = $customer->balance;
                }
                ?>
                <div id="floatThead" class="section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>Head</th>
                            <th>Date</th>
                            <th>Invoice / Payment #</th>
                            <th>Customer</th>
                            <th>Status</th>
                            <th>Payment Type</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;
                                }
                            }
                        }

                        $qry = Invoice::GetInvoicePaymentReportLists($filterReport);

                        $customerIds = array();
                        foreach ($qry as $qery) {
                            if (!in_array($qery->customer_id, $customerIds) && $qery->nameTable == 'invoice') {
                                $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                $opBalance += $customer->balance;
                                $customerIds[] = $qery->customer_id;
                            }
                        }
                        $balanceAmount -= $opBalance;
                        $totalCreditAmount += $opBalance;
                        ?>
                        <tr style="border: 1px solid #666;">
                            <td>Opening</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td>-</td>
                            <td><?= $totalDebitAmount ?></td>
                            <td><?= $totalCreditAmount ?></td>
                            <td><?= $balanceAmount ?></td>
                        </tr>
                        <?php
                        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);
                                        ?>
                                        <td><?php echo $qery->code; ?></td>
                                        <td><?php echo $customer->name; ?></td>
                                        <td><?php echo $qery->status; ?></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><?php echo date('Y-m-d h:i A', strtotime($qery->create_date)); ?></td>
                                        <?php
                                        $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                        ?>
                                        <td><?php echo $qery->code; ?></td>
                                        <td><?php echo $customer->name; ?></td>
                                        <td>-</td>
                                        <td><?php echo $qery->payment_type; ?></td>
                                        <td><?php echo $qery->amount; ?></td>
                                        <td>0</td>
                                        <td><?php echo $balanceAmount; ?></td>
                                    </tr>
                                    <?php
                                }
                            }
                        } ?>
                        <tr>
                            <th colspan="6"
                                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 () {
        var catname = $('#cat_name').val();
        var customername = "<?=$customer_name?>";
        if(catname != ''){
            load(catname);
            $('#customer_name').each(function(){
                console.log($(this).val());
                if($(this).val() == parseInt(customername)){
                    console.log("Test "+customername);
                    $(this).attr('selected', true);
                }
            });
            $('#customer_name').trigger('contentChanged');
        }
        function load(data){
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersAll.php?id=' + data, function (data) {
                $("#customer_name").empty();
                $("#customer_name").append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        }
        // initialize
        $('#customer_name').material_select();

        // setup listener for custom event to re-initialize on change
        $('#customer_name').on('contentChanged', function () {
            $(this).material_select();
        });
        $('#cat_name').on('change', function () {
//            $('body.container').block({message: 'Loading...'});
//            $.get('getFilterCustomersAll.php?id=' + $(this).val(), function (data) {
//                $("#customer_name").empty();
//                $("#customer_name").append(data);
//                $('body.container').unblock();
//                $('#customer_name').trigger('contentChanged');
//            });
            load($(this).val());
        });
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/catcustledgprint.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>