{{>header}}

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <link rel="icon" href="/admin/images/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
    {{!--
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> --}}
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: 'Source Sans Pro', sans-serif;
            background-color: #f4f6f9;
        }

        .row {
            margin: 0;
        }

        .col-lg-3 {
            margin-bottom: 20px;
        }

        @media (max-width: 767px) {
            .small-box {
                height: 200px;
            }
        }

        .custom-box {
            position: relative;
            background: #f1eded9b;
            padding: 20px;
            border-radius: 16px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.07);
            transition: all 0.4s ease-in-out;
            height: 130px;
            overflow: hidden;
        }

        .custom-box:hover {
            transform: translateY(-4px) scale(1.02);
            background: linear-gradient(135deg, #4B0F77, #2D0948);
            /* green gradient */
        }

        .custom-box:hover .icon {
            color: #ffffff;
        }

        .custom-box .icon {
            position: absolute;
            top: 12px;
            right: 12px;
            font-size: 44px;
            color: #4B0F77;
            opacity: 0.8;
            transition: color 0.4s ease-in-out;
        }

        .custom-box .inner h3 {
            font-size: 28px;
            margin: 0;
            font-weight: 700;
            transition: color 0.4s ease-in-out;
        }

        .custom-box .inner h5 {
            font-size: 16px;
            margin-top: 8px;
            font-weight: 600;
            color: #333;
            transition: color 0.4s ease-in-out;
        }

        .custom-box:hover span,
        .custom-box:hover .inner h3,
        .custom-box:hover .inner h5 {
            color: #ffffff;
        }

        .filter-btn {
            border-color: #4B0F77;
            color: #4B0F77;
        }

        .filter-btn:hover {
            background-color: #4B0F77 !important;
            color: white !important;
            border-color: #4B0F77 !important;
        }

        .filter-btn.active {
            background-color: #4B0F77 !important;
            color: white !important;
            border-color: #4B0F77 !important;
        }

        .lower-knob {
            margin-top: 100px;
        }
     /*.count {
    display: inline-block;
    transform-origin: center;
    animation: bounceIn 0.6s ease forwards;
} */

.count {
    display: inline-block;
    transform-origin: center;
}

/*@keyframes bounceIn {
    0% { transform: scale(0.3) rotateY(0deg); opacity: 0; }
    50% { transform: scale(1.2) rotateY(180deg); opacity: 1; }
    70% { transform: scale(0.9) rotateY(270deg); }
    100% { transform: scale(1) rotateY(360deg); }
}*/
/*knob style*/
.dashboard-card {
    background-color: #ffffff !important;
}
.products-title {
    font-size: 22px;
    letter-spacing: 0.5px;
}

    </style>
</head>

<body>
    <div class="container my-4">
        <div class="row">
            <div class="row">
                <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/v1/allVendors" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                            <div class="icon">
                                <i class="fas fa-store"></i>
                            </div>
                            <div class="inner">
                                <h3  class="count" data-target="{{activeStores}}">0</h3>
                                <h5><b>Active Communities</b></h5>
                            </div>
                            <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                        </div>
                    </a>
                </div>
                <!-- Inactive Stores -->
                <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/v1/allVendors" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                            <div class="icon">
                                <i class="fas fa-store-slash"></i>
                            </div>
                            <div class="inner">
                                <h3 class="count" data-target="{{inactiveStores}}">0</h3>
                                <h5><b>Inactive Communities</b></h5>
                            </div>
                            <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                        </div>
                    </a>
                </div>
                 <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/v1/allorders" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                        <div class="icon">
                            <i class="fas fa-shopping-cart"></i>
                        </div>
                        <div class="inner">
                            <h3 class="count" data-target="{{allOrders}}">0</h3>
                            <h5><b>Total Orders</b></h5>
                        </div>
                        <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                    </div>
                    </a>
                </div>
                <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/v1/allorders" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                        <div class="icon">
                            <i class="fas fa-shopping-cart"></i>
                        </div>
                        <div class="inner">
                            <h3 class="count" data-target="{{pendingOrders}}">0</h3>
                            <h5><b>Pending Orders</b></h5>
                        </div>
                        <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                    </div>
                    </a>
                </div>
                <!-- Food Products -->
                {{!-- <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/allProducts" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                            <div class="icon">
                                <i class="fas fa-utensils"></i>
                            </div>
                            <div class="inner">
                                <h3 class="count" data-target="{{foodCategoryProducts}}">0</h3>
                                <h5><b>Food Products</b></h5>
                            </div>
                            <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                        </div>
                    </a>
                </div> --}}
                <!-- Food Revenue -->
                {{!-- <div class="col-lg-3 col-6 mb-4">
                    <a href="#revenueGraph" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                        <div class="icon">
                            <i class="fas fa-wallet"></i>
                        </div>
                        <div class="inner">
                            <h3 id="foodRevenue" class="count revenue-count" data-target="{{foodRevenue}}">₹0</h3>
                            <h5><b>Food Revenue</b></h5>
                        </div>
                        <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                    </div>
                    </a>
                </div> --}}
            </div>
            <div class="row">
                <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/v1/allProducts" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                            <div class="icon">
                                <i class="fas fa-shopping-basket"></i>
                            </div>
                            <div class="inner">
                                <h3 class="count" data-target="{{groceryCategoryProducts}}">0</h3>
                                <h5><b> Products</b></h5>
                            </div>
                            <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                        </div>
                    </a>
                </div>
                <div class="col-lg-3 col-6 mb-4">
                    <a href="#revenueGraph" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                        <div class="icon">
                            <i class="fas fa-coins"></i>
                        </div>
                        <div class="inner">
                            <h3 id="groceryRevenue" class="count revenue-count" data-target="{{revenue}}">0</h3>
                            <h5><b> Revenue</b></h5>
                        </div>
                        <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                    </div>
                    </a>
                </div>
                {{!-- <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/allProducts" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                            <div class="icon">
                                <i class="fas fa-tag"></i>
                            </div>
                            <div class="inner">
                                <h3 class="count" data-target="{{ecommerceCategoryProducts}}">0</h3>
                                <h5><b>Ecommerce Products</b></h5>
                            </div>
                            <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                        </div>
                    </a>
                </div> --}}
                {{!-- <div class="col-lg-3 col-6 mb-4">
                    <a href="#revenueGraph" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                        <div class="icon">
                            <i class="fas fa-briefcase"></i>
                        </div>
                        <div class="inner">
                            <h3 id="ecomRevenue" class="count revenue-count" data-target="{{ecommerceRevenue}}">₹0</h3>
                            <h5><b>Ecommerce Revenue</b></h5>
                        </div>
                        <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                    </div>
                    </a>
                </div> --}}
                <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/v1/allUsers" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                        <div class="icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="inner">
                            <h3 class="count" data-target="{{activeUsers}}">0</h3>
                            <h5><b>Active Users</b></h5>
                        </div>
                        <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                    </div>
                    </a>
                </div>
                <div class="col-lg-3 col-6 mb-4">
                    <a href="/admin/v1/allUsers" style="text-decoration: none; color: inherit;">
                        <div class="custom-box position-relative">
                        <div class="icon">
                            <i class="fas fa-users-slash"></i>
                        </div>
                        <div class="inner">
                            <h3 class="count" data-target="{{inactiveUsers}}">0</h3>
                            <h5><b>Inactive Users</b></h5>
                        </div>
                        <span class="btn btn-sm position-absolute bottom-0 end-0 m-2">
                                See More
                            </span>
                    </div>
                    </a>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="card p-3 shadow-sm">
                        <h5><strong>Recent Orders</strong></h5>
                        <a href="/admin/v1/allorders" class="text-success"
                            style="position: absolute; top: 15px; right: 20px;" title="View All Orders">
                            <i class="fa-solid fa-arrow-up-right-from-square"
                                style="font-size: 1.2rem; color:#4B0F77;"></i>
                        </a>
                        </h5>
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th>Order ID</th>
                                        {{!-- <th>Date</th> --}}
                                        <th>Customer</th>
                                        {{!-- <th>Category</th> --}}
                                        <th>Payment</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {{#each recentOrders}}
                                    <tr>
                                        <td>#{{this.orderId}}</td>
                                        {{!-- <td style="white-space: nowrap;">{{formatDate1 this.createdAt}}</td> --}}
                                        <td>{{this.firstName}}</td>
                                        {{!-- <td>{{this.category}}</td> --}}
                                        <td>{{this.paymentType}}</td>
                                        <td>₹{{toFixed this.amount 2}}</td>
                                        <td>{{this.status}}</td>
                                    </tr>
                                    {{/each}}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                {{#if lowStockProducts}}
                <div class="col-md-6">
                    <div class="card p-3 shadow-sm">
                        <h5><strong>Inventory Management</strong></h5><br>
                        {{#each lowStockProducts}}
                        <div class="d-flex align-items-center mb-3 border-bottom pb-2">
                            <div style="width: 30%;">
                                <strong>Product Name</strong><br> {{this.productName}}
                            </div>
                            <div style="width: 20%;">
                                <strong>Price</strong><br> ₹{{this.price}}
                            </div>
                            <div style="width: 20%;">
                                <strong>Stock</strong><br> {{this.stock}}
                            </div>
                            <div style="width: 30%;">
                                <button class="btn btn-success ms-3" data-bs-toggle="modal"
                                    data-bs-target="#updateStockModal-{{this._id}}"
                                    style="background-color: #4B0F77; color: #f4f6f9;">
                                    + Add Stock
                                </button>
                            </div>
                        </div>
                        <!-- Stock Update Modal -->
                        <div class="modal fade" id="updateStockModal-{{this._id}}" tabindex="-1"
                            aria-labelledby="modalLabel-{{this._id}}" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <form action="/admin/v1/updatestock/{{this._id}}" method="POST">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="modalLabel-{{this._id}}"><b>Update Stock</b>
                                            </h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                                aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="mb-3">
                                                <label class="form-label">Vendor Name</label>
                                                <input type="text" class="form-control"
                                                    value="{{this.vendorInfo.vendorName}}" readonly>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Community Name</label>
                                                <input type="text" class="form-control"
                                                    value="{{this.vendorInfo.communityName}}" readonly>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Product Name</label>
                                                <input type="text" class="form-control" value="{{this.productName}}"
                                                    readonly>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Product Price</label>
                                                <input type="text" class="form-control" value="₹{{this.price}}"
                                                    readonly>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Stock Alert</label>
                                                <input type="number" class="form-control" name="stockAlert" min="0"
                                                    max="999" value="{{this.stockAlert}}"
                                                    data-original="{{this.stockAlert}}">
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Current Stock</label>
                                                <input type="number" class="form-control" name="stock"
                                                    value="{{this.stock}}" data-original="{{this.stock}}" min="0"
                                                    max="999" required>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary"
                                                data-bs-dismiss="modal">Cancel</button>
                                            <button type="submit" class="btn btn-success"
                                                style="background-color: #4B0F77;">Update</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        {{/each}}
                    </div>
                </div>
                {{/if}}
            </div>
            <div class="row" id="revenueGraph">
                <div class="col-12"> <!-- Ensures full width across row -->
                    <div class="card p-3 shadow-sm">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5><strong>Total Revenue: <span id="totalRevenue">₹0</span></strong></h5>
                            <div class="btn-group">
                                <button class="btn btn-outline-success filter-btn active" id="daily"
                                    onclick="updateChart('daily')">Daily</button>
                                <button class="btn btn-outline-success filter-btn" id="weekly"
                                    onclick="updateChart('weekly')">Weekly</button>
                                <button class="btn btn-outline-success filter-btn" id="monthly"
                                    onclick="updateChart('monthly')">Monthly</button>
                            </div>
                        </div>
                        <div style="position: relative; height: 300px;">
                            <canvas id="revenueChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                {{!-- <div class="col-md-6 ">
    <div class="card  shadow-sm text-center h-100">
        <div class="card-body dashboard-card d-flex flex-column justify-content-center align-items-center">

            <input type="text"
                   class="knob grocery-knob"
                   value="{{groceryCategoryProducts}}"
                   data-width="150"
                   data-height="150"
                   data-thickness="0.35"
                   data-fgColor="#e74c3c"
                   data-bgColor="#f1f1f1"
                   data-readOnly="true">

            <h6 class="mt-3 mb-1 fw-bold products-title">Products</h6>

        </div>
    </div>
</div> --}}

                <div class="col-md-6">
                    <div class="card p-3 shadow-sm">
                          <h1 style="text-align: center; color:black; font-weight:bold">Send Notifications</h1>
                    <form action="/admin/v1/sendnotifications" id="notificationForm" method="post" onsubmit="changeButtonState()">
                    <div class="mb-3">
                            <label for="title" class="form-label">Send Notifications To:</label>
                            <select name="type" class="form-control" required> 
                                <option value="users">Users</option>
                                <option value="vendors">Vendors</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="title" class="form-label">Title:</label>
                            <input type="text" id="title" name="title" class="form-control" placeholder="Enter title here" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">Description:</label>
                            <textarea id="body" name="body" class="form-control" minlength="5" rows="4" placeholder="Enter description here" required></textarea>
                        </div>
                        <div class="w-100"  style="display: flex; justify-content:center;">
                            <button type="submit" id="notificationBtn" class="btn btn-primary" style="background-color:#4B0F77; border-color:#4B0F77; width:11em">Send</button>
                        </div>
                    </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
{{!-- <script>
    // These values come from your backend
    const foodRevenue = {{{ foodRevenue }}};
    console.log(foodRevenue);
    const groceryRevenue = {{groceryRevenue}};
    const ecomRevenue = {{{ecomRevenue}}};

    function formatRevenue(value) {
        if (parseFloat(value) >= 10000000) { // crore
            return (value / 10000000).toFixed(2) + "Cr";
        } else if (value >= 100000) { // lakh
            return (value / 100000).toFixed(2) + "L";
        } else if (parseInt(value) >= 1000) { // thousand
            return (value / 1000).toFixed(2) + "K";
        }
        return value.toFixed(2);
    }

    document.getElementById("foodRevenue").innerText = "₹" + formatRevenue(foodRevenue);
    document.getElementById("groceryRevenue").innerText = "₹" + formatRevenue(groceryRevenue);
    document.getElementById("ecomRevenue").innerText = "₹" + formatRevenue(ecomRevenue);
</script> --}}

<script>
document.addEventListener("DOMContentLoaded", () => {
    const counters = document.querySelectorAll('.count');

    counters.forEach(counter => {
        const target = parseInt(counter.getAttribute('data-target'), 10);
        const isRevenue = counter.classList.contains("revenue-count");
        if (isNaN(target)) return;

        const duration = 3000;
        let startTime = null;

        const easeOut = t => 1 - Math.pow(1 - t, 3);

        const formatRevenue = (value, isRevenue) => {
            if (isRevenue) {
                if (value >= 10000000) return "₹" + (value / 10000000).toFixed(2) + " Cr";
                if (value >= 100000) return "₹" + (value / 100000).toFixed(2) + " L";
                if (value >= 1000) return "₹" + (value / 1000).toFixed(2) + " K";
                return "₹" + value.toLocaleString("en-IN");
            }
            return value.toLocaleString("en-IN"); // normal counters
        };

        const updateCount = (timestamp) => {
            if (!startTime) startTime = timestamp;
            const elapsed = timestamp - startTime;
            const progress = Math.min(elapsed / duration, 1);

            const currentValue = Math.floor(target * easeOut(progress));

            counter.textContent = formatRevenue(currentValue, isRevenue);

            if (progress < 1) {
                requestAnimationFrame(updateCount);
            } else {
                counter.textContent = formatRevenue(target, isRevenue);
            }
        };

        requestAnimationFrame(updateCount);
    });
});
</script>


<script>
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('hidden.bs.modal', function () {
            const stockAlertInput = modal.querySelector('input[name="stockAlert"]');
            const stockInput = modal.querySelector('input[name="stock"]');


            if (stockAlertInput) {
                stockAlertInput.value = stockAlertInput.getAttribute('data-original');
            }

            if (stockInput) {
                stockInput.value = stockInput.getAttribute('data-original');
            }
        });
    });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-knob-chif@1.2.13/dist/jquery.knob.min.js"></script>
<script>
    $(document).ready(function () {
        $(".knob").each(function () {
            const $this = $(this);
            const value = parseInt($this.val(), 10) || 0;
            const max = Math.max(100, Math.ceil(value / 100) * 100);
            $this.attr("data-max", max);
        });
        // Initialize knobs after setting max
        $(".knob").knob();
    });
</script>
<script>
    const rawDaily = {{{ dailySalesJSON }}};

    // 🔧 Helper functions
    const getMonthKey = (dateStr) => {
        const d = new Date(dateStr);
        return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}`;
    };

    const getWeekKey = (dateStr) => {
        const d = new Date(dateStr);
        const janFirst = new Date(d.getFullYear(), 0, 1);
        const week = Math.ceil((((d - janFirst) / 86400000) + janFirst.getDay() + 1) / 7);
        return `${d.getFullYear()}-W${week.toString().padStart(2, '0')}`;
    };

    const groupByKey = (data, keyFn) => {
        const result = {};
        data.forEach(item => {
            const key = keyFn(item._id);
            result[key] = (result[key] || 0) + item.totalAmount;
        });
        return result;
    };

    const fillMissingKeys = (keys, map) => {
        const result = {};
        keys.forEach(key => {
            result[key] = map[key] || 0;
        });
        return result;
    };

    const getDateRange = (start, end) => {
        const dates = [];
        let current = new Date(start);
        while (current <= end) {
            dates.push(new Date(current));
            current.setDate(current.getDate() + 1);
        }
        return dates;
    };

    const getWeekRange = (start, end) => {
        const weeks = new Set();
        let current = new Date(start);
        while (current <= end) {
            weeks.add(getWeekKey(current.toISOString()));
            current.setDate(current.getDate() + 1);
        }
        return Array.from(weeks);
    };

    const getMonthRange = (start, end) => {
        const months = [];
        const current = new Date(start.getFullYear(), start.getMonth(), 1);
        while (current <= end) {
            months.push(getMonthKey(current.toISOString()));
            current.setMonth(current.getMonth() + 1);
        }
        return months;
    };

    //  Define date boundaries
    const today = new Date();
    const daysAgo = (n) => new Date(today.getFullYear(), today.getMonth(), today.getDate() - n);
    const weeksAgo = (n) => new Date(today.getFullYear(), today.getMonth(), today.getDate() - (n * 7));
    const monthsAgo = (n) => new Date(today.getFullYear(), today.getMonth() - n, 1);

    const rawDailyLast7Days = rawDaily.filter(d => new Date(d._id) >= daysAgo(6));
    const rawDailyLast6Weeks = rawDaily.filter(d => new Date(d._id) >= weeksAgo(5));
    const rawDailyLast6Months = rawDaily.filter(d => new Date(d._id) >= monthsAgo(5));

    //  Daily Data (last 7 days)
    const dailyMin = daysAgo(6);
    const dailyMax = today;
    const allDailyKeys = getDateRange(dailyMin, dailyMax).map(d =>
        d.toLocaleDateString('en-IN', { month: 'short', day: 'numeric' })
    );
    const fullDailyMap = {};
    rawDailyLast7Days.forEach(item => {
        const label = new Date(item._id).toLocaleDateString('en-IN', { month: 'short', day: 'numeric' });
        fullDailyMap[label] = (fullDailyMap[label] || 0) + item.totalAmount;
    });
    const dailyData = {
        labels: allDailyKeys,
        values: allDailyKeys.map(label => fullDailyMap[label] || 0),
        total: Object.values(fullDailyMap).reduce((a, b) => a + b, 0)
    };

    //  Weekly Data (last 6 weeks)
    const weeklyMap = groupByKey(rawDailyLast6Weeks, getWeekKey);
    const fullWeeklyKeys = getWeekRange(weeksAgo(5), today);
    const fullWeeklyMap = fillMissingKeys(fullWeeklyKeys, weeklyMap);
    const weeklyData = {
        labels: Object.keys(fullWeeklyMap),
        values: Object.values(fullWeeklyMap),
        total: Object.values(fullWeeklyMap).reduce((a, b) => a + b, 0)
    };

    //  Monthly Data (last 6 months)
    const monthlyMap = groupByKey(rawDailyLast6Months, getMonthKey);
    const fullMonthlyKeys = getMonthRange(monthsAgo(5), today);
    const fullMonthlyMap = fillMissingKeys(fullMonthlyKeys, monthlyMap);
    const monthlyData = {
        labels: fullMonthlyKeys.map(m => {
            const [y, mo] = m.split('-');
            return new Date(`${y}-${mo}-01`).toLocaleDateString('en-IN', { month: 'short', year: 'numeric' });
        }),
        values: Object.values(fullMonthlyMap),
        total: Object.values(fullMonthlyMap).reduce((a, b) => a + b, 0)
    };

    //  Chart Setup
    const ctx = document.getElementById("revenueChart").getContext("2d");
    const gradient = ctx.createLinearGradient(0, 0, 0, 400);
    gradient.addColorStop(0, '#4B0F77');
    gradient.addColorStop(1, '#8f9a7e');

    let revenueChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: dailyData.labels,
            datasets: [{
                label: 'Daily Revenue',
                data: dailyData.values,
                tension: 0.4,
                borderColor: '#4B0F77',
                backgroundColor: gradient,
                fill: true,
                pointBackgroundColor: '#4B0F77',
                pointRadius: 5,
                pointHoverRadius: 7
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                tooltip: {
                    callbacks: {
                        label: context => `₹${context.formattedValue}`
                    }
                },
                legend: { display: false }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: value => `₹${value.toLocaleString()}`
                    }
                }
            }
        }
    });

    //  Update Revenue Heading
    function updateTotalRevenue(amount) {
        document.getElementById("totalRevenue").textContent = `₹${amount.toLocaleString()}`;
    }

    //  Filter Change Handler
    function updateChart(view) {
        let data;
        if (view === 'weekly') data = weeklyData;
        else if (view === 'monthly') data = monthlyData;
        else data = dailyData;

        revenueChart.data.labels = data.labels;
        revenueChart.data.datasets[0].data = data.values;
        revenueChart.update();

        updateTotalRevenue(data.total);

        document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
        document.getElementById(view).classList.add('active');
    }

    //  Initial Load
    updateTotalRevenue(dailyData.total);
</script>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
{{!--
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> --}}
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js"></script>
{{>footer}}