<?php
include("../../classes/manager.class.php");

// Initialize Manager Class
$m = new Manager();

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

// Extract GET parameters safely
$cat_type = isset($_GET['cat_type']) ? $_GET['cat_type'] : 'All';
$status_type = isset($_GET['status_type']) ? $_GET['status_type'] : 'All';

// Initialize Filter Query
$filterReport = "WHERE 1 "; // Ensures the query syntax remains correct

// Filter by `is_mart` condition (Wholesaler, Local Mart, All)
if ($cat_type != 'All') {
    $filterReport .= " AND is_mart = '$cat_type' ";
}

// Filter by `status` condition (Active, Inactive, All)
if ($status_type != 'All') {
    $filterReport .= " AND status = '$status_type' ";
}
?>
<!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 List Report</h3>
            </div>

            <!-- Search Form -->
            <form action="customerlist.php" method="get" name="search" id="searchfrm">
                <input type="hidden" name="view" value="1">  <!-- Ensures data appears after Search -->

                <table class="table">
                    <tr>
                        <td class="col s4">Type<br>
                            <select class="form-control" required id="cat_type" name="cat_type">
                                <option value="All" <?= ($cat_type == 'All') ? 'selected' : '' ?>>All</option>
                                <option value="0" <?= ($cat_type == '0') ? 'selected' : '' ?>>Wholesaler</option>
                                <option value="1" <?= ($cat_type == '1') ? 'selected' : '' ?>>Local Mart</option>
                            </select>
                        </td>

                        <td class="col s4">Status<br>
                            <select class="form-control" required id="status_type" name="status_type">
                                <option value="All" <?= ($status_type == 'All') ? 'selected' : '' ?>>All</option>
                                <option value="active" <?= ($status_type == 'active') ? 'selected' : '' ?>>Active</option>
                                <option value="inactive" <?= ($status_type == 'inactive') ? 'selected' : '' ?>>Inactive</option>
                              	<option value="deleted" <?= ($status_type == 'deleted') ? 'selected' : '' ?>>Deleted</option>
                            </select>
                        </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
                                    onclick="exportTableToCSV('customerlist-<?= 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'])) {
                $qry = CustomerSetup::GetCustomerSetupList($filterReport);

                if ($qry) {
                    echo '<div id="floatThead" class="section">';
                    echo '<table class="striped demo1 bordered">';
                    echo '<thead>
                            <tr style="border: 1px solid #666;">
                                <th>S.No</th>
                                <th>Name</th>
                                <th>Location</th>
                                <th>Status</th>
                            </tr>
                          </thead>
                          <tbody>';

                    $counter = 1;
                    foreach ($qry as $qery) {
                        echo "<tr style='border: 1px solid #666;'>
                                <td>{$counter}</td>
                                <td>{$qery->name}</td>
                                <td>{$qery->location}</td>
                                <td>{$qery->status}</td>
                                
                              </tr>";
                        $counter++;
                    }
                    echo '</tbody></table></div>';
                } else {
                    echo "<p style='text-align: center; color: red;'>No Customers Found</p>";
                }
            }
            ?>
        </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) {
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/customerlist_pdf.php?").submit();

            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, 2000);
        });

        $('table.demo1').floatThead({
            position: 'fixed',
            scrollingTop: 65
        });

        $('table.demo1 thead').css('background', '#ECEFF1');
    });

    // CSV Export Function
    function exportTableToCSV(filename) {
        let csv = [];
        let rows = document.querySelectorAll(".demo1 tr");

        for (let i = 0; i < rows.length; i++) {
            let row = [];
            let cols = rows[i].querySelectorAll("td, th");

            for (let j = 0; j < cols.length; j++)
                row.push(cols[j].innerText);

            csv.push(row.join(","));
        }

        let csvContent = csv.join("\n");
        let blob = new Blob([csvContent], { type: "text/csv" });
        let link = document.createElement("a");

        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>
</body>
</html>
