<?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="#quarterly">Quarterly Summary</button></li>
            
            <!--<li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#growth">Month-on-Month Growth</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 shadow">
                                  <div class="card-body">
                                    <div class="d-flex flex-nowrap justify-content-between">
                                      <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Declarations</h6>
                                      <div class="bg-info bg-opacity-25 text-info p-2 rounded ms-2">
                                        <i class="fa-solid fa-list"></i>
                                      </div>
                                    </div>
                                    <div class="fs-4 fw-semibold pb-3 text-center counter" id="totalDeclarations"></div>
                                    <!--<small class="text-success">(17.2%)</small>-->
                                  </div>
                                </div>
                              </div>
                
                              <div class="col-md-4">
                                <div class="card mb-2 shadow">
                                  <div class="card-body">
                                    <div class="d-flex flex-nowrap justify-content-between">
                                      <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Containers</h6>
                                      <div class="bg-warning bg-opacity-25 text-warning p-2 rounded ms-2">
                                        <i class="fa-solid fa-truck-moving"></i>
                                      </div>
                                    </div>
                                    <div class="fs-4 fw-semibold pb-3 text-center counter" id="totalContainers"></div>
                                    <!--<small class="text-success">(17.2%)</small>-->
                                  </div>
                                </div>
                              </div>
                
                              
                
                              <div class="col-md-4">
                                <div class="card mb-2 shadow">
                                  <div class="card-body">
                                    <div class="d-flex flex-nowrap justify-content-between">
                                      <h6 class="card-title text-body-secondary text-truncate" data-coreui-i18n="orders">Revenue Collected</h6>
                                      <div class="bg-success bg-opacity-25 text-success p-2 rounded ms-2">
                                        <i class="fa-solid fa-check-to-slot"></i>
                                      </div>
                                    </div>
                                    <div class="fs-4 fw-semibold pb-3 text-center">
                                      <span>₦</span> <span class="counter" id="totalCollected"></span>
                                    </div>
                                    <!--<small class="text-success">(17.2%)</small>-->
                                  </div>
                                </div>
                              </div>
                            </div> <!-- end row -->
                          </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 row">
                            <div class="col-7">
                              <div class="c-chart-wrapper">
                                <canvas id="revenueChart" style=""></canvas>
                              </div>
                            </div>
                            <div class="col-5">
                                <canvas id="declarationPieChart"></canvas>
                            </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="dailyRevenueChart" 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 Declarations</th>
                                              <th>Total Containers</th>
                                              <th>Total Collection (₦)</th>
                                            </tr>
                                          </thead>
                                          <tbody></tbody>
                                        </table>

                                    </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 text-center">
                                        <canvas id="quarterlyPieChartFasttrack" style="display:inline"></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>Declarations</th>
                                                          <th>Containers</th>
                                                          <th>Collections</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="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> 
                <!--        </div> 
                      
                <!--    </div> 
                <!--</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/chartjs-plugin-datalabels"></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 fetchData() {
  $.ajax({
    url: 'models/fasttrack_model.php',
    method: 'GET',
    dataType: 'json',
    success: function(response) {
      // === Totals (unchanged) ===
      $('#totalDeclarations').text(Number(response.totals.total_declarations).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
      $('#totalContainers').text(Number(response.totals.total_containers).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
      $('#totalGenerated').text(Number(response.totals.total_generated).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
      $('#totalCollected').text(Number(response.totals.total_collected).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));

      // === Monthly Bar Chart ===
      const labels = response.monthly.map(item => item.month);
      const revenueCollected = response.monthly.map(item => item.total_collected);

      const ctxBar = document.getElementById('revenueChart').getContext('2d');
      new Chart(ctxBar, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: 'Monthly Revenue Collected',
            data: revenueCollected,
            backgroundColor: '#458bcc'
          }]
        },
        options: {
          responsive: true,
          plugins: {
            title: {
              display: true,
              text: 'Monthly Revenue Collected'
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  return '₦' + Number(context.raw).toLocaleString();
                }
              }
            }
          },
          scales: {
            y: {
              beginAtZero: true,
              ticks: {
                callback: function(value) {
                  return Number(value).toLocaleString();
                }
              }
            }
          }
        }
      });

     // === Declarations Pie Chart ===
const declarations = response.monthly.map(item => item.total_declarations);
const labels2 = response.monthly.map(item => item.month); // Ensure this exists
const ctxPie = document.getElementById('declarationPieChart').getContext('2d');

new Chart(ctxPie, {
  type: 'pie',
  data: {
    labels: labels2,
    datasets: [{
      label: 'Monthly Declarations',
      data: declarations,
      backgroundColor: [
        '#0d6efd', '#198754', '#ffc107', '#dc3545',
        '#6f42c1', '#20c997', '#fd7e14', '#6610f2',
        '#6c757d', '#e83e8c', '#00bcd4', '#795548'
      ]
    }]
  },
  options: {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Monthly Declarations Distribution'
      },
      tooltip: {
        callbacks: {
          label: function(context) {
            return `${context.label}: ${Number(context.raw).toLocaleString()} declarations`;
          }
        }
      },
      datalabels: {
        color: '#fff',
        font: { weight: 'bold' },
        formatter: function(value) {
          return value.toLocaleString();
        }
      }
    }
  },
  plugins: [ChartDataLabels]
});

    },
    error: function(err) {
      console.log('Error fetching data:', err);
    }
  });
}

        $(document).ready(fetchData);
        
    </script>

<!--DAILY CHART-->
<script>
    fetch('models/daily_fasttrack.php')
  .then(res => res.json())
  .then(data => {
    const labels = data.daily.map(item => item.label);
    const values = data.daily.map(item => item.total_collected);

    new Chart(document.getElementById('dailyRevenueChart'), {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: `Daily Revenue Collected (${data.month} ${data.year})`,
          data: values,
          backgroundColor: '#0d6efd'
        }]
      },
      options: {
        responsive: true,
        plugins: {
          tooltip: {
            callbacks: {
              label: context => '₦' + Number(context.raw).toLocaleString()
            }
          },
          title: {
            display: false,
            text: 'Daily Revenue Collection'
          }
        },
        scales: {
          y: {
            ticks: {
              callback: val => Number(val).toLocaleString()
            }
          }
        }
      }
    });
  });

</script>

<!--WEEKLY FASTTRACK TABLE-->
<script>
    fetch('models/weekly_fasttrack_table.php')
  .then(res => res.json())
  .then(data => {
    const tbody = document.querySelector('#weeklySummaryTable tbody');
    tbody.innerHTML = '';
    data.forEach(week => {
      const row = `
        <tr>
          <td>${week.week_number}</td>
          <td>${week.week_range}</td>
          <td>${week.total_declarations.toLocaleString()}</td>
          <td>${week.total_containers.toLocaleString()}</td>
          <td>₦${Number(week.total_collected).toLocaleString()}</td>
        </tr>`;
      tbody.insertAdjacentHTML('beforeend', row);
    });
  });

</script>

<!--QUARTERLY FASTRACK DATA-->
<script>
    
fetch('models/quarterly_fasttrack_data.php')
  .then(res => res.json())
  .then(data => {
    const labels = data.map(d => d.quarter);
    const collections = data.map(d => d.total_collected);

    // Populate table
    const tbody = document.querySelector('#quarterlyRevenueTable tbody');
    tbody.innerHTML = '';
    data.forEach(row => {
      tbody.innerHTML += `
        <tr>
          <td>${row.quarter}</td>
          <td>${Number(row.total_declarations).toLocaleString()}</td>
          <td>${Number(row.total_containers).toLocaleString()}</td>
          <td>₦${Number(row.total_collected).toLocaleString()}</td>
        </tr>
      `;
    });

    // Draw Pie chart for Collections
    const ctx = document.getElementById('quarterlyPieChartFasttrack').getContext('2d');
    new Chart(ctx, {
      type: 'pie',
      data: {
        labels: labels,
        datasets: [{
          label: 'Quarterly Collections',
          data: collections,
          backgroundColor: ['#0d6efd', '#198754', '#ffc107', '#dc3545']
        }]
      },
      options: {
        responsive: true,
        plugins: {
          title: {
            display: true,
            text: 'Quarterly Collections (₦)'
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return `${context.label}: ₦${Number(context.raw).toLocaleString()}`;
              }
            }
          }
        }
      }
    });
  });


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

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