<?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">

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

      <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">
                        <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">
                        <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">
                        <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> <!-- 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);

            // Set the yearly total
            if (el) el.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: "index.php" }
    
  ];

  const countdownSeconds = 5000; // 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>
<script>

</script>