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

// ---- Date handling ----
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));

// Default values if not set
if (!isset($customer_name)) {
    $customer_name = 'All';
}
if (!isset($cat_name)) {
    $cat_name = 'All';
}

/**
 * Build filter for main invoice query
 * - When specific customer: join invoice_product for qty and group by invoice
 * - When all customers: group by customer only (uses GetInvoiceCustomerReportListMonthlySaleCustomers)
 */
$baseWhere = " 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 ($customer_name != '' && $customer_name != 'All') {

    // DETAIL mode: single customer, join invoice_product for product_qty
    $filterReport  = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust 
                          ON inv.customer_id = cust.id
                       JOIN " . TABLE_INVOICE_PRODUCT . " AS invPr 
                          ON inv.id = invPr.invoice_id ";
    $filterReport .= $baseWhere;

    // Category filter (if selected)
    if ($cat_name != 'All') {
        $filterReport .= " AND cust.category_id = '$cat_name'";
    }

    // Specific customer
    $filterReport .= " AND inv.customer_id = '$customer_name'";

    // Group by invoice (one row per invoice)
    $filterReport .= " GROUP BY inv.code ";

} else {

    // SUMMARY mode: all customers (or all within one category)
    $filterReport  = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust 
                          ON inv.customer_id = cust.id ";
    $filterReport .= $baseWhere;

    // Category filter (if selected)
    if ($cat_name != 'All') {
        $filterReport .= " AND cust.category_id = '$cat_name'";
    }

    // Group by customer
    $filterReport .= " GROUP BY inv.customer_id ";
}

// Final order
$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 Sale 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">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-lg-4">Customer<br>
                            <?php
                            // Initial customer list (can be refined via JS if you already use getFilterCustomersAll.php)
                            $customersfilter = " WHERE status = 'active' ORDER BY name";
                            $customers       = CustomerSetup::GetCustomerSetupList($customersfilter);
                            ?>
                            <select class="form-control" required id="customer_name" name="customer_name">
                                <option value="All">All</option>
                                <?php
                                if ($customers) {
                                    foreach ($customers AS $customersRow) {
                                        echo '<option value="' . $customersRow->id . '" ';
                                        if ($customersRow->id == $customer_name) {
                                            echo 'selected';
                                        }
                                        echo '>' . $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-sale-<?= 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'])) {

                // Optional heading: show category name if filtered
                if ($cat_name != 'All') {
                    $catObj = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
                    if (!empty($catObj)) {
                        echo '<table style="width: 100%;"><tr><th style="text-align: center;">';
                        echo "<h4 style='text-align: center;'>" . $catObj->name . " - Category</h4>";
                        echo '</th></tr></table>';
                    }
                }

                // Heading for specific customer
                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 Invoice</th>
                            <?php } else { ?>
                                <th>Date</th>
                                <th>Invoice #</th>
                                <th>Qty</th>
                            <?php } ?>
                            <th>Sale Price</th>
                            <?php if ((PROJECT_DISCOUNT == 1 || !empty($discount_price))) { ?>
                                <th>Discount</th>
                            <?php } ?>
                            <th>Total</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        if ($customer_name != '' && $customer_name != 'All') {

                            // DETAIL: one customer, multiple invoices
                            $qry = Invoice::GetInvoiceCustomerReportListMonthlySale($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->product_qty; ?></td>
                                        <td><?php echo number_format(($qery->total_amount + $qery->discount_price), 2, '.', ''); ?></td>
                                        <td><?php echo number_format(($qery->discount_price), 2, '.', ''); ?></td>
                                        <td><?php echo number_format($qery->total_amount, 2, '.', ''); ?></td>
                                    </tr>
                                    <?php
                                    $productQtyTotal += $qery->product_qty;
                                    $unitPriceTotal  += ($qery->total_amount + $qery->discount_price);
                                    $totalDiscount   += $qery->discount_price;
                                    $totalProfit     += $qery->total_amount;
                                }
                            }

                        } else {

                            // SUMMARY: per customer (optionally filtered by category)
                            $qry = Invoice::GetInvoiceCustomerReportListMonthlySaleCustomers($filterReport);
                            $counter = 0;
                            if ($qry) {
                                foreach ($qry as $qery) {
                                    $counter++;
                                    $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);
                                    ?>
                                    <tr style="border: 1px solid #666;">
                                        <td><?= $counter ?></td>
                                        <td>
                                            <a target="_blank"
                                               href="/salesnew/admin/report/monthly_sale.php?datefrom=<?= $datefrom ?>&view=&dateto=<?= $dateto ?>&cat_name=<?= $cat_name ?>&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 + $qery->discount_price), 2, '.', ''); ?></td>
                                        <td><?php echo number_format(($qery->discount_price), 2, '.', ''); ?></td>
                                        <td><?php echo number_format($qery->total_amount, 2, '.', ''); ?></td>
                                    </tr>
                                    <?php
                                    $unitPriceTotal += ($qery->total_amount + $qery->discount_price);
                                    $totalDiscount   += $qery->discount_price;
                                    $totalProfit     += $qery->total_amount;
                                }
                            }
                        }
                        ?>
                        <tr>
                            <?php
                            // Colspan for "Total" label
                            if ($customer_name == '' || $customer_name == 'All') {
                                $num = 3;
                            } else {
                                $num = 3;
                            }
                            ?>
                            <th colspan="<?= $num ?>" style="text-align: right; border: 1px solid #000;">
                                Total
                            </th>
                            <?php if ($customer_name != '' && $customer_name != 'All') {  ?>
                                <th style="border: 1px solid #000;"><?= $productQtyTotal ?></th>
                            <?php } ?>
                            <th style="border: 1px solid #000;"><?= $unitPriceTotal ?></th>
                            <?php if ((PROJECT_DISCOUNT == 1 || $discount_price != 0)) { ?>
                                <th style="border: 1px solid #000;"><?= number_format(($totalDiscount), 2, '.', '') ?></th>
                            <?php } ?>
                            <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_sale.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');

        // OPTIONAL: if you already use getFilterCustomersAll.php in other reports,
        // you can uncomment this block to make customer dropdown dependent on category

        function loadCustomers(catId, selectedCustomer) {
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersAll.php?id=' + catId + '&cus_id=' + selectedCustomer, function (data) {
                $("#customer_name").empty().append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        }

        $('#customer_name').material_select();
        $('#customer_name').on('contentChanged', function () {
            $(this).material_select();
        });

        $('#cat_name').on('change', function () {
            var catId = $(this).val();
            var currentCustomer = 0; // reset on change
            if (catId !== '') {
                loadCustomers(catId, currentCustomer);
            }
        });

        // On first load, if a category is selected, reload customers for it
        var initialCat = '<?= $cat_name ?>';
        var initialCustomer = '<?= $customer_name ?>';
        if (initialCat !== 'All') {
            loadCustomers(initialCat, initialCustomer);
        }
    });
</script>
</body>
</html>
