<?php
include("../../classes/manager.class.php");
$m = new Manager();

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

$monthfrom = "";
$monthto   = "";

extract($_REQUEST);

// ✅ Defaults: last 6 months
if ($monthfrom == "") {
    $monthfrom = date('Y-m-01', strtotime("-5 months"));
} else {
    $monthfrom = date("Y-m-01", strtotime($monthfrom));
}

if ($monthto == "") {
    $monthto = date('Y-m-01');
} else {
    $monthto = date("Y-m-01", strtotime($monthto));
}

// ✅ Display for inputs
$monthfrom_display = date("d-m-Y", strtotime($monthfrom));
$monthto_display   = date("d-m-Y", strtotime($monthto));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>

<div id="container">
    <?php include('../includes/inc_top.php'); ?>

    <div class="row">
        <div class="col s12 m12">

            <div class="">
                <h3>Customer Monthly Comparison 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">
                            Month From<br>
                            <input type="text" name="monthfrom" id="datepicker"
                                   placeholder="Month From"
                                   value="<?= $monthfrom_display ?>" class="form-control"/>
                            <input type="hidden" name="view" value="1"/>
                        </td>

                        <td class="col-lg-4">
                            Month To<br>
                            <input type="text" name="monthto" id="datepicker1"
                                   placeholder="Month To"
                                   value="<?= $monthto_display ?>" class="form-control"/>
                        </td>
                    </tr>

                    <tr>
                        <td colspan="2" class="col-lg-4">
                            <button type="submit" class="btn waves-effect waves-light" style="float:left;">
                                View Report
                            </button>

                            <?php if (isset($_GET['view'])) { ?>
                                <button type="button"
                                        onclick="exportTableToCSV('monthly-comparison-<?= 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'])) {

                // ✅ Convert display dates into proper range for function
                $fromDate = date("Y-m-01", strtotime($monthfrom));
                $toDate   = date("Y-m-01", strtotime($monthto));

                $result = Invoice::GetCustomerMonthlyComparisonReport($fromDate, $toDate);

                $months = [];
                $rows   = [];

                if ($result) {
                    $months = $result["months"];
                    $rows   = $result["rows"];
                }

                // ✅ Totals setup
                $monthTotals = [];
                foreach ($months as $mth) {
                    $monthTotals[$mth] = 0;
                }

                $grandTotalInvoices = 0;
                $grandTotalAmount = 0;

                // For overall Avg Repeat Days
                $repeatDaysSum = 0;
                $repeatDaysCount = 0;
                ?>

                <div id="floatThead" class="adv-table section">
                    <table class="striped demo1 bordered">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th>Customer Name</th>

                            <?php foreach ($months as $mth) { ?>
                                <th><?= date("M Y", strtotime($mth . "-01")) ?></th>
                            <?php } ?>

                            <th>Total Invoices</th>
                            <th>Avg Order Value</th>
                            <th>Avg Repeat Days</th>
                            <th>Total Amount</th>
                        </tr>
                        </thead>

                        <tbody>
                        <?php
                        $counter = 0;
                        if ($rows) {
                            foreach ($rows as $r) {
                                $counter++;

                                $grandTotalInvoices += (int)$r->total_invoices;
                                $grandTotalAmount += (float)$r->total_amount;

                                if ((float)$r->avg_repeat_days > 0) {
                                    $repeatDaysSum += (float)$r->avg_repeat_days;
                                    $repeatDaysCount++;
                                }
                                ?>
                                <tr style="border: 1px solid #666;">
                                    <td><?= $counter ?></td>
                                    <td><?= $r->customer_name ?></td>

                                    <?php foreach ($months as $mth) {
                                        $col = "cnt_" . str_replace("-", "_", $mth);
                                        $val = isset($r->$col) ? (int)$r->$col : 0;
                                        $monthTotals[$mth] += $val;
                                        ?>
                                        <td style="text-align:center;"><?= $val ?></td>
                                    <?php } ?>

                                    <td style="text-align:center;"><?= (int)$r->total_invoices ?></td>
                                    <td style="text-align:right;"><?= number_format($r->avg_order_value, 2, '.', '') ?></td>
                                    <td style="text-align:center;"><?= number_format($r->avg_repeat_days, 2, '.', '') ?></td>
                                    <td style="text-align:right;"><?= number_format($r->total_amount, 2, '.', '') ?></td>
                                </tr>
                                <?php
                            }

                            // ✅ Overall Avg Order Value (Grand)
                            $overallAvgOrderValue = ($grandTotalInvoices > 0) ? ($grandTotalAmount / $grandTotalInvoices) : 0;

                            // ✅ Overall Avg Repeat Days (Only customers having repeat days > 0)
                            $overallAvgRepeatDays = ($repeatDaysCount > 0) ? ($repeatDaysSum / $repeatDaysCount) : 0;

                            ?>
                            <tr>
                                <th colspan="2" style="text-align:right; border:1px solid #000;">TOTAL</th>

                                <?php foreach ($months as $mth) { ?>
                                    <th style="border:1px solid #000; text-align:center;">
                                        <?= $monthTotals[$mth] ?>
                                    </th>
                                <?php } ?>

                                <th style="border:1px solid #000; text-align:center;">
                                    <?= $grandTotalInvoices ?>
                                </th>

                                <th style="border:1px solid #000; text-align:right;">
                                    <?= number_format($overallAvgOrderValue, 2, '.', '') ?>
                                </th>

                                <th style="border:1px solid #000; text-align:center;">
                                    <?= number_format($overallAvgRepeatDays, 2, '.', '') ?>
                                </th>

                                <th style="border:1px solid #000; text-align:right;">
                                    <?= number_format($grandTotalAmount, 2, '.', '') ?>
                                </th>
                            </tr>
                            <?php

                        } else {
                            ?>
                            <tr>
                                <td colspan="<?= 6 + count($months) ?>" style="text-align:center; padding: 12px;">
                                    No record found.
                                </td>
                            </tr>
                            <?php
                        }
                        ?>
                        </tbody>

                    </table>
                </div>

            <?php } ?>

        </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="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/customer_monthly_comparison.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>
