<?php include "../header.php"; ?>
<style>

</style>
<?php
$cards = array();
$previewURL = APIURL . '/website/leaderboard'; // Change to your actual URL

$ch = curl_init();
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array()));
curl_setopt($ch, CURLOPT_URL, $previewURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);


if ($response === false) {
  //echo "cURL Error: " . curl_error($ch);
} else {
  $result  = json_decode($response, true);
  $winners   = (!empty($result) && isset($result['status']) && $result['status'] == '1' && isset($result['winners'])) ? $result['winners'] : array();
  $monthlyWinners   = (!empty($result) && isset($result['status']) && $result['status'] == '1' && isset($result['monthlyWinners'])) ? $result['monthlyWinners'] : array();
  $yearlyWinners   = (!empty($result) && isset($result['status']) && $result['status'] == '1' && isset($result['yearlyWinners'])) ? $result['yearlyWinners'] : array();
}

// print '<pre>';
// print_r($monthlyWinners);
// exit;

curl_close($ch);

?>

<script>
  function selectType(type) {
    $(".typecls").hide();
    $(".typecls").removeClass('active');
    $("#" + type).addClass('active');
    $("#" + type).show();
    if (type == 'latest') {
      $(".top3winners").show();
    }

  }

  function selectYear(year, clickedElement = null) {


    const currentYear = $("#year").text();

    // Remove active class from all year items
    document.querySelectorAll('.dropdown-menu .dropdown-item').forEach(item => {
      item.classList.remove('active');
    });

    // Add active class to clicked item
    clickedElement.classList.add('active');

    if (currentYear == year) return; // Don't proceed if same year


    $.ajax({
      url: '../process.php', // The PHP script to process the request
      type: 'POST',
      data: {
        year: year
      },
      dataType: 'json',
      success: function(response) {

        let tbody = $('#winnersTable tbody'); // Update with your actual table ID
        $(".no_records").hide();
        $("#year").html(year);
        if (response.status == 1 && response.yearlyWinners) {
          let yearlyWinners = response.yearlyWinners;
          let rankClass = {
            1: "first-rank",
            2: "second-rank",
            3: "third-rank"
          };
          // Check and append top winners
          if (yearlyWinners.topwinners && Object.keys(yearlyWinners.topwinners).length > 0) {
            $.each(yearlyWinners.topwinners, function(index, winner) {
              let rankNumber = winner.rank.replace('#', '');
              let rankClassName = rankClass[rankNumber] || "";
              let row = `
                        <tr>
                            <td colspan="5" style="padding: 0 !important; border-radius: 10px; overflow: hidden;">
                                <table class="${rankClassName} rank-wd">
                                  <tbody>
                                      <tr>
                                          <td data-label="Rank" class="inner-rank">${winner.rank}</td>
                                          <td data-label="Name">
                                              <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                                                  <img class="" src="${winner.imagepath}" alt="">
                                                  <p class="m-0">${winner.name}</p>
                                              </div>
                                          </td>
                                          <td data-label="Type">${winner.category}</td>
                                          <td data-label="Place">${winner.city}</td>          
                                          <td class="text-end" data-label="Point11">${winner.points}</td>          
                                      </tr>
                                    </tbody>
                                </table>
                            </td>
                        </tr>`;
              $("#yearlywinnershtml").append(row);
            });
          }

          // Check and append other winners
          if (yearlyWinners.otherwinners && Object.keys(yearlyWinners.otherwinners).length > 0) {
            $.each(yearlyWinners.otherwinners, function(index, winner) {
              let row = `
                        <tr>
                            <td data-label="Account">${winner.rank}</td>
                            <td data-label="Due Date">
                                <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                                    <img class="" src="${winner.imagepath}" alt="">
                                    <p class="m-0">${winner.name}</p>
                                </div>
                            </td>
                            <td data-label="Amount">${winner.category}</td>
                            <td data-label="Period">${winner.city}</td>
                            <td class="text-end" data-label="Point">${winner.points}</td> 
                        </tr>`;
              $("#yearlywinnershtml").append(row);
            });
          }

          // If no winners found
          if ((!yearlyWinners.topwinners || Object.keys(yearlyWinners.topwinners).length === 0) &&
            (!yearlyWinners.otherwinners || Object.keys(yearlyWinners.otherwinners).length === 0)) {
            $("#yearlywinnershtml").html('<tr class="no_records"><td class="text-center" colspan="5">No Records Found</td></tr>');
          }
        } else {
          $("#yearlywinnershtml").html('<tr class="no_records"><td class="text-center" colspan="5">No Records Found</td></tr>');
        }
      },
      error: function() {
        $("#yearlywinnershtml").html('<tr><td colspan="5">Error fetching data</td></tr>');
      }

    });
  }



  function selectMonth(month, clickedElement = null) {
    $.ajax({
      url: '../process.php',
      type: 'POST',
      data: {
        filterid: month
      },
      dataType: 'json',
      success: function(response) {
        // Update month display
        const monthNames = [
          "January", "February", "March", "April", "May", "June",
          "July", "August", "September", "October", "November", "December"
        ];
        const selectedMonth = monthNames[parseInt(month) - 1];
        $("#monthDisplay").html(selectedMonth + " " + new Date().getFullYear());

        // Remove "active" class from all items
        document.querySelectorAll('#monthDropdownMenu .dropdown-item').forEach(item => {
          item.classList.remove('active');
        });

        // Add "active" class to the clicked item
        clickedElement.classList.add('active');

        // Get the tbody of the monthly winners table
        let tbody = $('#profile table tbody');

        if (response.status == 1 && response.monthlyWinners && response.monthlyWinners.length > 0) {
          let monthlyWinners = response.monthlyWinners;
          let html = '';
          let rankClass = {
            1: "first-rank rank-wd",
            2: "second-rank rank-wd",
            3: "third-rank rank-wd"
          };

          // Separate winners by prize category
          let prizeWinners = [];
          let participants = [];

          monthlyWinners.forEach(winner => {
            if (winner.prize_category &&
              winner.prize_category.toLowerCase() !== 'participant' &&
              winner.prize_category !== '') {
              prizeWinners.push(winner);
            } else {
              participants.push(winner);
            }
          });

          // Add prize winners
          prizeWinners.forEach(winner => {
            let rankNumber = winner.rank_number;
            let rankClassName = rankClass[rankNumber] || "";
            console.log(winner);

            html += `
            <tr>
              <td colspan="5" style="padding: 0 !important; border-radius: 10px; overflow: hidden;">
                <table class="${rankClassName}">
                  <tr>
                    <td data-label="Rank" class="inner-rank">${winner.rank}</td>
                    <td data-label="Name">
                      <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                        <img class="" src="${winner.imagepath}" alt="">
                        <p class="m-0">${winner.name}</p>
                      </div>
                    </td>
                    <td data-label="Type">${winner.category}</td>
                    <td data-label="Place">${winner.city}</td>
                    <td class="text-end" data-label="Point">${winner.points}</td> 
                  </tr>
                </table>
              </td>
            </tr>`;
          });

          // Add participants
          participants.forEach(participant => {
            html += `
            <tr>
              <td data-label="Rank">${participant.rank}</td>
              <td data-label="Name">
                <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                  <img class="" src="${participant.imagepath}" alt="">
                  <p class="m-0">${participant.name}</p>
                </div>
              </td>
              <td data-label="Type">${participant.category}</td>
              <td data-label="Place">${participant.city}</td>
              <td class="text-end" data-label="Point">${participant.points}</td> 
            </tr>`;
          });

          tbody.html(html);
        } else {
          // Show No Records Found message
          tbody.html('<tr><td colspan="5" class="text-center">No Records Found</td></tr>');
        }
      },
      error: function() {
        $('#profile table tbody').html('<tr><td colspan="5" class="text-center">Error fetching data</td></tr>');
      }
    });
  }
</script>


<style>


</style>
<section class="banner leaderboard">
  <div class="container h-100 py-5">
    <div class="col-lg-10 mx-auto">
      <div class="row pt-5 align-items-center">
        <div class="col-lg-6 col-md-12 text-lg-start text-center">
          <span>Leaderboard – Rise to the Top!</span>
          <h2 class="sub-banner-hd">Compete, Score, <br>and Win!</h2>
        </div>
        <div class="col-lg-6 col-md-12 text-lg-start text-center">
          <p class="lb-banner mt-2">Stay ahead of the competition and track your progress on our leaderboard! Earn points by participating in quizzes and polls, climb the ranks, and secure your spot at the top. The highest scorer of the month wins a free subscription to exclusive content. Keep playing, keep winning! </p>
        </div>
      </div>
    </div>


    <div class=" mt-5">
      <div class=" border-tab d-block d-sm-flex  justify-content-md-between justify-content-center ">
        <ul class="nav nav-tabs  border-none" id="myTab" role="tablist">
          <li class="nav-item" role="presentation">
            <button class="nav-link exclude-leadership" id="latest-tab" data-bs-toggle="tab" type="button" role="tab" aria-controls="latest" aria-selected="false" onclick="selectType('latest')">Latest</button>
          </li>


          <li class="nav-item" role="presentation">
            <button class="nav-link exclude-leadership" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false" onclick="selectType('profile')">This Month</button>
          </li>
          <li class="nav-item" role="presentation">
            <button class="nav-link exclude-leadership" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false" onclick="selectType('contact')">This Year</button>
          </li>
        </ul>
        <div class="text-center text-sm-right"><a href="<?php echo BASEURL; ?>/leaderboard/prizesandrules.php" class="get-start mb-0 px-5 py-2 mt-1" style="font-size: 18px;">Prizes & Rules</a></div>
      </div>

      <div class="tab-content" id="myTabContent">
        <div class="tab-pane fade show active typecls" id="latest" role="tabpanel" aria-labelledby="latest-tab">
          <?php if (!empty($winners) && isset($winners['topwinners']) && !empty($winners['topwinners'])) {
            $topWinners = $winners['topwinners'];
          ?>
            <div class="winner-card position-relative top3winners">
              <div class="row p-4 pb-5">
                <div class="col-12 text-center">
                  <img class="topbanner" src="<?php echo BASEURL; ?>img/topbanner.png" alt="">
                </div>
                <div class="col-lg-6 col-md-9 col-12 mx-auto mt-4">
                  <div class="d-flex  justify-content-center">
                    <?php if (isset($topWinners['2']) && !empty($topWinners['2'])) { ?>
                      <div class="winners second">
                        <div class="text-center">
                          <div class="position-relative">
                            <img class="winners-img" src="<?php echo $topWinners['2']['imagepath']; ?>" alt="">
                            <img class="second-img" src="<?php echo BASEURL; ?>img/top-b.png" alt="">
                          </div>
                          <h3><?php echo $topWinners['2']['name']; ?></h3>
                          <?php if ($topWinners['2']['category'] != '') { ?>
                            <p><?php echo $topWinners['2']['category']; ?></p>
                            <p class="point"><?php echo $topWinners['2']['points']; ?></p>
                          <?php } ?>
                          <?php if ($topWinners['2']['city'] != '') { ?>
                            <span><i class="fa-solid fa-location-dot pe-2"></i><?php echo $topWinners['2']['city']; ?></span>
                          <?php } ?>
                        </div>
                      </div>
                    <?php } ?>
                    <?php if (isset($topWinners['1']) && !empty($topWinners['1'])) { ?>
                      <div class="winners first ">
                        <div class="text-center">
                          <div class="position-relative">
                            <img class="crown" src="<?php echo BASEURL; ?>img/top.png" alt="">
                            <img class="winners-img" src="<?php echo $topWinners['1']['imagepath']; ?>" alt="">
                            <img class="first-img" src="<?php echo BASEURL; ?>img/top-a.png" alt="">
                          </div>

                          <h3><?php echo $topWinners['1']['name']; ?></h3>
                          <?php if ($topWinners['1']['category'] != '') { ?>
                            <p><?php echo $topWinners['1']['category']; ?></p>
                            <p class="point"><?php echo $topWinners['1']['points']; ?></p>
                          <?php } ?>
                          <?php if ($topWinners['1']['city'] != '') { ?>
                            <span><i class="fa-solid fa-location-dot pe-2"></i><?php echo $topWinners['1']['city']; ?></span>
                          <?php } ?>
                        </div>

                      </div>
                    <?php } ?>
                    <?php if (isset($topWinners['3']) && !empty($topWinners['3'])) { ?>
                      <div class="winners third">
                        <div class="text-center">
                          <div class="position-relative">
                            <img class="winners-img" src="<?php echo $topWinners['3']['imagepath']; ?>" alt="">
                            <!-- <span class="third-img">3</span> -->
                            <img class="third-img" src="<?php echo BASEURL; ?>img/top-c.png" alt="">
                          </div>
                          <h3><?php echo $topWinners['3']['name']; ?></h3>
                          <?php if ($topWinners['3']['category'] != '') { ?>
                            <p><?php echo $topWinners['3']['category']; ?></p>
                            <p class="point"><?php echo $topWinners['3']['points']; ?></p>
                          <?php } ?>
                          <?php if ($topWinners['3']['city'] != '') { ?>
                            <span><i class="fa-solid fa-location-dot pe-2"></i><?php echo $topWinners['3']['city']; ?></span>
                          <?php } ?>
                        </div>
                      </div>
                    <?php } ?>



                  </div>

                </div>
              </div>
              <img class="popper-l" src="<?php echo BASEURL; ?>img/winner-popper.png" alt="">
              <img class="popper-r" src="<?php echo BASEURL; ?>img/winner-popper.png" alt="">
            </div>
          <?php } ?>
          <?php if (isset($winners['otherwinners']) && !empty($winners['otherwinners'])) { ?>
            <div class="listing">
              <table>
                <thead>
                  <tr>
                    <th scope="col">Rank</th>
                    <th scope="col">Name</th>
                    <th scope="col">Type</th>
                    <th scope="col">Place</th>
                    <th scope="col">Point</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($winners['otherwinners'] as $wn) { ?>
                    <tr>
                      <td data-label="Account"><?php echo $wn['rank']; ?></td>
                      <td data-label="Due Date">
                        <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                          <img class="" src="<?php echo $wn['imagepath']; ?>" alt="">
                          <p class="m-0"><?php echo $wn['name']; ?></p>
                        </div>
                      </td>
                      <td data-label="Amount"><?php echo $wn['category']; ?></td>
                      <td data-label="Period"><?php echo $wn['city']; ?></td>
                      <td class="text-end" data-label="Point"><?php echo $wn['points']; ?></td>
                    </tr>
                  <?php } ?>
                </tbody>
              </table>
            </div>
          <?php } ?>

          <?php if (empty($winners['otherwinners']) && empty($winners['topwinners'])) { ?>
            <div class="listing">
              <table>
                <tr>
                  <td class="text-center" colspan="5">No Records Found</td>

                </tr>
              </table>
            </div>
          <?php } ?>

        </div>
        <div class="tab-pane fade typecls" id="profile" role="tabpanel" aria-labelledby="profile-tab">
          <div class="listing">

            <div class="d-flex justify-content-between align-items-center">
              <h2 id="monthDisplay"><?php echo date("F Y"); ?></h2>
              <div>
                <div class="dropdown">
                  <button class="btn btn-secondary dropdown-toggle p-0" type="button" id="monthDropdownButton" data-bs-toggle="dropdown" aria-expanded="false">
                    <span class="material-symbols-outlined">calendar_month</span>
                  </button>
                  <ul class="dropdown-menu date-dd" id="monthDropdownMenu" aria-labelledby="monthDropdownButton">
                    <!-- Months will be injected here by JavaScript -->
                  </ul>
                </div>
              </div>
            </div>


            <!-- <div class="d-flex">
              <h2><php echo date("F Y"); ?></h2>
            </div> -->
            <table>
              <thead>
                <tr>
                  <th scope="col">Rank</th>
                  <th scope="col">Name</th>
                  <th scope="col">Type</th>
                  <th scope="col">Place</th>
                  <th scope="col">Point</th>
                </tr>
              </thead>
              <tbody>
                <?php
                if (isset($monthlyWinners) && !empty($monthlyWinners)) {
                  // Define rank classes for colors
                  $rankClass = array(
                    "1" => "first-rank rank-wd",    // Gold
                    "2" => "second-rank rank-wd",   // Silver  
                    "3" => "third-rank rank-wd"     // Bronze
                  );

                  // Separate winners by prize category
                  $prizeWinners = array();
                  $participants = array();

                  foreach ($monthlyWinners as $winner) {
                    if (
                      isset($winner['prize_category']) &&
                      strtolower($winner['prize_category']) !== 'participant' &&
                      !empty($winner['prize_category'])
                    ) {
                      $prizeWinners[] = $winner;
                    } else {
                      $participants[] = $winner;
                    }
                  }

                  // Display prize winners (ranks 1-3) with special styling
                  foreach ($prizeWinners as $winner) {
                    $rankNumber = $winner['rank_number'];
                    $rankCssClass = isset($rankClass[$rankNumber]) ? $rankClass[$rankNumber] : '';
                ?>
                    <tr>
                      <td colspan="5" style="padding: 0 !important; border-radius: 10px; overflow: hidden;">
                        <table class="<?php echo $rankCssClass; ?>">
                          <tr>
                            <td data-label="Rank" class="inner-rank"><?php echo $winner['rank']; ?></td>
                            <td data-label="Name">
                              <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                                <img class="" src="<?php echo htmlspecialchars($winner['imagepath']); ?>" alt="">
                                <p class="m-0"><?php echo htmlspecialchars($winner['name']); ?></p>
                              </div>
                            </td>
                            <td data-label="Type"><?php echo htmlspecialchars($winner['category']); ?></td>
                            <td data-label="Place"><?php echo htmlspecialchars($winner['city']); ?></td>
                            <td class="text-end" data-label="Point"><?php echo htmlspecialchars($winner['points']); ?></td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                  <?php
                  }

                  // Display participants (no prizes) with regular styling
                  foreach ($participants as $participant) {
                  ?>
                    <tr>
                      <td data-label="Rank"><?php echo $participant['rank']; ?></td>
                      <td data-label="Name">
                        <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                          <img class="" src="<?php echo htmlspecialchars($participant['imagepath']); ?>" alt="">
                          <p class="m-0"><?php echo htmlspecialchars($participant['name']); ?></p>
                        </div>
                      </td>
                      <td data-label="Type"><?php echo htmlspecialchars($participant['category']); ?></td>
                      <td data-label="Place"><?php echo htmlspecialchars($participant['city']); ?></td>
                      <td class="text-end" data-label="Point"><?php echo htmlspecialchars($participant['points']); ?></td>
                    </tr>
                  <?php
                  }
                } else {
                  // No data found
                  ?>
                  <tr>
                    <td class="text-center" colspan="5">No Records Found</td>
                  </tr>
                <?php
                }
                ?>
              </tbody>
            </table>
          </div>
        </div>
        <div class="tab-pane fade typecls" id="contact" role="tabpanel" aria-labelledby="contact-tab">
          <div class="listing">


            <?php
            $startYear = 2024;
            $currentYear = date("Y");
            $endYear = $currentYear;
            ?>
            <div class="d-flex justify-content-between align-items-center">
              <h2 id="year"><?php echo date('Y'); ?></h2>
              <div>
                <div class="dropdown">
                  <button class="btn btn-secondary dropdown-toggle p-0" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
                    <span class="material-symbols-outlined">calendar_month</span>
                  </button>
                  <ul class="dropdown-menu date-dd" aria-labelledby="dropdownMenuButton1">
                    <?php for ($year = $startYear; $year <= $endYear; $year++): ?>
                      <li><a class="dropdown-item" href="javascript:void(0);" onclick="selectYear('<?php echo $year; ?>',this)"><?php echo $year; ?></a></li>
                    <?php endfor; ?>
                  </ul>
                </div>
              </div>
            </div>

            <table>
              <thead>
                <tr>
                  <th scope="col">Rank</th>
                  <th scope="col">Name</th>
                  <th scope="col">Type</th>
                  <th scope="col">Place</th>
                  <th scope="col">Point</th>
                </tr>
              </thead>
              <tbody id="yearlywinnershtml">
                <?php if (!empty($yearlyWinners) && isset($yearlyWinners['topwinners']) && !empty($yearlyWinners['topwinners'])) {
                  $topYearlyWinners = $yearlyWinners['topwinners'];
                  $rankClass = array("1" => "first-rank rank-wd", "2" => "second-rank rank-wd", "3" => "third-rank rank-wd");
                  foreach ($topYearlyWinners as $mn) {
                ?>
                    <tr>
                      <td colspan="5" style="padding: 0 !important;  border-radius: 10px; overflow: hidden;">
                        <table class="<?php echo $rankClass[$mn['rank_number']]; ?>">
                          <tr>
                            <td data-label="Rank" class="inner-rank"><?php echo $mn['rank']; ?></td>
                            <td data-label="Name">
                              <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                                <img class="" src="<?php echo $mn['imagepath']; ?>" alt="">
                                <p class="m-0"><?php echo $mn['name']; ?></p>
                              </div>
                            </td>
                            <td data-label="Type"><?php echo $mn['category']; ?></td>
                            <td data-label="Place"><?php echo $mn['city']; ?></td>
                            <td class="text-end" data-label="Point"><?php echo $mn['points']; ?></td>
                          </tr>
                        </table>
                      </td>
                    </tr>
                <?php }
                }  ?>
                <?php if (!empty($yearlyWinners) && isset($yearlyWinners['otherwinners']) && !empty($yearlyWinners['otherwinners'])) {
                  $otherYearlyWinners = $yearlyWinners['otherwinners'];
                  foreach ($otherYearlyWinners as $omv) {
                ?>
                    <tr>
                      <td data-label="Account"><?php echo $omv['rank']; ?></td>
                      <td data-label="Due Date">
                        <div class="d-flex align-items-center justify-content-md-start justify-content-end">
                          <img class="" src="<?php echo $omv['imagepath']; ?>" alt="">
                          <p class="m-0"><?php echo $omv['name']; ?></p>
                        </div>
                      </td>
                      <td data-label="Amount"><?php echo $omv['category']; ?></td>
                      <td data-label="Period"><?php echo $omv['city']; ?></td>
                      <td class="text-end" data-label="Point"><?php echo $omv['points']; ?></td>
                    </tr>
                <?php }
                } ?>

                <?php if (empty($yearlyWinners['otherwinners']) && empty($yearlyWinners['topwinners'])) { ?>
                  <tr class="no_records">
                    <td class="text-center" colspan="5">No Records Found</td>

                  </tr>

                <?php } ?>
              </tbody>

            </table>
          </div>
        </div>
      </div>


    </div>
  </div>
  </div>
</section>







<?php include "../footer.php"; ?>
<script>
  $(document).ready(function() {
    $("#latest-tab").trigger('click');
  });
</script>

<script>
  const monthNames = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];

  const monthDropdown = document.getElementById("monthDropdownMenu");

  monthNames.forEach((name, index) => {
    const monthNumber = String(index + 1).padStart(2, '0'); // e.g. "01", "02", ...
    const li = document.createElement("li");
    const a = document.createElement("a");

    a.className = "dropdown-item";
    a.href = "javascript:void(0);";
    a.textContent = name;
    a.dataset.month = monthNumber;
    a.onclick = () => selectMonth(monthNumber, a);

    li.appendChild(a);
    monthDropdown.appendChild(li);
  });
</script>


<script>
  // Wait for DOM to be ready
  document.addEventListener("DOMContentLoaded", function() {
    const currentMonth = String(new Date().getMonth() + 1).padStart(2, '0');
    const dropdownItems = document.querySelectorAll('#monthDropdownMenu .dropdown-item');

    dropdownItems.forEach(item => {
      if (item.dataset.month === currentMonth) {
        // Trigger the same logic as a user click
        selectMonth(currentMonth, item);
      }
    });


    // Auto-select current year
    const currentYear = new Date().getFullYear().toString();
    const yearItems = document.querySelectorAll('.dropdown-menu .dropdown-item');

    yearItems.forEach(item => {
      if (item.textContent.trim() === currentYear) {
        selectYear(currentYear, item);
      }
    });

  });
</script>