<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();

$output = '';
$datefrom = "";
$dateto = "";
$category_id = "All";
$totalGrand = 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));

// Categories
$catList = $db->fetch_all_array("SELECT id, name FROM customer_category WHERE (status='active' OR status='Active') ORDER BY name ASC");
if (!$catList) { $catList = array(); }

// Filter (same pattern as monthly_sale customer-summary view)
$filterReport = " JOIN " . TABLE_CUSTOMERSETUP . " AS cust ON inv.customer_id = cust.id
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($category_id) && $category_id != '' && $category_id != 'All') {
    $filterReport .= " AND cust.category_id ='$category_id' ";
}
$filterReport .= " GROUP BY inv.customer_id ";
// (NO ORDER BY here — your method already orders by slab)

// Fetch
$qry = false;
if (isset($_GET['view'])) {
    $qry = Invoice::GetCustomerSalesSegregationReport($filterReport);
}

// Slabs
$bucketOrder = array(
    'Up to 10,000',
    '10,001 to 20,000',
    '20,001 to 30,000',
    '30,001 to 50,000',
    '50,001 to 100,000',
    '100,001 to 200,000',
    '200,001 to 300,000',
    '300,001 to 400,000',
    '400,001 to 500,000',
    'Above 500,000'
);

// Grouping
$bucketed = array();
foreach ($bucketOrder as $b) { $bucketed[$b] = array(); }

if ($qry) {
    foreach ($qry as $r) {
        $slab = $r->sales_slab;
        if (!isset($bucketed[$slab])) $bucketed[$slab] = array();
        $bucketed[$slab][] = $r;
        $totalGrand += (float)$r->total_amount;
    }
}

// Category title
$catTitle = "";
if (isset($_GET['view']) && isset($category_id) && $category_id != '' && $category_id != 'All') {
    $row = $db->query_first("SELECT name FROM customer_category WHERE id='$category_id' LIMIT 1");
    if (!empty($row->name)) { $catTitle = $row->name; }
}
?>
<!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>Customer Sales Segregation 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">Customer Category<br>
                            <select class="form-control" required id="category_id" name="category_id">
                                <option>All</option>
                                <?php
                                if (!empty($catList)) {
                                    foreach ($catList as $cat) {
                                        $cid   = is_object($cat) ? $cat->id : $cat['id'];
                                        $cname = is_object($cat) ? $cat->name : $cat['name'];

                                        echo '<option ';
                                        if ((string)$cid === (string)$category_id) echo 'selected';
                                        echo ' value="' . $cid . '" >' . $cname . '</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('customer-sales-seg-<?= 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'])) { ?>

                <?php if ($catTitle != "") { ?>
                    <table style="width: 100%;"><tr><th style="text-align: center;">
                        <h2 style="text-align: center;"><?= $catTitle ?></h2>
                    </th></tr></table>
                <?php } ?>

                <div id="floatThead" class="adv-table section">

                    <table class="striped bordered" style="margin-bottom: 20px;">
                        <tbody>
                        <tr style="border: 1px solid #666;">
                            <th style="border: 1px solid #666;">Date From</th>
                            <td style="border: 1px solid #666;"><?= $datefrom ?></td>
                            <th style="border: 1px solid #666;">Date To</th>
                            <td style="border: 1px solid #666;"><?= $dateto ?></td>
                            <th style="border: 1px solid #666; text-align:right;">Grand Total</th>
                            <td style="border: 1px solid #666; text-align:right; font-weight:600;">
                                <?= number_format($totalGrand, 2, '.', '') ?>
                            </td>
                        </tr>
                        </tbody>
                    </table>

                    <?php foreach ($bucketOrder as $bucketName) {

                        $list = $bucketed[$bucketName];
                        $bucketTotal = 0;
                        foreach ($list as $x) { $bucketTotal += (float)$x->total_amount; }
                        ?>

                        <table style="width: 100%; margin-top: 25px;">
                            <tr>
                                <th style="text-align: left;">
                                    <h5 style="margin: 0;"><?= $bucketName ?></h5>
                                    <span style="font-size: 14px; font-weight: normal;">
                                        Customers: <?= count($list) ?> |
                                        Bucket Total: <?= number_format($bucketTotal, 2, '.', '') ?>
                                    </span>
                                </th>
                            </tr>
                        </table>

                        <table class="striped demo1 bordered">
                            <thead>
                            <tr style="border: 1px solid #666;">
                                <th>S.No</th>
                                <th>Customer</th>
                                <th>No. of Invoice</th>
                                <th>Location</th>
                                <th>Contact</th>
                               
                                <th style="text-align:right;">Total</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
                            if (!empty($list)) {
                                $counter = 0;
                                foreach ($list as $r) {
                                    $counter++;
                                    ?>
                                    <tr style="border: 1px solid #666;">
                                        <td><?= $counter ?></td>
                                        <td><?= $r->customer_name ?></td>
                                        <td><?= (int)$r->total_invoices ?></td>
                                        <td><?= $r->location ?></td>
                                        <td><?= $r->contact ?></td>
                                       
                                        <td style="text-align:right;"><?= number_format($r->total_amount, 2, '.', '') ?></td>
                                    </tr>
                                    <?php
                                }
                            } else {
                                echo '<tr><td colspan="8" style="text-align:center; border:1px solid #666;">No Record</td></tr>';
                            }
                            ?>

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

                            </tbody>
                        </table>

                    <?php } ?>

                </div>
            <?php } ?>

        </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 () {

        // Keep same print behavior (print file can be added later)
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/customer_sales_segregation.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>
