<?php 
    include("header.php");
    include("left-sidebar.php");
    // $svn = $_SESSION['svn'];
    // $commandCode = $_SESSION['command_code'];
    // $svn = $_SESSION['svn'];
?>

            <!-- ============================================================== -->
            <!-- Start Page Content here -->
            <!-- ============================================================== -->

<div class="content-page px-1 pb-4" style="z-index:300;">
  <div class="content">
    <div class="container-fluid">

        <div class=" mt-1">
            <ul class="nav nav-tabs m-0 p-0" id="dashboardTabs" role="tablist">
            <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#overview">Overview</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#thisMonth">This Month</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#monthly">Monthly Trends</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#yearly">Yearly Comparison</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#quarterly">Quarterly Summary</button></li>
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#top">Top 5 Months</button></li>
            <!-- <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#percentage">% Contribution</button></li> -->
            <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#growth">Month-on-Month Growth</button></li>
            <!-- <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#weekly">Weekly Chart</button></li> -->
            </ul>
            <div class="tab-content pt-0">
                <div class="tab-pane fade show active" id="overview">
                    <div class="row">
                        <div class="card px-0 mb-1">
                        <div class="card-body py-0 my-0 px-1">
                            <div class="row pt-2">

                                <div class="col-md-4">
                                    <div class="card mb-2 p-2 shadow">
                                        <div class="card-body p-2">
                                            <div class="d-flex flex-nowrap justify-content-between">
                                            <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Revenue 2023</h6>
                                            <div class="bg-opacity-25  p-2 rounded ms-2" style="background-color: rgba(75, 192, 192, 0.4); color: rgb(75, 192, 192);">
                                                <i class="fa-solid fa-line-chart"></i>
                                            </div>
                                            </div>
                                            <div><h5> <span>₦</span> <span class="counter" id="total2023"> </span></h5></div>
                                            <small class="text-success" id="change2023">
                                                
                                            </small>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-4">
                                    <div class="card mb-2 p-2 shadow">
                                        <div class="card-body p-2 ">
                                            <div class="d-flex flex-nowrap justify-content-between">
                                            <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Revenue 2024</h6>
                                            <div class="bg-opacity-25 p-2 rounded ms-2" style="background-color: rgba(153, 102, 255, 0.4); color: rgb(153, 102, 255);" >
                                                <i class="fa-solid fa-line-chart"></i>
                                            </div>
                                            </div>
                                            <div><h5> <span>₦</span> <span class="counter" id="total2024"> </span></h5></div>
                                            <small class="text-success" id="change2024">
                                                
                                            </small>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-4">
                                    <div class="card mb-2 p-2 shadow">
                                        <div class="card-body p-2">
                                            <div class="d-flex flex-nowrap justify-content-between">
                                            <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Revenue 2025</h6>
                                            <div class="bg-opacity-25 p-2 rounded ms-2" style="background-color: rgba(255, 159, 64, 0.4); color: rgb(255, 159, 64);">
                                                <i class="fa-solid fa-line-chart"></i>
                                            </div>
                                            </div>
                                            <div><h5> <span>₦</span> <span class="counter" id="total2025"> </span></h5></div>
                                            <small class="text-success" id="change2025">
                                                
                                            </small>
                                        </div>
                                    </div>
                                </div>

                            </div> <!-- end row -->
                        </div> <!-- end card-body -->
                        </div> <!-- end card -->
                    </div> <!-- end row -->

                    <div class="row mb-1">
                        <div class="card px-1 mb-0">
                        <div class="card-body py-2 my-0 px-1">
                            <div class="d-flex justify-content-between align-items-baseline">
                            <div class="fw-semibold">37% Collected</div>
                            <div class="text-nowrap small text-body-secondary ms-3">
                                <span data-coreui-i18n-date="dateShortMonthName, { 'date': '2023, 6, 11'}">Feb 01, 2025</span> -
                                <span data-coreui-i18n-date="dateShortMonthName, { 'date': '2023, 7, 10'}">Feb 17, 2025</span>
                            </div>
                            </div>
                            <div class="progress progress-thin mt-1 px-0 col-12">
                            <div class="progress-bar bg-success" role="progressbar" style="width: 37%" aria-valuenow="37" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                        </div> <!-- end card-body -->
                        </div> <!-- end card -->
                    </div> <!-- end row -->

                        <div class="row">
                            <div class="card report px-0 mb-2" id="revenue">
                                <div class="card-body py-0 my-0 px-1">
                                    <div class="example">
                                            
                                            
                                        <div class="c-chart-wrapper row">
                                            <div class="col-8">
                                                <canvas id="amountChart" width="800" height="390"></canvas>
                                            </div>
                                            <div class="col-4">
                                                <canvas id="radarChart" width="800" height="390"></canvas>
                                            </div>
                                        <!-- <canvas id="revenueChart" width="320" height="100" style="display: block; box-sizing: border-box; height: 128px; width: 256px;"></canvas> -->
                                        
                                        </div>
                                            
                                    </div>
                                </div> <!-- end card-body -->
                            </div> <!-- end card -->
                        </div> <!-- end row -->
                </div>
                
                <div class="tab-pane fade" id="thisMonth">
                    <div class="row mb-1">
                        
                        <div class="card px-1 mb-0">
                            <div class="card-body p-1 my-0">

                                <div class="row">

                                    <div class="col-12">
                                        <canvas id="dailyMayChart" height="100"></canvas>
                                    </div>

                                    <div class="col-12">
                                        
                                        <table class="table table-bordered table-sm" id="weeklySummaryTable">
                                          <thead class="table-success">
                                            <tr>
                                              <th>Week #</th>
                                              <th>Week Range</th>
                                              <th>Total SGD</th>
                                              <th>Total eCash (₦)</th>
                                              <th>Average % Target Met</th>
                                            </tr>
                                          </thead>
                                          <tbody></tbody>
                                        </table>
                                    </div>

                                </div>
                                
                                
                            </div> <!-- end card-body -->
                        </div> <!-- end card -->
                      
                    </div> <!-- end row --> 
                </div>

                <div class="tab-pane fade show" id="monthly">
                    <div class="row mb-1">
                        
                            <div class="card px-1 mb-0">
                                <div class="card-body py-2 my-0 px-1">

                                    <div class="row">

                                        <div class="col-7">
                                            <canvas id="monthlyChart"></canvas>
                                        </div>

                                        <div class="col-5">
                                            <div class="card">
                                                <div class="card-body shadow">
                                                    <table class="table table-sm table-bordered table-striped" id="monthlyRevenueTable">
                                                        <thead>
                                                            <tr class="text-ncs-green">
                                                            <th class="text-center">Month</th>
                                                            <th class="text-center">2023</th>
                                                            <th class="text-center">2024</th>
                                                            <th class="text-center">2025</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody></tbody>
                                                    </table>
                                                </div>
                                            </div>
                                            
                                        </div>

                                    </div>
                                  
                                    
                                </div> <!-- end card-body -->
                            </div> <!-- end card -->
                      
                    </div> <!-- end row --> 
                </div>

                <div class="tab-pane fade" id="yearly">
                    <div class="row mb-1">
                        
                        <div class="card px-2 mb-0">
                            <div class="card-body p-4 my-0">

                                <div class="row">

                                    <div class="col-8">
                                        <canvas id="yearlyChart"></canvas>
                                    </div>

                                    <div class="col-4">

                                        <div class="col-12">
                                            <div class="card mb-2 p-2 shadow">
                                                <div class="card-body p-2">
                                                    <div class="d-flex flex-nowrap justify-content-between">
                                                    <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Revenue 2023</h6>
                                                    <div class="bg-opacity-25  p-2 rounded ms-2" style="background-color: rgba(75, 192, 192, 0.4); color: rgb(75, 192, 192);">
                                                        <i class="fa-solid fa-line-chart"></i>
                                                    </div>
                                                    </div>
                                                    <div><h5> <span>₦</span> <span class="counter" id="tableTotal2023"> </span></h5></div>
                                                    <small class="text-success" id="tableChange2023">
                                                        
                                                    </small>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-12">
                                            <div class="card mb-2 p-2 shadow">
                                                <div class="card-body p-2">
                                                    <div class="d-flex flex-nowrap justify-content-between">
                                                    <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Revenue 2024</h6>
                                                    <div class="bg-opacity-25  p-2 rounded ms-2" style="background-color: rgba(75, 192, 192, 0.4); color: rgb(75, 192, 192);">
                                                        <i class="fa-solid fa-line-chart"></i>
                                                    </div>
                                                    </div>
                                                    <div><h5> <span>₦</span> <span class="counter" id="tableTotal2024"> </span></h5></div>
                                                    <small class="text-success" id="tableChange2024">
                                                        
                                                    </small>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-12">
                                            <div class="card mb-2 p-2 shadow">
                                                <div class="card-body p-2">
                                                    <div class="d-flex flex-nowrap justify-content-between">
                                                    <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Revenue 2025</h6>
                                                    <div class="bg-opacity-25  p-2 rounded ms-2" style="background-color: rgba(75, 192, 192, 0.4); color: rgb(75, 192, 192);">
                                                        <i class="fa-solid fa-line-chart"></i>
                                                    </div>
                                                    </div>
                                                    <div><h5> <span>₦</span> <span class="counter" id="tableTotal2025"> </span></h5></div>
                                                    <small class="text-success" id="tableChange2025">
                                                        
                                                    </small>
                                                </div>
                                            </div>
                                        </div>

                                    </div>

                                </div>
                                
                                
                            </div> <!-- end card-body -->
                        </div> <!-- end card -->
                      
                    </div> <!-- end row -->  
                </div>

                <div class="tab-pane fade" id="quarterly">
                    <div class="row mb-1">
                        
                        <div class="card pt-3 mb-0">
                            <div class="card-body p-4 my-0 ">

                                <div class="row">

                                    <div class="col-6">
                                        <canvas id="quarterlyChart"></canvas>
                                    </div>

                                    <div class="col-6">
                                        
                                        
                                            <div class="card mb-2 shadow">
                                                <div class="card-body">
                                                    <table class="table table-bordered table-sm table-striped" id="quarterlyRevenueTable">
                                                        <thead>
                                                            <tr class="text-ncs-green text-center">
                                                            <th>Quarter</th>
                                                            <th>2023 Total</th>
                                                            <th>2024 Total</th>
                                                            <th>2025 Total</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody></tbody>
                                                    </table>
                                                </div>
                                            </div>
                                       

                                    </div>

                                </div>
                                
                                
                            </div> <!-- end card-body -->
                        </div> <!-- end card -->
                      
                    </div> <!-- end row -->  
                </div>

                <div class="tab-pane fade" id="top">
                    <div class="row mb-1">
                        
                        <div class="card px-4 mb-0">
                            <div class="card-body p-4 my-0 ">

                                <div class="row">

                                    <div class="col-12">
                                        <canvas id="topMonthsChart"></canvas>
                                    </div>

                                    <!-- <div class="col-5">
                                        
                                    </div> -->

                                </div>
                                
                                
                            </div> <!-- end card-body -->
                        </div> <!-- end card -->
                      
                    </div> <!-- end row -->  
                </div>
                <!-- <div class="tab-pane fade" id="percentage">
                    <div class="row mb-1">
                        
                        <div class="card px-1 mb-0">
                            <div class="card-body py-2 my-0 px-1">

                                <div class="row">

                                    <div class="col-7">
                                        <canvas id="percentageChart"></canvas>
                                    </div>

                                    <div class="col-5">
                                        
                                    </div>

                                </div>
                                
                                
                            </div> 
                        </div> 
                      
                    </div> 
                </div> -->
                <div class="tab-pane fade" id="growth">
                    <div class="row mb-1">
                        
                        <div class="card px-1 mb-0">
                            <div class="card-body p-4 my-0">

                                <div class="row">

                                    <div class="col-12">
                                        <canvas id="growthChart"></canvas>
                                    </div>

                                    <!-- <div class="col-5">
                                        
                                    </div> -->

                                </div>
                                
                                
                            </div> <!-- end card-body -->
                        </div> <!-- end card -->
                      
                    </div> <!-- end row --> 
                </div>

                <!-- <div class="tab-pane fade" id="weekly">
                    <canvas id="weeklyChart"></canvas>
                </div> -->

            </div>
        </div>

      <!-- PAGE TITLE & OTHER ROWS OMITTED -->

      

    </div> <!-- end container-fluid -->
  </div> <!-- end content -->
</div> <!-- end content-page -->

    <?php include("modals.php"); ?>

    <?php include("footer.php"); ?>
   
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery.counterup@2.1.0/jquery.counterup.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
    
    <!-- COUNTER UP -->
    <script>
      $(document).ready(function(){
          $('.counter').counterUp({
              delay: 6, // Speed of counting
              time: 3000 // Duration of animation
          });
      });
</script>

      <!-- DARK MODE -->
<script>
    const toggleBtn = document.getElementById('darkModeToggle');
    const icon = document.getElementById('darkModeIcon');
  
    // Function to apply dark mode and update icon
    function applyDarkMode(isDark) {
      document.body.classList.toggle('dark-mode', isDark);
      icon.classList.remove('fa-sun', 'fa-moon');
      icon.classList.add(isDark ? 'fa-sun' : 'fa-moon');
    }
  
    // Load saved mode on page load
    const savedMode = localStorage.getItem('darkMode');
    const isDarkMode = savedMode === 'true' || (!savedMode && window.matchMedia('(prefers-color-scheme: dark)').matches);
    applyDarkMode(isDarkMode);
  
    // Toggle and save on click
    toggleBtn.addEventListener('click', function () {
      const isDark = document.body.classList.toggle('dark-mode');
      localStorage.setItem('darkMode', isDark);
      icon.classList.remove('fa-sun', 'fa-moon');
      icon.classList.add(isDark ? 'fa-sun' : 'fa-moon');
    });
  </script>

  <!-- CHARTS -->
 <script>
           
function formatNumber(value) {
    const abs = Math.abs(value);
    if (abs >= 1.0e+12) return (value / 1.0e+12).toFixed(1).replace(/\.0$/, '') + 'T';
    if (abs >= 1.0e+9)  return (value / 1.0e+9).toFixed(1).replace(/\.0$/, '') + 'B';
    if (abs >= 1.0e+6)  return (value / 1.0e+6).toFixed(1).replace(/\.0$/, '') + 'M';
    if (abs >= 1.0e+3)  return (value / 1.0e+3).toFixed(1).replace(/\.0$/, '') + 'k';
    return value.toString();
}


fetch('models/index_model.php')
    .then(response => response.json())
    .then(result => {
        const monthMap = {
            January: 0, February: 1, March: 2, April: 3,
            May: 4, June: 5, July: 6, August: 7,
            September: 8, October: 9, November: 10, December: 11
        };

        const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", 
                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        const dataByYear = {
            2023: Array(12).fill(0),
            2024: Array(12).fill(0),
            2025: Array(12).fill(0)
        };

        result.monthly.forEach(row => {
            const year = parseInt(row.year);
            const monthIndex = monthMap[row.month];
            if (dataByYear[year] && monthIndex !== undefined) {
                dataByYear[year][monthIndex] = parseFloat(row.total_amount);
            }
        });

        // Yearly Totals formatting
        let prevTotal = null;

        result.yearly_totals.forEach(row => {
            const year = parseInt(row.year);
            const total = parseFloat(row.yearly_total);
            const el = document.getElementById('total' + year);
            const elTable = document.getElementById('tableTotal' + year);

            // Set the yearly total CHART
            if (el) el.textContent = total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            // Set the yearly total TABLE
            if (elTable) elTable.textContent = total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            

            const changeEl = document.getElementById('change' + year); // Element to show change

            if (changeEl) {
                if (prevTotal === null || isNaN(prevTotal)) {
                    changeEl.textContent = '(N/A)';
                    changeEl.style.color = 'gray';
                } else {
                    const percentageChange = ((total - prevTotal) / prevTotal) * 100;
                    const sign = percentageChange >= 0 ? '+' : '';
                    changeEl.textContent = `(${sign}${percentageChange.toFixed(2)}%)`;
                    changeEl.style.color = percentageChange >= 0 ? 'green' : 'red';
                }
            }

            prevTotal = total;
        });



        // Bar Chart
        new Chart(document.getElementById('amountChart'), {
            type: 'bar',
            data: {
                labels: months,
                datasets: [
                    {
                        label: '2023',
                        data: dataByYear[2023],
                        backgroundColor: 'rgba(75, 192, 192, 0.6)'
                    },
                    {
                        label: '2024',
                        data: dataByYear[2024],
                        backgroundColor: 'rgba(153, 102, 255, 0.6)'
                    },
                    {
                        label: '2025',
                        data: dataByYear[2025],
                        backgroundColor: 'rgba(255, 159, 64, 0.6)'
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Monthly Revenue for 2023, 2024, 2025'
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': ' + formatNumber(context.raw);
                            }
                        }
                    }
                },
                scales: {
                    x: {
                        border: {
                        display: true
                        },
                        grid: {
                            
                            color: 'rgba(144,144,144,.1)',
                        }
                    },
                    y: {
                        beginAtZero: true,
                        border: {
                        display: false
                        },
                        grid: {
                            
                            color: 'rgba(144,144,144,.1)',
                        },
                        ticks: {
                            callback: function(value) {
                                return formatNumber(value);
                            }
                        },
                        title: {
                            display: true,
                            text: 'Revenue'
                        }
                        
                    },
                    
                }
            }
        });

        // Radar Chart
        new Chart(document.getElementById('radarChart'), {
            type: 'radar',
            data: {
                labels: months,
                datasets: [
                    {
                        label: '2023',
                        data: dataByYear[2023],
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '2024',
                        data: dataByYear[2024],
                        backgroundColor: 'rgba(153, 102, 255, 0.2)',
                        borderColor: 'rgba(153, 102, 255, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '2025',
                        data: dataByYear[2025],
                        backgroundColor: 'rgba(255, 159, 64, 0.2)',
                        borderColor: 'rgba(255, 159, 64, 1)',
                        borderWidth: 1
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    title: {
                        display: true,
                        text: 'Radar Chart - Monthly Revenue for 2023, 2024, 2025'
                    },
                    legend: {
                        position: 'top'
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.dataset.label + ': ' + formatNumber(context.raw);
                            }
                        }
                    }
                },
                scales: {
                    r: {
                        angleLines: { display: true },
                        suggestedMin: 0,
                        ticks: {
                            callback: function(value) {
                                return formatNumber(value);
                            }
                        },
                        border: {
                        display: true
                        },
                        grid: {
                            
                            color: 'rgba(144,144,144,.2)',
                        }
                    }
                }
            }
        });
    });


    </script>

        
<!-- TIMMER REDIRECT  -->
<script>
  const pages = [
    { name: "Fast-Track", url: "fasttrack.php" },
    { name: "Revenue", url: "revenue.php" }
    
  ];

  const countdownSeconds = 360; // seconds per page
  let currentPageIndex = 0;
  let remainingTime = countdownSeconds;
  let intervalId = null;
  let isPaused = false;

  const countdownText = document.getElementById("countdown-text");
  const countdownTime = document.getElementById("countdown-time");
  const pageNameSpan = document.getElementById("page-name");
  const pauseBtn = document.getElementById("pause-btn");

  function updateCountdown() {
    const minutes = Math.floor(remainingTime / 60);
    const seconds = remainingTime % 60;
    countdownTime.textContent = `${minutes}m ${seconds}s`;

    if (remainingTime <= 0) {
      clearInterval(intervalId);
      redirectToNextPage();
    }

    remainingTime--;
  }

  function redirectToNextPage() {
    const nextPage = pages[currentPageIndex];
    window.location.href = nextPage.url;
    // Optionally: update index and restart for demo loops
    // currentPageIndex = (currentPageIndex + 1) % pages.length;
    // startCountdown();
  }

  function startCountdown() {
    const currentPage = pages[currentPageIndex];
    pageNameSpan.textContent = currentPage.name;
    remainingTime = countdownSeconds;
    updateCountdown(); // Show initial time
    intervalId = setInterval(() => {
      if (!isPaused) {
        updateCountdown();
      }
    }, 1000);
  }

  pauseBtn.addEventListener("click", () => {
    isPaused = !isPaused;
    pauseBtn.textContent = isPaused ? "Resume" : "Pause";
  });

  // Begin
  startCountdown();
</script>


<!-- THE TABS -->
 <!-- SWITHCH TABS AUTHOMATICALLY -->
  <script>
  document.addEventListener("DOMContentLoaded", function () {
    const tabs = document.querySelectorAll('[data-bs-toggle="tab"]');
    let current = 0;

    if (tabs.length > 1) {
      setInterval(() => {
        current = (current + 1) % tabs.length;
        const tabTrigger = new bootstrap.Tab(tabs[current]);
        tabTrigger.show();
      }, 60000); // change tab every 5 seconds(5000)
    }
  });
</script>

 <script>
    const colors = ['#36A2EB', '#FF6384', '#FFCE56', '#4BC0C0', '#9966FF'];

    fetch('analytics_data.php')
      .then(res => res.json())
      .then(data => {
        renderMonthlyChart(data);
        renderYearlyChart(data);
        renderQuarterlyChart(data);
        renderQuarterlyTable(data);
        renderTopMonthsChart(data);
        // renderPercentageChart(data);
        renderGrowthChart(data);
        // renderWeeklyChart(data);
         
      });

    function renderMonthlyChart(data) {
      const ctx = document.getElementById('monthlyChart').getContext('2d');
      const colors = ['rgba(54, 162, 235, 0.5)', 'rgba(255, 99, 132, 0.5)', 'rgba(255, 206, 86, 0.5)'];
      const datasets = Object.keys(data.monthly).map((year, idx) => ({
        label: year,
        data: data.months.map(m => data.monthly[year][m] || 0),
        borderColor: colors[idx % colors.length],
        fill: true,
        backgroundColor: colors[idx % colors.length]
        
      }));
      new Chart(ctx, {
        type: 'line',
        data: { labels: data.months, datasets },
        options: {
          responsive: true,
          plugins: {
            title: { display: true, text: 'Monthly Trends' },
            tooltip: {
              callbacks: {
                label: function(context) {
                  return `${context.dataset.label}: ₦${formatNumber(context.raw)}`;
                }
              }
            }
          },
          scales: {
            y: {
              ticks: {
                callback: function(value) {
                  return formatNumber(value);
                }
              }
            }
          }
        }
      });
    }

    function renderYearlyChart(data) {
      const ctx = document.getElementById('yearlyChart').getContext('2d');
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: Object.keys(data.yearly),
          datasets: [{
            label: 'Total Revenue',
            data: Object.values(data.yearly),
            backgroundColor: colors
          }]
        },
        options: { responsive: true, plugins: { title: { display: true, text: 'Yearly Comparison' } } }
      });
    }

    function renderQuarterlyChart(data) {
      const ctx = document.getElementById('quarterlyChart').getContext('2d');
      const labels = ['Q1', 'Q2', 'Q3', 'Q4'];
      const colors = ['#36a2eb', '#ff6384', '#ffce56'];

      const datasets = Object.keys(data.quarterly).map((year, idx) => ({
        label: year,
        data: labels.map(q => data.quarterly[year][q] || 0),
        backgroundColor: colors[idx % colors.length]
      }));

      new Chart(ctx, {
        type: 'bar',
        data: { labels, datasets },
        options: {
          responsive: true,
          plugins: {
            title: { display: true, text: 'Quarterly Summary' },
            tooltip: {
              callbacks: {
                label: function(context) {
                  return `${context.dataset.label}: ₦${formatNumber(context.raw)}`;
                }
              }
            }
          },
          scales: {
            y: {
              ticks: {
                callback: function(value) {
                  return formatNumber(value);
                }
              }
            }
          }
        }
      });
    }

    function renderQuarterlyTable(data) {
      const quarterlyData = data.quarterly;
      const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
      const years = ['2023', '2024', '2025'];
      const tableBody = document.querySelector('#quarterlyRevenueTable tbody');
      tableBody.innerHTML = '';

      quarters.forEach(q => {
        const tr = document.createElement('tr');
        let row = `<td>${q}</td>`;
        years.forEach(year => {
          const value = quarterlyData[year] && quarterlyData[year][q] ? `₦${Number(quarterlyData[year][q]).toLocaleString()}` : '—';
          row += `<td>${value}</td>`;
        });
        tr.innerHTML = row;
        tableBody.appendChild(tr);
      });
    }


    function renderTopMonthsChart(data) {
      const allMonths = [];
      for (let year in data.monthly) {
        for (let month in data.monthly[year]) {
          allMonths.push({ label: `${month} ${year}`, value: data.monthly[year][month] });
        }
      }
      const top = allMonths.sort((a,b) => b.value - a.value).slice(0, 5);
      const ctx = document.getElementById('topMonthsChart').getContext('2d');
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: top.map(x => x.label),
          datasets: [{ label: 'Revenue', data: top.map(x => x.value), backgroundColor: colors }]
        },
        options: { responsive: true, plugins: { title: { display: true, text: 'Top 5 Months' } } }
      });
    }

    function renderPercentageChart(data) {
      const ctx = document.getElementById('percentageChart').getContext('2d');
      const year = Object.keys(data.monthly).pop();
      const total = Object.values(data.monthly[year]).reduce((a,b) => a + b, 0);
      const percentages = data.months.map(m => (data.monthly[year][m] || 0) / total * 100);
      new Chart(ctx, {
        type: 'pie',
        data: {
          labels: data.months,
          datasets: [{ label: `% Contribution - ${year}`, data: percentages, backgroundColor: colors.concat(colors) }]
        },
        options: { responsive: true, plugins: { title: { display: true, text: `% Monthly Contribution - ${year}` } } }
      });
    }

    function renderGrowthChart(data) {
      const ctx = document.getElementById('growthChart').getContext('2d');
      const year = Object.keys(data.monthly).pop();
      const values = data.months.map(m => data.monthly[year][m] || 0);
      const growth = values.map((v, i) => i === 0 ? 0 : ((v - values[i - 1]) / values[i - 1] * 100).toFixed(2));
      new Chart(ctx, {
        type: 'line',
        data: { labels: data.months, datasets: [{ label: `MoM Growth - ${year}`, data: growth, borderColor: '#198754' }] },
        options: { responsive: true, plugins: { title: { display: true, text: 'Month-on-Month Growth (%)' } } }
      });
    }

    
  </script>
  
<script>
// DAILY REVENUE CHARTS
fetch('models/daily_revenue_chart.php')
  .then(res => res.json())
  .then(data => {
    const ctx = document.getElementById('dailyMayChart').getContext('2d');
    new Chart(ctx, {
      type: 'bar',
      data: {
        labels: data.labels,
        datasets: [
          {
            label: 'eCash',
            data: data.ecash,
            backgroundColor: 'rgba(255, 99, 132, 0.6)',
            yAxisID: 'y'
          },
          {
            label: 'Performance (%)',
            data: data.percentage,
            type: 'line',
            borderColor: 'rgba(255, 206, 86, 1)',
            backgroundColor: 'rgba(255, 206, 86, 0.4)',
            yAxisID: 'y1',
            tension: 0.4,
            fill: false
          }
        ]
      },
      options: {
        responsive: true,
        plugins: {
          
          tooltip: {
            callbacks: {
              label: ctx => `${ctx.dataset.label}: ${ctx.dataset.label === 'Performance (%)' ? ctx.raw + '%' : '₦' + formatNumber(ctx.raw)}`
            }
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            title: { display: true, text: 'eCash' },
            ticks: {
              callback: value => formatNumber(value)
            }
          },
          y1: {
            position: 'right',
            beginAtZero: true,
            title: { display: true, text: 'Percentage (%)' },
            grid: { drawOnChartArea: false }
          }
        }
      }
    });
  });


</script>

  <!-- TABLES -->
<script>
//   MONTHLY REVENUE TABLE
    fetch('models/tbl_monthly_revenue.php')
      .then(response => response.json())
      .then(data => {
        const tbody = document.querySelector('#monthlyRevenueTable tbody');
        data.forEach(row => {
          const tr = document.createElement('tr');
          tr.innerHTML = `
            <td class='fw-bold'>${row.month}</td>
            <td class='fs-6'>₦${Number(row[2023]).toLocaleString()}</td>
            <td class='fs-6'>₦${Number(row[2024]).toLocaleString()}</td>
            <td class='fs-6'>₦${Number(row[2025]).toLocaleString()}</td>
          `;
          tbody.appendChild(tr);
        });
      })
      .catch(error => console.error('Error fetching data:', error));
</script>
  
<script>
// WEEKLY REVENUE TABLE
    fetch('models/weekly_revenue_table.php')
      .then(res => res.json())
      .then(data => {
        
        const tableBody = document.querySelector('#weeklySummaryTable tbody');
        data.weekly.forEach(week => {
          const tr = document.createElement('tr');
          const start = formatDateDMY(week.week_start);
          const end = formatDateDMY(week.week_end);
          tr.innerHTML = `
            <td>W${week.week_number}</td>
            <td>${start} to ${end}</td>
            <td>${formatNumber(week.total_sgd)}</td>
            <td>₦${formatNumber(week.total_ecash)}</td>
            <td class="text-center"><span class="p-1 bg-${week.avg_percentage >= 100 ? 'success' : 'warning'}">${week.avg_percentage}%</span></td>
          `;
          tableBody.appendChild(tr);
        });
      });
      
      function formatDateDMY(dateString) {
        const d = new Date(dateString);
          const dd = String(d.getDate()).padStart(2, '0');
          const mm = String(d.getMonth() + 1).padStart(2, '0');
          const yy = String(d.getFullYear()).slice(-2);
          return `${dd}/${mm}/${yy}`;
        }
</script>