<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$category_name = "";
$mainCat = "";
$catName = "";
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 = " AS ex RIGHT JOIN " . TABLE_SUPPLIERSETUP . " AS exCat ON ex.supplier_id = exCat.id WHERE DATE_FORMAT(ex.create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(ex.create_date,'%Y-%m-%d')<='$qryTo' ";

if (isset($category_name) && $category_name != 'All') {
    if (isset($sub_category) && $sub_category != 'All') {
        $filterReport .= " AND ex.supplier_id ='$sub_category'";
    } else {
//        $filterReport .= " AND exCat.parent_id ='$category_name'";
    }
    $filterReport .= " ORDER BY ex.supplier_id";
} else {
//    $filterReport .= " ORDER BY exCat.parent_id";
}
//print_r($filterReport);
//exit;
?>
<!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>Purchase 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">Supplier<br>
                            <?php
                            $categoryfilter = " WHERE parent_id = 0 ORDER BY name";
                            $category = PurchaseCategorySetup::GetPurchaseCategorySetupList($categoryfilter);
                            ?>
                            <select class="form-control" required id="category_name"
                                    name="category_name">
                                <option>All</option>
                                <?php
                                if ($category) {
                                    foreach ($category AS $categoryRow) {
                                        echo '<option ';
                                        if ($categoryRow->id == $category_name) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $categoryRow->id . '" >' . $categoryRow->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                        <td class="col s6">Category<br>
                            <?php
                            $filterSubCategory = " WHERE parent_id = '$category_name' and parent_id <> 0";
                            $subCategory = PurchaseCategorySetup::GetPurchaseCategorySetupList($filterSubCategory);
                            ?>
                            <select class="form-control" required id="sub_category"
                                    name="sub_category">
                                <option>All</option>
                                <?php
                                if ($subCategory) {
                                    foreach ($subCategory AS $subCategoryRow) {
                                        echo '<option ';
                                        if ($subCategoryRow->id == $sub_category) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $subCategoryRow->id . '" >' . $subCategoryRow->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('purchase-<?= date('d-m-Y-h-i-a') ?>.csv')"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Download 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'])) {
                ?>
                <div class="table">
                    <table class="table bordered">
                        <?php
                        $qry = PurchaseSetup::GetPurchaseSetupList($filterReport);
                        if ($category_name == 'All' && $sub_category == 'All') {
                            if ($qry) {
                                $counter = 0;
                                $counterSerial = 0;
                                $amountTotal = 0;
                                $amountSubTotal = 0;
                                foreach ($qry as $qery) {
                                    $exPCategory = SupplierSetup::GetSupplierSetupById($qery->parent_id);
                                    $counter++;
                                    if ($exPCategory->name != $mainCat && $counter != 1) {
                                        echo '<span class="right">' . $amountSubTotal . '</span></th></tr>';
                                    }
                                    if ($catName != $exPCategory->name) {
                                        $amountSubTotal = 0;
                                        $counterSerial = 0;
                                        echo '
<tbody style="border: 1px solid #666;"><tr ><th colspan="4"><span class="left">' . $exPCategory->name . '</span>';
                                    }
                                    $counterSerial++;
                                    $amountSubTotal += $qery->amount;
                                    $amountTotal += $qery->amount;
                                    $catName = $exPCategory->name;
                                    $mainCat = $exPCategory->name;
                                }
                                echo '<span class="right">' . $amountSubTotal . '</span></th></tr>';
                            }
                            //$filterReportPay = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' AND DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND status <> 'Cancel'";
                            //$qrypayment = Purpayment::GetPurpaymentList($filterReportPay);
//                                            $totalPayment = 0;
//                                            if($qrypayment){
//                                                foreach($qrypayment AS $qrypaymentRow){
//                                                    $totalPayment += $qrypaymentRow->amount;
//                                                }
//                                            }
//                                            $amountTotalfinal = $amountTotal- $totalPayment;
                            ?>
                            <tr >
                                <th colspan="3"
                                    style="text-align: right; border: 1px solid #000;">
                                    Total
                                </th>

                                <th style="border: 1px solid #000; text-align: right;"><?= $amountTotal ?></th>
                            </tr>
                            </tbody>
                            <!--                                            <tr>-->
                            <!--                                                <th colspan="3"-->
                            <!--                                                    style="text-align: right; border: 1px solid #000;">-->
                            <!--                                                    Total Payment-->
                            <!--                                                </th>-->
                            <!---->
                            <!--                                                <th style="border: 1px solid #000; text-align: right;">--><? //= $totalPayment ?><!--</th>-->
                            <!--                                            </tr>-->
                            <!--                                            <tr>-->
                            <!--                                                <th colspan="3"-->
                            <!--                                                    style="text-align: right; border: 1px solid #000;">-->
                            <!--                                                    Total-->
                            <!--                                                </th>-->
                            <!---->
                            <!--                                                <th style="border: 1px solid #000; text-align: right;">--><? //= $amountTotalfinal ?><!--</th>-->
                            <!--                                            </tr>-->
                            <?php
                        } else {
                            if ($qry) {
                                $counter = 0;
                                $counterSerial = 0;
                                $amountTotal = 0;
                                $amountSubTotal = 0;
                                foreach ($qry as $qery) {
                                    $counter++;
                                    if ($catName != $qery->name) {
                                        $amountSubTotal = 0;
                                        $counterSerial = 0;
                                        echo '<tbody style="border: 1px solid #666;"><tr style="border:1px solid #666;"><th  style="border-top:1px solid #666;" colspan="5" style="font-size: 16px;">' . $qery->name . '</th></tr>
                                                    <tr >
                                                        <th>S.No</th>
                                                        <th>Date</th>
                                                        <th>Description</th>
                                                        <th style="border-right:1px solid #666;">Amount</th>
                                                    </tr>';
                                    }
                                    $counterSerial++;
                                    ?>
                                    <tr >
                                        <td><?= $counterSerial ?></td>
                                        <td><?php echo date('Y-m-d', strtotime($qery->lastupdated)); ?></td>
                                        <td><?php echo $qery->description; ?></td>
                                        <td style="border-right:1px solid #666;"><?php echo number_format(($qery->amount), 2, '.', ''); ?></td>
                                    </tr>
                                    <?php
                                    $amountSubTotal += $qery->amount;
                                    $amountTotal += $qery->amount;
                                    $catName = $qery->name;
                                    if (isset($qry[$counter]->name) && $qry[$counter]->name != $qery->name && $sub_category == 'All') {
                                        echo '<tr style="border:1px solid #666;"><th colspan="3"></th><th style="border-right:1px solid #666;">' . $amountSubTotal . '</th></tr></tbody><body><tr><td colspan="3"></td></tr></body>';
                                    }
                                }
                                echo '<tr style="border:1px solid #666;"><th colspan="3"></th><th style="border-right:1px solid #666;">' . $amountSubTotal . '</th></tr></tbody><body><tr><td colspan="3"></td></tr></body>';
                                ?>
                                <tr >
                                    <th colspan="3"
                                        style="text-align: right; border: 1px solid #000;">
                                        Total
                                    </th>

                                    <th style="border: 1px solid #000;"><?= $amountTotal ?></th>
                                </tr>
                                <?php
                                /*
                                $filterReportPay = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' AND DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' AND supplier_id = '$category_name' AND status <> 'Cancel'";
                                $qrypayment = Purpayment::GetPurpaymentList($filterReportPay);
                                $totalPayment = 0;
                                if($qrypayment){
                                    $counterSerial = 0;
                                    foreach($qrypayment AS $qrypaymentRow){
                                        $counterSerial++;
                                        $bank_name = BankSetup::GetBankSetupById($qrypaymentRow->bank_name);
                                        if ($counterSerial == 1) {
                                            echo '<tr><th colspan="5">Payments</th></tr>
                                    <tr>
                                        <th>S.No</th>
                                        <th>Date</th>
                                        <th>Description</th>
                                        <th>Amount</th>
                                    </tr>';
                                        }
                                        ?>
                                        <tr>
                                            <td><?= $counterSerial ?></td>
                                            <td><?php echo date('Y-m-d', strtotime($qrypaymentRow->create_date)); ?></td>
                                            <td><?php echo ucwords($qrypaymentRow->payment_type)." - ".$bank_name->bank_name; ?></td>
                                            <td><?php echo number_format(($qrypaymentRow->amount), 2, '.', ''); ?></td>
                                        </tr>
                                        <?php
                                        $totalPayment += $qrypaymentRow->amount;
                                    }
                                ?>
                                <tr>
                                    <th colspan="3"
                                        style="text-align: right; border: 1px solid #000;">
                                        Sub Total
                                    </th>

                                    <th style="border: 1px solid #000;"><?= $totalPayment ?></th>
                                </tr>
                                <?php
                                }
                                $amountTotalfinal = $amountTotal- $totalPayment;
                                */
                            } ?>
                            <!--                                            <tr>-->
                            <!--                                                <th colspan="3"-->
                            <!--                                                    style="text-align: right; border: 1px solid #000;">-->
                            <!--                                                    Total-->
                            <!--                                                </th>-->
                            <!---->
                            <!--                                                <th style="border: 1px solid #000;">--><? //= $amountTotal ?><!--</th>-->
                            <!--                                            </tr>-->
                        <?php } ?>
                    </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="application/javascript">
    $(document).ready(function () {
        // initialize
        $('#sub_category').material_select();
        // setup listener for custom event to re-initialize on change
        $('#sub_category').on('contentChanged', function () {
            $(this).material_select();
        });

        $('#category_name').on('change', function () {
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterPurchaseCat.php?id=' + $(this).val(), function (data) {
                $("#sub_category").empty();
                $("#sub_category").append(data);
                $('body.container').unblock();
                $('#sub_category').trigger('contentChanged');
            });
        });
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/purchase.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, fewSeconds * 1000);
        });
    });
</script>
</body>
</html>