<?php include("loginChecker.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DataboxLab</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/style.css" />
    <style>
        
      </style>
      
</head>
<body>
    <div class="toggle-btn" onclick="toggleSidebar()">
        <i class="fas fa-bars"></i>
    </div>

    <div class="sidebar" id="sidebar">
        <!-- Logo section -->
        <div class="text-center mb-3">
          <img src="../images/logo.jpg" alt="Logo" style="width: 80px; height: auto; margin-bottom: 5px;">
          <h6 class="mb-0">APAPA AREA COMMAND</h6>
          <p class="fs-6 p-0 m-0 text-success">Research & Development Office</p>
        </div>
      
        <!-- Navigation links -->
        <a href="index.php" class="nav-link"><i class="fa fa-chart-line"></i> <span>Revenue</span></a>
        <a href="fast_track.php" class="nav-link"><i class="fa fa-fast-forward"></i> <span>Fast-Track</span></a>
        <a href="#" class="nav-link"><i class="fa fa-file-alt"></i> <span>PAAR</span></a>
        <a href="#" class="nav-link"><i class="fa fa-tachometer-alt"></i> <span>KPIs</span></a>
        <a href="logout.php" class="nav-link"><i class="fa fa-sign-out"></i> <span>Logout</span></a>
      </div>
      

    <div class="main-content pt-0">
        <div class="row m-0">
            <div class="d-flex justify-content-between align-items-center mb-3 bg-success">
                <h4 class="text-white">Revenue </h4>
                <button id="darkModeToggle" class="btn btn-sm btn-outline-light" style="background: none; border: none; color: white; font-size: 20px;">
                    <i class="fas fa-moon" id="darkModeIcon"></i>
                  </button>
                  
            </div>

        </div>
        

       
     
        <div class="card mb-3 report" id="revenue"  style="display: block;">
            <div class="card-header"><strong>Year on Year Revenue Generated including  Year to Date  </div>
            <div class="card-body">
              <div class="example">
                
                
                    <div class="c-chart-wrapper row">
                        <div class="col-8">
                            <canvas id="amountChart" width="800" height="400"></canvas>
                        </div>
                        <div class="col-4">
                            <canvas id="radarChart" width="800" height="350"></canvas>
                        </div>
                      <!-- <canvas id="revenueChart" width="320" height="100" style="display: block; box-sizing: border-box; height: 128px; width: 256px;"></canvas> -->
                      
                    </div>
                 
              </div>
            </div>
        </div>

        <div class="row mb-3 text-center ">

            <div class="col-md-4">
                <div class="card mb-2 p-2">
                  <div class="card-body p-4">
                    <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-4">
                    <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-4">
                    <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 class="col">
              <div><strong>2023 Total:</strong> <span id="total2023">--</span></div>
            </div> -->
            <!-- <div class="col">
              <div><strong>2024 Total:</strong> <span id="total2024">--</span></div>
            </div> -->
            <!-- <div class="col">
              <div><strong>2025 Total:</strong> <span id="total2025">--</span></div>
            </div> -->
          </div>

       
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://kit.fontawesome.com/d9c9660a46.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.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>
    <script>
      $(document).ready(function(){
          $('.counter').counterUp({
              delay: 6, // Speed of counting
              time: 3000 // Duration of animation
          });
      });

      // Highlight the active nav link
      const links = document.querySelectorAll('.sidebar a');
        const currentPage = window.location.pathname.split('/').pop();

        links.forEach(link => {
            if (link.getAttribute('href') === currentPage) {
            link.classList.add('active');
            }
        });
  </script>

<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>
  
    <script>
        function toggleSidebar() {
            document.getElementById("sidebar").classList.toggle("collapsed");
        }

        // document.getElementById('darkModeToggle').addEventListener('click', function() {
        //     document.body.classList.toggle('dark-mode');
        // });

       

        
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('y2d_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>

</body>
</html>
