<?php
error_reporting(0);

$ppnnow = 11;

// Redirect if 'index.php' is found in the URL
$requestUri = $_SERVER['REQUEST_URI'];
if (strpos($requestUri, 'index.php') !== false) {
    $newUrl = str_replace('index.php', '', $requestUri);
    header('Location: ' . $newUrl);
    exit;
}

// Start the session
// session_start();

// Include essential files
include "config/connect.php";
include 'pages/control_page.php';
include 'list_data/list_data.php';
include 'list_data/sweetalert.php';
include "config/routeros_api.class.php";
include "config/whatsapp_api.php";
include "config/tanggal_indo.php";
include "tracking/kata_kunci.php";

// Initialize global variables
$List = new Listdata();
$date = date('Y-m-d H:i:s');

// Check user session and redirect to login if necessary
if (!isset($_SESSION['user']) && !isset($_SESSION['master'])) {
    header('Location: login.php');
    exit();
}

// Define User ID based on session
$UserId = isset($_SESSION['user']) ? $_SESSION['user'] : '0';

// Initialize menu array
$armenu2 = [];

// Prepare and execute query to get menu IDs
$stmt = $pdo->prepare("SELECT id FROM master_menu WHERE master_akses = '0' AND id != '13'");
$stmt->execute();
$menu_ids = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);

foreach ($menu_ids as $id) {
    $armenu2[$id]['menu'] = $id;
}

// Define user data and access permissions
if (isset($_SESSION['user'])) {
    // Fetch user details
    $stmt = $pdo->prepare("SELECT id, id_data_server, id_group_akses, nama, profile FROM user_akses WHERE id = :id");
    $stmt->bindParam(':id', $_SESSION['user']);
    $stmt->execute();
    $UserAdminAkses = $stmt->fetch(PDO::FETCH_ASSOC);

    // Fetch group access details
    $stmt = $pdo->prepare("SELECT id_data_server,akses,per_marketing,tagihan_berjalan FROM group_akses WHERE id = :id");
    $stmt->bindParam(':id', $UserAdminAkses['id_group_akses']);
    $stmt->execute();
    $GroupUserAdminAkses = $stmt->fetch(PDO::FETCH_ASSOC);
    // Define SQL filters based on user access
    $SvId = $UserAdminAkses['id_data_server'];
    // $SvId = implode(',', array_map('intval', $UserAdminAkses['id_data_server']));
    $SvNama = $UserAdminAkses['nama'];
    //jika user adalah marketing
    if($GroupUserAdminAkses['per_marketing'] == 'Y'){
      $SqlSvData = "id_data_server IN ($SvId) AND id_marketing = '$UserAdminAkses[id]' AND";
      $SqlDataWHIdM = "WHERE id_data_server IN ($SvId) AND id_marketing = '$UserAdminAkses[id]'";
    }
    else{
      $SqlSvData = "id_data_server IN ($SvId) AND";
      $SqlDataWHIdM = "WHERE id_data_server IN ($SvId)";
    }
    
    $bulanIni = date("Y-m");
    //Logika Hanya Muncul Tagihan Bulan Berjalan di Tunggakan
    if($GroupUserAdminAkses['tagihan_berjalan'] == 'Y'){
        $tagihanJalan = "SUBSTRING(limit_pembayaran, 1, 7) = '$bulanIni' AND";
    } else {
        $tagihanJalan = "";
    }
    // $SqlSvData = "id_data_server IN ($SvId) AND";
    $SqlDataWH = "WHERE id IN ($SvId)";
    $SqlDataWHId = "WHERE id_data_server IN ($SvId)";
    $SqlDataWHLikeId = "WHERE id_data_server LIKE '%$SvId%'";
    $SqlDataId = "AND id_data_server IN ($SvId)";

    // Merge menu access
    $array2 = json_decode($GroupUserAdminAkses['akses'], true);
    $mergedArray = array_replace($armenu2, $array2);
    $menu_akses = json_encode($mergedArray);

    $profile = $UserAdminAkses['profile'];
} else {
    // Fetch master user details
    $stmt = $pdo->prepare("SELECT id, nama_pemilik, akses, profile,expaired_date, quick_setting FROM data_server WHERE id = :id");
    $stmt->bindParam(':id', $_SESSION['master']);
    $stmt->execute();
    $UserMaster = $stmt->fetch(PDO::FETCH_ASSOC);
    $SvId = $UserMaster['id'];
    // $SvId = implode(',', array_map('intval', $UserMaster['id']));
    $SvNama = $UserMaster['nama_pemilik'];

    if ($UserMaster['id'] == '1') {
        // Define SQL filters for master user
        $SqlSvData = '';
        $SqlDataWH = "WHERE id != '1'";
        $SqlDataWHId = "";
        $SqlDataWHIdM = "";
        $SqlDataWHLikeId = "";
        $SqlDataId = "";

        $menu_akses = $UserMaster['akses'];
    } else {
        // Define SQL filters for non-master user
        $SqlSvData = "id_data_server = '$SvId' AND";
        $SqlDataWH = "WHERE id IN ($SvId)";
        $SqlDataWHId = "WHERE id_data_server IN ($SvId)";
        $SqlDataWHIdM = "WHERE id_data_server IN ($SvId)";
        $SqlDataWHLikeId = "WHERE id_data_server LIKE '%$SvId%'";
        $SqlDataId = "AND id_data_server IN ($SvId)";
    }
    
    $tagihanJalan = "";
    // Merge menu access
    $array2 = json_decode($UserMaster['akses'], true);
    $mergedArray = array_replace($armenu2, $array2);
    $menu_akses = json_encode($mergedArray);

    $profile = $UserMaster['profile'];
}

// Ambil data dari POST atau variabel lain
$json_array = json_decode($menu_akses, true);

// Query untuk mendapatkan data menu dan submenu dari database
$menu_query = "
  SELECT * FROM master_menu WHERE id != '26'
  ORDER BY urutan ASC
";
$result = mysqli_query($con, $menu_query);

if (!$result) {
  echo 'Error executing query: ' . mysqli_error($con);
  exit;
}

// Simpan hasil query ke dalam array
$menus = [];
while ($row = mysqli_fetch_assoc($result)) {
  $menus[] = $row;
}

// Index berdasarkan ID menu untuk akses cepat
$menu_map = [];
foreach ($menus as $menu) {
  $menu_map[$menu['id']] = $menu;
}

// Bebaskan hasil query
mysqli_free_result($result);


// Buat array \$menus_user berdasarkan ID di \$json_array
$menus_user = array_filter($menus, function($menu) use ($json_array) {
    return isset($json_array[$menu['id']]);
});

// encrypt url
define('ENCRYPTION_KEY', hex2bin('9a307dfcf16ac2e4406b1a59a31c1d096eafe37e40c60ddee4bb827b6a947079'));
define('ENCRYPTION_METHOD', 'AES-256-CBC');

function encrypt_url($data) {
    $iv = random_bytes(16);
    $encrypted = openssl_encrypt($data, ENCRYPTION_METHOD, ENCRYPTION_KEY, OPENSSL_RAW_DATA, $iv);
    // Gabungkan IV hex + "::" + encrypted base64, lalu base64 encode seluruh string
    $result = base64_encode(bin2hex($iv) . "::" . base64_encode($encrypted));
    return $result;
}

function decrypt_url($data) {
    $decoded = base64_decode($data);
    if ($decoded === false) return false;
    $parts = explode('::', $decoded);
    if (count($parts) !== 2) return false;

    $iv = hex2bin($parts[0]);
    $encrypted_data = base64_decode($parts[1]);
    return openssl_decrypt($encrypted_data, ENCRYPTION_METHOD, ENCRYPTION_KEY, OPENSSL_RAW_DATA, $iv);
}


// Data Pages AND POST
// if ($_SERVER['QUERY_STRING'] != '') {
//     $pag = decrypt_url($_SERVER['QUERY_STRING']);
//     $page = explode("|", $pag);

//     $pages = $page[0];
// } else {
//     $pages = 'dashboard';
// }

if ($_SERVER['QUERY_STRING'] != '') {
    $pag = decrypt_url($_SERVER['QUERY_STRING']);
    $page = explode("|", $pag);
    
     $pagex = $page[0];

     $menu_links = array_column($menus_user, 'link_menu');
     $menu_other = array_column($menus, 'link_menu');

    // if (in_array($pagex, $menu_links)) {
    //     $pages = $pagex;
    // } else {
    //     $pages = (in_array($pagex, $menu_links) && !in_array($pagex, $menu_other)) ? $pagex : 'dashboard';
    // }
     $pages = $pagex;

} else {
    $pages = 'dashboard';
}
//DATA Page
$Page = new Pages();
$Page->set_page($pages);

$stm = $pdo->prepare("SELECT status_payment_gateway FROM data_server WHERE id IN (:id)");
$stm->bindParam(':id', $SvId);
$stm->execute();
$datastatus = $stm->fetch(PDO::FETCH_ASSOC);
$statuspaygw = $datastatus['status_payment_gateway'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ManjaPro</title>
  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
  <!-- Tempusdominus Bootstrap 4 -->
  <link rel="stylesheet" href="plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">
  <!-- iCheck -->
  <link rel="stylesheet" href="plugins/icheck-bootstrap/icheck-bootstrap.min.css">
  <!-- JQVMap -->
  <!-- <link rel="stylesheet" href="plugins/jqvmap/jqvmap.min.css"> -->
  <!-- Theme style -->
  <link rel="stylesheet" href="dist/css/adminlte.min.css">
  <!-- overlayScrollbars -->
  <link rel="stylesheet" href="plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
  <!-- Daterange picker -->
  <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker.css">
  <!-- summernote -->
  <link rel="stylesheet" href="plugins/summernote/summernote-bs4.min.css">
  <!-- Icon Aplikasi -->
  <link rel="icon" href="dist/img/logo-sm.png" type="image/gif" />
  <!-- Data Tabel -->
  <link rel="stylesheet" href="plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="plugins/datatables-responsive/css/responsive.bootstrap4.min.css">
  <link rel="stylesheet" href="plugins/datatables-buttons/css/buttons.bootstrap4.min.css">
  <link rel="stylesheet" href="plugins/select2/css/select2.min.css">
  <link rel="stylesheet" href="plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">
  <!-- Bootstrap Color Picker -->
  <link rel="stylesheet" href="plugins/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css">
  <!-- Bootstrap4 Duallistbox -->
  <link rel="stylesheet" href="plugins/bootstrap4-duallistbox/bootstrap-duallistbox.min.css">
  <!-- BS Stepper -->
  <link rel="stylesheet" href="plugins/bs-stepper/css/bs-stepper.min.css">
  <!-- dropzonejs -->
  <link rel="stylesheet" href="plugins/dropzone/min/dropzone.min.css">
  <!-- Custom CSS -->
  <link rel="stylesheet" href="dist/customcss/form_image_load.css">
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <!--jquery http-->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <!-- Load Google Maps API library -->
  <script>
  (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
    key: "AIzaSyA1MgLuZuyqR_OGY3ob3M52N46TDBRI_9k",
    v: "weekly",
    // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
    // Add other bootstrap parameters as needed, using camel case.
  });
</script>
<style type="text/css">
  /* Styling untuk marquee container */
  .marquee-container {
      height: 20px; /* Tinggi elemen marquee */
      overflow: hidden; /* Menghindari teks yang meluap */
      position: relative;
      top: 0; /* Memastikan marquee berada di bawah navbar */
      width: 100%; /* Lebar elemen marquee */
  }

  /* Styling untuk marquee */
  marquee {
      line-height: 20px; /* Menyelaraskan teks dengan tinggi container */
      color: white;
  }
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

   <!--Preloader-->
  <div class="preloader flex-column justify-content-center align-items-center" style="background: rgba(128,128,128,0.5);">
    <img class="animation__shake" src="dist/img/logo-sm.png" alt="AdminLTELogo" height="140" width="140">
  </div>

  <!-- Navbar -->
  <nav class="main-header navbar navbar-expand navbar-white navbar-light">
    <!-- Left navbar links -->
    <ul class="navbar-nav">
      <li class="nav-item">
        <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
      </li>
    </ul>
    <!-- Right navbar links -->
    <ul class="navbar-nav ml-auto">
      <!-- Navbar Search -->
      <!-- <li class="nav-item">
        <a class="nav-link" data-widget="navbar-search" href="#" role="button">
          <i class="fas fa-search"></i>
        </a>
        <div class="navbar-search-block">
          <form class="form-inline">
            <div class="input-group input-group-sm">
              <input class="form-control form-control-navbar" type="search" placeholder="Search" aria-label="Search">
              <div class="input-group-append">
                <button class="btn btn-navbar" type="submit">
                  <i class="fas fa-search"></i>
                </button>
                <button class="btn btn-navbar" type="button" data-widget="navbar-search">
                  <i class="fas fa-times"></i>
                </button>
              </div>
            </div>
          </form>
        </div>
      </li> -->
      <!-- Messages Dropdown Menu -->
      <!-- <li class="nav-item dropdown">
        <a class="nav-link" data-toggle="dropdown" href="#">
          <i class="far fa-comments"></i>
          <span class="badge badge-danger navbar-badge">3</span>
        </a>
        <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
          <a href="#" class="dropdown-item">
            <div class="media">
              <img src="dist/img/user1-128x128.jpg" alt="User Avatar" class="img-size-50 mr-3 img-circle">
              <div class="media-body">
                <h3 class="dropdown-item-title">
                  Brad Diesel
                  <span class="float-right text-sm text-danger"><i class="fas fa-star"></i></span>
                </h3>
                <p class="text-sm">Call me whenever you can...</p>
                <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p>
              </div>
            </div>
          </a>
          <div class="dropdown-divider"></div>
          <a href="#" class="dropdown-item">
            <div class="media">
              <img src="dist/img/user8-128x128.jpg" alt="User Avatar" class="img-size-50 img-circle mr-3">
              <div class="media-body">
                <h3 class="dropdown-item-title">
                  John Pierce
                  <span class="float-right text-sm text-muted"><i class="fas fa-star"></i></span>
                </h3>
                <p class="text-sm">I got your message bro</p>
                <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p>
              </div>
            </div>
          </a>
          <div class="dropdown-divider"></div>
          <a href="#" class="dropdown-item">
            <div class="media">
              <img src="dist/img/user3-128x128.jpg" alt="User Avatar" class="img-size-50 img-circle mr-3">
              <div class="media-body">
                <h3 class="dropdown-item-title">
                  Nora Silvester
                  <span class="float-right text-sm text-warning"><i class="fas fa-star"></i></span>
                </h3>
                <p class="text-sm">The subject goes here</p>
                <p class="text-sm text-muted"><i class="far fa-clock mr-1"></i> 4 Hours Ago</p>
              </div>
            </div>
          </a>
          <div class="dropdown-divider"></div>
          <a href="#" class="dropdown-item dropdown-footer">See All Messages</a>
        </div>
      </li> -->
      <!-- Notifications Dropdown Menu -->
      <!-- <li class="nav-item dropdown">
        <a class="nav-link" data-toggle="dropdown" href="#">
          <i class="far fa-bell"></i>
          <span class="badge badge-warning navbar-badge">15</span>
        </a>
        <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
          <span class="dropdown-item dropdown-header">15 Notifications</span>
          <div class="dropdown-divider"></div>
          <a href="#" class="dropdown-item">
            <i class="fas fa-envelope mr-2"></i> 4 new messages
            <span class="float-right text-muted text-sm">3 mins</span>
          </a>
          <div class="dropdown-divider"></div>
          <a href="#" class="dropdown-item">
            <i class="fas fa-users mr-2"></i> 8 friend requests
            <span class="float-right text-muted text-sm">12 hours</span>
          </a>
          <div class="dropdown-divider"></div>
          <a href="#" class="dropdown-item">
            <i class="fas fa-file mr-2"></i> 3 new reports
            <span class="float-right text-muted text-sm">2 days</span>
          </a>
          <div class="dropdown-divider"></div>
          <a href="#" class="dropdown-item dropdown-footer">See All Notifications</a>
        </div>
      </li> -->
      <?php if (isset($_SESSION['master'])) { ?>
      <li class="nav-item">
        <a class="nav-link">
          <p>Kedaluarsa : <?php echo $UserMaster['expaired_date']; ?></p>
        </a>
      </li>
      <?php } ?>
      <li class="nav-item">
        <a class="nav-link" data-widget="fullscreen" href="iframe.php" role="button">
          <i class="fas fa-expand-arrows-alt"></i>
        </a>
      </li>
      <!-- <li class="nav-item">
        <a class="nav-link" data-widget="control-sidebar" data-slide="true" href="#" role="button">
          <i class="fas fa-th-large"></i>
        </a>
      </li> -->
    </ul>
  </nav>
  <!-- /.navbar -->
  <?php if (isset($_SESSION['master'])) { 
    $expiredDate = $UserMaster['expaired_date'];
    $currentDate = date('Y-m-d');
    $diff = strtotime($expiredDate) - strtotime($currentDate);
    $daysLeft = ceil($diff / (60 * 60 * 24));
  
    if ($daysLeft < 0) { ?>
        <div class="marquee-container" style="background-color: red;">
          <marquee direction="left">Masa aktif Aplikasi BilsPro telah berakhir <b><?php echo substr($daysLeft,1); ?></b> hari lalu</marquee>
        </div>
      <?php
    $status_menu = "Tidak Aktif";
       } 
    elseif($daysLeft <= 10 && $daysLeft >= 0) { ?>
        <div class="marquee-container" style="background-color: green;">
          <marquee direction="left">Masa aktif Aplikasi BilsPro akan berakhir <b><?php echo $daysLeft; ?></b> hari lagi</marquee>
        </div>
    <?php
    $status_menu = "Aktif"; } 
    else {
      $status_menu = "Aktif";
    }
  }
  else {
    $stmt = $pdo->prepare("SELECT expaired_date FROM data_server WHERE id = :id");
    $stmt->bindParam(':id', $GroupUserAdminAkses['id_data_server']);
    $stmt->execute();
    $AksesUserMenu = $stmt->fetch(PDO::FETCH_ASSOC);
    $expiredDate = $AksesUserMenu['expaired_date'];
    $currentDate = date('Y-m-d');
    $diff = strtotime($expiredDate) - strtotime($currentDate);
    $daysLeft = ceil($diff / (60 * 60 * 24));
    if ($daysLeft < 0) {
      $status_menu = "Tidak Aktif";
    }
    else{
      $status_menu = "Aktif";
    }
  } 
  ?>

  <!-- Main Sidebar Container -->
  <aside class="main-sidebar sidebar-dark-primary elevation-4">
    <!-- Brand Logo -->
    <a href="index.php" class="brand-link">
      <img src="dist/img/logo_clr.png" alt="AdminLTE Logo" width="130px" class="ml-3" style="opacity: .8">
      <p style="font-size : 12px;" class="ml-3 mb-0">Managemen Jaringan Profesional</p>
      <!--<span class="brand-text font-weight-light">BilsPro</span>-->
    </a>
    <!-- Sidebar -->
    <div class="sidebar">
      <!-- Sidebar user panel (optional) -->
      <div class="user-panel mb-3 d-flex">
        <div class="image pt-2">
          <img src="img/user/<?php echo $profile; ?>" class="img-circle elevation-2" alt="User Image">
        </div>
        <div class="info">
          <a href="?<?php echo encrypt_url('setting_profile'); ?>" class="d-block"><?php echo $SvNama; ?></a>
          <?php if($status_menu == "Aktif") { ?>
          <a href="?<?php echo encrypt_url('setting_profile'); ?>" class="fas fa-genderless text-success"><i class="ml-2 mb-0 text-light">Active</i></a>
          <?php } else { ?>
          <a href="?<?php echo encrypt_url('setting_profile'); ?>" class="fas fa-genderless text-danger"><i class="ml-2 mb-0 text-light">Expaired</i></a>
          <?php } ?>
        </div>
      </div>
      <!-- Sidebar Menu -->
      <nav class="mt-2">
        <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">

          <?php 
            //Menu Quick Setting
            if (isset($_SESSION['master']) && $UserMaster['quick_setting'] == 'on' && $status_menu == "Aktif") { 
          ?>
          <li class="nav-item">
            <a href="?<?php echo encrypt_url('quick_setting_app'); ?>" class="nav-link">
              <i class="fas fa-cog nav-icon"></i>
              <p>Quick Setting</p>
            </a>
          </li>
        <?php } ?> 

        <?php 

          function render_submenu($menu_id, $menus, $json_array, $Page, $status_menu) {
              echo '<ul class="nav nav-treeview">';
              foreach ($menus as $submenu) {
                  if ($submenu['master'] == $menu_id) {
                      $submenu_id = htmlspecialchars($submenu['id']);
                      $submenu_name = htmlspecialchars($submenu['nama']);
                      $submenu_link = htmlspecialchars($submenu['link_menu']);
                      $submenu_icon = htmlspecialchars($submenu['icon']);
                      $submenu_active = ($Page->get_page() == $submenu_link) ? 'active' : '';
                      $menu_href = ($status_menu == "Aktif") ? '?'.encrypt_url($submenu_link) : '?'.encrypt_url('setting_profile');

                      echo '<li class="nav-item">';
                      echo '    <a href="'. $menu_href .'" class="nav-link ' . $submenu_active . '">';
                      echo '        <i class="' . $submenu_icon . ' nav-icon"></i>';
                      echo '        <p>' . $submenu_name . '</p>';
                      echo '    </a>';
                      echo '</li>';
                  }
              }
              echo '</ul>';
          }

          // Tampilkan menu utama
          foreach ($menus as $menu) {
              $menu_id = htmlspecialchars($menu['id']);
              $menu_name = htmlspecialchars($menu['nama']);
              $menu_link = htmlspecialchars($menu['link_menu']);
              $menu_icon = htmlspecialchars($menu['icon']);
              $is_active = ($Page->get_page() == $menu_link) ? 'active' : '';
              $menu_href = ($status_menu == "Aktif") ? '?'.encrypt_url($menu_link) : '?'.encrypt_url('setting_profile');
              // Cek apakah menu_id ada dalam JSON array
              $data_menu = isset($json_array[$menu_id]);


              if (!empty($data_menu)) {
                  if ($menu['sub_menu'] == 'N' && $menu['master'] == '0') {
                      // Tampilkan item menu tanpa submenu
                      echo '<li class="nav-item">';
                      echo '    <a href="'. $menu_href .'" class="nav-link ' . $is_active . '">';
                      echo '        <i class="nav-icon ' . $menu_icon . '"></i>';
                      echo '        <p>' . $menu_name . '</p>';
                      echo '    </a>';
                      echo '</li>';
                  } elseif ($menu['sub_menu'] == 'Y' && $menu['master'] == '0') {
                      // Cek ID menu aktif
                      $link_menu = $Page->get_page();
                      $menuid_master = '';
                      foreach ($menus as $item) {
                          if ($item['link_menu'] == $link_menu) {
                              $menuid_master = $item['master'];
                              break;
                          }
                      }

                      // Tampilkan item menu dengan submenu
                      echo '<li class="nav-item ' . ($menuid_master == $menu_id ? 'menu-open' : '') . '">';
                      echo '    <a href="#" class="nav-link ' . ($menuid_master == $menu_id ? 'active' : '') . '">';
                      echo '        <i class="nav-icon ' . $menu_icon . '"></i>';
                      echo '        <p>' . $menu_name;
                      if ($menu['sub_menu'] == 'Y') {
                          echo '            <i class="right fas fa-angle-left"></i>';
                      }
                      echo '        </p>';
                      echo '    </a>';
                      render_submenu($menu_id, $menus, $json_array, $Page, $status_menu);
                      echo '</li>';
                  }
              }
          }

       
          ?>
          <li class="nav-item">
            <a href="?<?php echo encrypt_url('logout'); ?>" class="nav-link">
              <i class="fas fa-share nav-icon"></i>
              <p>Logout</p>
            </a>
          </li>
          <br><br><br><br>
        </ul>
      </nav>
      <!-- /.sidebar-menu -->
    </div>
    <!-- /.sidebar -->
  </aside>
  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">

  <?php
  
//   echo $pages . ' ' . $page[1];

  include 'pages/'.$Page->get_page().'.php';

  ?>
  
  </div>

  <!-- Control Sidebar -->
  <aside class="control-sidebar control-sidebar-dark">
    <!-- Control sidebar content goes here -->
  </aside>
  <!-- /.control-sidebar -->
</div>
<!-- /.wrapper -->

<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
  $.widget.bridge('uibutton', $.ui.button)
</script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- ChartJS -->
<!--<script src="plugins/chart.js/Chart.min.js"></script>-->
<!-- Sparkline -->
<script src="plugins/sparklines/sparkline.js"></script>
<!-- JQVMap -->
<!-- <script src="plugins/jqvmap/jquery.vmap.min.js"></script>
<script src="plugins/jqvmap/maps/jquery.vmap.usa.js"></script> -->
<!-- jQuery Knob Chart -->
<script src="plugins/jquery-knob/jquery.knob.min.js"></script>
<!-- daterangepicker -->
<script src="plugins/moment/moment.min.js"></script>
<script src="plugins/daterangepicker/daterangepicker.js"></script>
<!-- Tempusdominus Bootstrap 4 -->
<script src="plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
<!-- Summernote -->
<script src="plugins/summernote/summernote-bs4.min.js"></script>
<!-- overlayScrollbars -->
<script src="plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="dist/js/demo.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="dist/js/pages/dashboard.js"></script>
<!-- Auto Upload File -->
<script src="dist/customjs/upload.js"></script>
<!-- DataTables  & Plugins -->
<script src="plugins/datatables/jquery.dataTables.min.js"></script>
<script src="plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="plugins/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
<script src="plugins/datatables-buttons/js/dataTables.buttons.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
<script src="plugins/jszip/jszip.min.js"></script>
<script src="plugins/pdfmake/pdfmake.min.js"></script>
<script src="plugins/pdfmake/vfs_fonts.js"></script>
<script src="plugins/datatables-buttons/js/buttons.html5.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.print.min.js"></script>
<script src="plugins/datatables-buttons/js/buttons.colVis.min.js"></script>
<!-- Select2 -->
<script src="plugins/select2/js/select2.full.min.js"></script>
<!-- <script src="plugins/select2/js/select2.min.js"></script> -->
<script src="plugins/dropzone/min/dropzone.min.js"></script>
<!-- Bootstrap Switch -->
<script src="plugins/bootstrap-switch/js/bootstrap-switch.min.js"></script>
<!-- BS-Stepper -->
<script src="plugins/bs-stepper/js/bs-stepper.min.js"></script>
<!-- bootstrap color picker -->
<script src="plugins/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js"></script>
<!-- date-range-picker -->
<script src="plugins/inputmask/jquery.inputmask.min.js"></script>
<script src="plugins/bootstrap4-duallistbox/jquery.bootstrap-duallistbox.min.js"></script>
<script>
  $(function () {
    $("#example1").DataTable({
      "responsive": true, 
      "lengthChange": false, 
      "autoWidth": false,
      "buttons": [ "excel", "pdf", "print"]
    }).buttons().container().appendTo('#example1_wrapper .col-md-6:eq(0)');
    $("#example2").DataTable({
      "responsive": true,
      "autoWidth": false
    });
    $("#example3").DataTable({
        "responsive": true, 
        "lengthChange": true, 
        "autoWidth": false,
        "buttons": [ "excel", "pdf", "print" ]
    }).buttons().container().appendTo('#example3_wrapper .col-md-6:eq(0)');
  });
</script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        var rupiahInputs = document.querySelectorAll(".rupiah");

        // Tambahkan format Rupiah saat halaman dimuat
        rupiahInputs.forEach(function(input) {
            input.value = formatRupiah(input.value, "Rp. ");
        });

        // Event delegation untuk input dengan class rupiah
        document.body.addEventListener("input", function(e) {
            if (e.target.classList.contains("rupiah")) {
                e.target.value = formatRupiah(e.target.value, "Rp. ");
            }
        });
    });

    /* Fungsi formatRupiah */
    function formatRupiah(angka, prefix) {
        var number_string = angka.replace(/[^,\d]/g, "").toString(),
            split = number_string.split(","),
            sisa = split[0].length % 3,
            rupiah = split[0].substr(0, sisa),
            ribuan = split[0].substr(sisa).match(/\d{3}/gi);

        // Tambahkan titik jika angka sudah menjadi ribuan
        if (ribuan) {
            separator = sisa ? "." : "";
            rupiah += separator + ribuan.join(".");
        }

        rupiah = split[1] != undefined ? rupiah + "," + split[1] : rupiah;
        return prefix == undefined ? rupiah : rupiah ? prefix + rupiah : "";
    }
</script>
<script>
  $('#myForm').on('submit', function(e){
  $('#myModal').modal('show');
  e.preventDefault();
  });
</script>
<!-- Page specific script -->
<script>
  $(function () {
    //Initialize Select2 Elements
    $('.select2').select2()

    //Initialize Select2 Elements
    $('.select2bs4').select2({
      theme: 'bootstrap4'
    })

    //Datemask dd/mm/yyyy
    $('#datemask').inputmask('dd/mm/yyyy', { 'placeholder': 'dd/mm/yyyy' })
    //Datemask2 mm/dd/yyyy
    $('#datemask2').inputmask('mm/dd/yyyy', { 'placeholder': 'mm/dd/yyyy' })
    //Money Euro
    $('[data-mask]').inputmask()

    //Date picker
    $('#reservationdate').datetimepicker({
        format: 'L'
    });

    //Date and time picker
    $('#reservationdatetime').datetimepicker({ icons: { time: 'far fa-clock' } });

    //Date range picker
    $('#reservation').daterangepicker()
    //Date range picker with time picker
    $('#reservationtime').daterangepicker({
      timePicker: true,
      timePickerIncrement: 30,
      locale: {
        format: 'MM/DD/YYYY hh:mm A'
      }
    })
    //Date range as a button
    $('#daterange-btn').daterangepicker(
      {
        ranges   : {
          'Today'       : [moment(), moment()],
          'Yesterday'   : [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
          'Last 7 Days' : [moment().subtract(6, 'days'), moment()],
          'Last 30 Days': [moment().subtract(29, 'days'), moment()],
          'This Month'  : [moment().startOf('month'), moment().endOf('month')],
          'Last Month'  : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        startDate: moment().subtract(29, 'days'),
        endDate  : moment()
      },
      function (start, end) {
        $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'))
      }
    )

    //Timepicker
    $('#timepicker').datetimepicker({
      format: 'LT'
    })

    //Bootstrap Duallistbox
    $('.duallistbox').bootstrapDualListbox()

    //Colorpicker
    $('.my-colorpicker1').colorpicker()
    //color picker with addon
    $('.my-colorpicker2').colorpicker()

    $('.my-colorpicker2').on('colorpickerChange', function(event) {
      $('.my-colorpicker2 .fa-square').css('color', event.color.toString());
    })

    $("input[data-bootstrap-switch]").each(function(){
      $(this).bootstrapSwitch('state', $(this).prop('checked'));
    })

  })
  
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA1MgLuZuyqR_OGY3ob3M52N46TDBRI_9k&callback=initMap" async defer></script>
<script>
var map;
var marker;

function initMap() {
    var latitudeInput = document.getElementById('latitude').value;
    var longitudeInput = document.getElementById('longitude').value;

    // Cek apakah input form memiliki nilai
    if (latitudeInput && longitudeInput) {
        var pos = {
            lat: parseFloat(latitudeInput),
            lng: parseFloat(longitudeInput)
        };
        initMapWithPos(pos);
    } else {
        // Jika input form kosong, gunakan geolocation
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var pos = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                initMapWithPos(pos);
                updateFormInputs(pos.lat, pos.lng);
            }, function() {
                handleLocationError(true);
            });
        } else {
            handleLocationError(false);
        }
    }
}

// Fungsi untuk menginisialisasi peta dengan posisi yang diberikan
function initMapWithPos(pos) {
    map = new google.maps.Map(document.getElementById('map'), {
        center: pos,
        zoom: 17,
        mapTypeId: 'hybrid',
        mapTypeControl: false,
        streetViewControl: false,
        fullscreenControl: true,
    });

    updateMarker(pos.lat, pos.lng);

    // Event listener untuk menambahkan marker saat peta diklik
    map.addListener('click', function(e) {
        var latitude = e.latLng.lat().toFixed(6);
        var longitude = e.latLng.lng().toFixed(6);
        updateMarker(latitude, longitude);
        updateFormInputs(latitude, longitude);
    });
}

// Fungsi untuk menampilkan marker pada peta
function updateMarker(latitude, longitude) {
    if (marker) {
        marker.setPosition({lat: parseFloat(latitude), lng: parseFloat(longitude)});
    } else {
        marker = new google.maps.Marker({
            position: {lat: parseFloat(latitude), lng: parseFloat(longitude)},
            map: map
        });
    }
    
    map.setCenter(marker.getPosition());
}

// Fungsi untuk memperbarui nilai input form
function updateFormInputs(latitude, longitude) {
    document.getElementById('latitude').value = latitude;
    document.getElementById('longitude').value = longitude;

    // Perbarui input latlong
    document.getElementById('latlong').value = `${latitude}, ${longitude}`;
}

// Tangani error jika geolocation tidak berhasil
function handleLocationError(browserHasGeolocation) {
    alert(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

document.addEventListener('DOMContentLoaded', function() {
    const latlongInput = document.getElementById('latlong');

    // Ambil input tersembunyi berdasarkan atribut data-maps
    const latitudeInput = document.querySelector('input[data-maps="latitude"]');
    const longitudeInput = document.querySelector('input[data-maps="longitude"]');

    // Set nilai latlong jika latitude dan longitude sudah ada
    if (latitudeInput.value && longitudeInput.value) {
        latlongInput.value = `${latitudeInput.value}, ${longitudeInput.value}`;
    }

    latlongInput.addEventListener('input', function() {
        const latlongValue = latlongInput.value.split(',');

        // Validasi format latitude dan longitude
        const latLongRegex = /^(-?\d+(\.\d+)?),\s*(-?\d+(\.\d+)?)$/; // Format: latitude, longitude
        if (latLongRegex.test(latlongInput.value.trim())) {
            // Pastikan kita memiliki dua nilai: latitude dan longitude
            if (latlongValue.length === 2) {
                const lat = latlongValue[0].trim();
                const long = latlongValue[1].trim();

                // Update input tersembunyi
                latitudeInput.value = lat;
                longitudeInput.value = long;

                // Update marker dan center peta
                updateMarker(lat, long);
                map.setCenter({lat: parseFloat(lat), lng: parseFloat(long)});
            }
        } else {
            // Jika format tidak valid, beri delay sebelum menampilkan pesan
            setTimeout(function() {
                latlongInput.value = ''; // Kosongkan nilai
                latlongInput.placeholder = 'Isi dengan format yang sesuai'; // Tampilkan pesan
                latitudeInput.value = ''; // Kosongkan input tersembunyi
                longitudeInput.value = ''; // Kosongkan input tersembunyi
            }, 500); // Delay 500ms
        }
    });

    // Event listener untuk mengupdate latlong input saat latitude atau longitude diubah
    latitudeInput.addEventListener('input', function() {
        const lat = latitudeInput.value;
        const long = longitudeInput.value;

        // Update latlong input
        latlongInput.value = `${lat}, ${long}`;
    });

    longitudeInput.addEventListener('input', function() {
        const lat = latitudeInput.value;
        const long = longitudeInput.value;

        // Update latlong input
        latlongInput.value = `${lat}, ${long}`;
    });
});

</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const dropdown0 = document.getElementById('dropdown0');
    const dropdown1 = document.getElementById('dropdown1');
    const dropdown2 = document.getElementById('dropdown2');
    const dropdown3 = document.getElementById('dropdown3');
    const dropdown4 = document.getElementById('dropdown4');
    const dropdown5 = document.getElementById('dropdown5');
    const dropdown6 = document.getElementById('dropdown6');

    // Menyembunyikan dropdown 2-6 pada awal
    const groupDropdowns = [
        document.getElementById('group-dropdown2'),
        document.getElementById('group-dropdown3'),
        document.getElementById('group-dropdown4'),
        document.getElementById('group-dropdown5'),
        document.getElementById('group-dropdown6')
    ];

    groupDropdowns.forEach(group => {
        if (group) group.style.display = 'none';
    });

    // Fungsi untuk mengupdate dropdown
    function updateDropdown(dropdown, data) {
        if (!dropdown) return; // Cek apakah dropdown ada

        const selectedId = dropdown.getAttribute('data-id') || dropdown.value; // Ambil nilai data-id atau value saat ini

        // Hapus semua opsi
        dropdown.innerHTML = ''; 

        // Tambahkan opsi default jika ada lebih dari satu opsi
        if (data.length > 1) {
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = 'Pilih';
            dropdown.appendChild(defaultOption);
        }

        // Tambahkan opsi baru dari data server
        data.forEach(option => {
            const optionElement = document.createElement('option');
            optionElement.value = option.id;
            optionElement.textContent = option.nama;

            // Set opsi sebagai selected jika id sesuai dengan data yang dipilih sebelumnya
            if (option.id === selectedId) {
                optionElement.selected = true;
            }
            dropdown.appendChild(optionElement);
        });

        // Tampilkan atau sembunyikan grup berdasarkan jumlah opsi
        const groupElement = dropdown.closest('.form-group');
        groupElement.style.display = data.length > 1 ? 'block' : 'none'; // Tampilkan atau sembunyikan grup dropdown
    }

    // Fungsi untuk mengupdate semua dropdown berdasarkan pilihan dropdown0 atau dropdown1 
    function updateAllDropdowns() {
        const selectedOption0 = dropdown0.value;
        const selectedOption1 = dropdown1.value;

        if (dropdown2) {
            fetch(`list_data/dropdown.php?dropdown=dropdown2&option=${encodeURIComponent(selectedOption0)}&option1=${encodeURIComponent(selectedOption1)}`)
                .then(response => response.json())
                .then(data => updateDropdown(dropdown2, data))
                .catch(error => console.error('Error fetching dropdown2 data:', error));
        }

        if (dropdown3) {
            fetch(`list_data/dropdown.php?dropdown=dropdown3&option=${encodeURIComponent(selectedOption0)}`)
                .then(response => response.json())
                .then(data => updateDropdown(dropdown3, data))
                .catch(error => console.error('Error fetching dropdown3 data:', error));
        }

        if (dropdown4) {
            fetch(`list_data/dropdown.php?dropdown=dropdown4&option=${encodeURIComponent(selectedOption0)}`)
                .then(response => response.json())
                .then(data => updateDropdown(dropdown4, data))
                .catch(error => console.error('Error fetching dropdown4 data:', error));
        }

        if (dropdown5) {
            fetch(`list_data/dropdown.php?dropdown=dropdown5&option=${encodeURIComponent(selectedOption0)}`)
                .then(response => response.json())
                .then(data => updateDropdown(dropdown5, data))
                .catch(error => console.error('Error fetching dropdown5 data:', error));
        }

        if (dropdown6) {
            fetch(`list_data/dropdown.php?dropdown=dropdown6&option=${encodeURIComponent(selectedOption0)}`)
                .then(response => response.json())
                .then(data => updateDropdown(dropdown6, data))
                .catch(error => console.error('Error fetching dropdown6 data:', error));
        }
    }

    // Mengisi dropdown0 dari server
    if (dropdown0) {
        fetch('list_data/dropdown.php?dropdown=dropdown0')
            .then(response => response.json())
            .then(options => {
                options.forEach(option => {
                    const optionElement = document.createElement('option');
                    optionElement.value = option.id;
                    optionElement.textContent = option.label;  // Pastikan bahwa label sesuai dengan data dari server
                    dropdown0.appendChild(optionElement);
                });

                // Jika dropdown0 sudah memiliki nilai, update dropdown lainnya
                if (dropdown0.value) {
                    updateAllDropdowns();
                }
            })
            .catch(error => console.error('Error fetching dropdown0 data:', error));

        // Event listener untuk dropdown0
        dropdown0.addEventListener('change', function() {
            updateAllDropdowns();
        });
    }

    // Mengisi dropdown1 dari server
    if (dropdown1) {
        fetch('list_data/dropdown.php?dropdown=dropdown1')
            .then(response => response.json())
            .then(options => {
                options.forEach(option => {
                    const optionElement = document.createElement('option');
                    optionElement.value = option.id;
                    optionElement.textContent = option.label; // Pastikan bahwa label sesuai dengan data dari server
                    dropdown1.appendChild(optionElement);
                });

                // Jika dropdown1 sudah memiliki nilai, update dropdown lainnya
                if (dropdown1.value) {
                    updateAllDropdowns();
                }

                // Tampilkan atau sembunyikan grup dropdown berdasarkan pilihan
                const groupElement = document.getElementById('group-hotspot');
                if (groupElement) { // Memeriksa apakah groupElement ada
                    if (dropdown1.value === "Hotspot") {
                        groupElement.style.display = 'block'; // Tampilkan grup dropdown
                    } else {
                        groupElement.style.display = 'none'; // Sembunyikan grup dropdown
                    }
                }
            })
            .catch(error => console.error('Error fetching dropdown1 data:', error));

        // Event listener untuk dropdown1
        dropdown1.addEventListener('change', function() {
            updateAllDropdowns();

            // Tampilkan atau sembunyikan grup dropdown berdasarkan pilihan
            const groupElement = document.getElementById('group-hotspot');
            if (groupElement) { // Memeriksa apakah groupElement ada
                if (dropdown1.value === "Hotspot") {
                    groupElement.style.display = 'block'; // Tampilkan grup dropdown
                } else {
                    groupElement.style.display = 'none'; // Sembunyikan grup dropdown
                }
            }
        });
    }



    // Jika dropdown1 sudah memiliki nilai saat halaman dimuat, update dropdown lainnya
    if (dropdown1 && dropdown1.value) {
        updateAllDropdowns();
    }
});

</script>

<script type="text/javascript">
function fileValidation(){
    var fileInput = document.getElementById('file');
    var filePath = fileInput.value;
    var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
    if(!allowedExtensions.exec(filePath)){
        alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
        fileInput.value = '';
        return false;
    }else{
        //Image preview
        if (fileInput.files && fileInput.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').innerHTML = '<img style="max-width : 500px;" src="'+e.target.result+'"/>';
            };
            reader.readAsDataURL(fileInput.files[0]);
        }
    }
}
</script>
<script>
  function updateSecondDropdown() {
    const firstDropdown = document.getElementById('firstDropdown');
    const secondDropdown = document.getElementById('secondDropdown');

    // Cek apakah dropdown pertama ada
    if (!firstDropdown || !secondDropdown) {
        console.warn('Dropdown tidak ditemukan di halaman.');
        return; // Keluar dari fungsi jika salah satu dropdown tidak ada
    }

    const selectedValue = firstDropdown.value;
    const dataId = secondDropdown.getAttribute('data-id');

    secondDropdown.innerHTML = '';
    // Clear existing options except the first option
    if (!dataId) {
        secondDropdown.innerHTML = '<option value="">Pilih</option>';
    }

    if (!selectedValue) {
        // If no value is selected in the first dropdown, keep the default option
        return;
    }

    // Fetch data using the selected value
    fetch(`list_data/form_topologi.php?category_id=${selectedValue}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // Check if there's a data-id and if it's not empty
            if (dataId) {
                // Add data-id as the first option if it does not exist in the fetched data
                const dataIdOption = document.createElement('option');
                dataIdOption.value = dataId;
                dataIdOption.textContent = `${dataId}`;
                dataIdOption.selected = true;
                // Check if the dataId option is already present
                const existingOptions = Array.from(secondDropdown.options).map(option => option.value);
                if (!existingOptions.includes(dataId)) {
                    secondDropdown.insertBefore(dataIdOption, secondDropdown.firstChild);
                }
            }

            // Add options from the fetched data only if data is an array
            if (Array.isArray(data)) {
                data.forEach(subcategory => {
                    const option = document.createElement('option');
                    option.value = subcategory.port_odp;
                    option.textContent = subcategory.port_odp;
                    secondDropdown.appendChild(option);
                });
            } else {
                console.warn('No data returned or data is not an array');
            }

            // Ensure the second dropdown is always visible if there are options
            secondDropdown.style.display = 'block';
        })
        .catch(error => {
            console.error('Error fetching data:', error);
            // Ensure the second dropdown is visible even if there's an error
            secondDropdown.style.display = 'block';
            // Optionally, you can add a default error message
            secondDropdown.innerHTML = '<option value="">Tidak ada data</option>';
        });
}

// Initial call to populate the second dropdown if the first dropdown has a selected value
document.addEventListener('DOMContentLoaded', function() {
    // Cek apakah dropdown pertama ada sebelum memanggil fungsi
    const firstDropdown = document.getElementById('firstDropdown');
    if (firstDropdown && firstDropdown.value) {
        updateSecondDropdown();
    }
});

</script>

</body>
</html>
