<?php
  if (isset($_POST['tambah'])) 
  {
    $menu_ids = $_POST['menu_ids'];
    $db = mysqli_query($con, "SELECT * FROM master_menu");
    if ($db) {
        while ($menu = mysqli_fetch_assoc($db)) {
            $menuid = $menu['id'];
            if (isset($menu_ids[$menuid])) {
                $menutam = !empty($menu['user_menu']) ? explode("_", $menu['user_menu']) : [];
                if (isset($menu_ids[$menuid]['sub_menu']) && is_array($menu_ids[$menuid]['sub_menu'])) {
                    foreach ($menutam as $key) {
                        if (!in_array($key, $menu_ids[$menuid]['sub_menu'])) {
                            $menu_ids[$menuid]['sub_menu'][] = $key;
                        }
                    }
                } else {
                    $menu_ids[$menuid]['sub_menu'] = $menutam;
                }
            }
        }
        $json_string = json_encode($menu_ids);
    }

    $nominal = preg_replace("/[^0-9]/","",$_POST['hsw']);
    
    $hashedPassword = password_hash($_POST[psw], PASSWORD_DEFAULT);
    
    $SQL = "
    INSERT INTO data_server (nama_server, nama_pemilik, nomor_whatsapp, alamat, kabupaten, username, password, harga_sewa, akses, status,  pesan_kirim_tagihan, pesan_peringatan_tagihan, pesan_isolir_pelanggan, pesan_melunasi_tagihan, pesan_koneksi_off, pesan_registrasi, pesan_aktivasi)
    VALUES ('$_POST[nsv]', '$_POST[npl]', '$_POST[nwa]', '$_POST[alt]', '', '$_POST[usm]', '$hashedPassword', '$nominal', '$json_string', 'Aktif', '*TAGIHAN LAYANAN INTERNET*\r\n\r\n#ket\r\nLimit Pembayaran tanggal #lmt\r\n\r\nNama                : *#usr*\r\nLayanan             : #lyn\r\n\r\nJumlah Tagihan : *Rp. #tot*\r\n\r\n_#Pesan Otomatis Sistem_', 'Pelanggan yang terhormat,\r\na/n. *#usr*\r\n\r\nHari ini adalah hari terakhir untuk melakukan pembayaran internet dengan total perbayaran sebagai berikut :\r\nTotal Tagihan : *Rp. #tot*\r\n\r\n_#Pesan Otomatis Sistem_', 'Pelanggan yang terhormat,\r\nMohon maaf saat ini internet kita matikan, karena anda belum melunasi tagihan, Lakukanlah pembayaran untuk terus menikmati layanan kami. \r\nTerimakasih..!!\r\n\r\n_#Pesan Otomatis Sistem_', 'Terimakasih telah melakukan pembayaran tagihan layanan internet\r\n\r\n_#Pesan otomatis sistem_', 'Pelanggan yang terhormat,\r\nStatus koneksi anda termonitor OFF dari server kami beberapa menit lalu, Jika ada kendala silahkan hubungi atau informasikan kepada kami.\r\nTerimakasih..!!', '*REGISTRASI PELANGGAN BARU*\r\n\r\nAtas Nama : *#usr*\r\nAlamat    : #add\r\n\r\nLayanan\r\nJenis Layanan  : #jly\r\nPaket Berlanggaan  : #lyn\r\nHarga Layanan : *#hly*\r\n\r\n#Status   : *Pendaftaran berhasil*\r\n\r\n_#Pesan Otomatis Sistem_', 'Pelanggan yang terhormat,\nLayanan anda telah di Aktivasi\n\nNama  : *#usr*\nID         : #ppp\n\nSelamat menikmati layanan internet kami \nTerimakasih.\n\n_#Pesan Otomatis Sistem_')";

    $input = mysqli_query($con, $SQL);
    if ($input) 
    {
      sweetAlert("Data telah di tambah", "success");
    }
  }
?>

<!-- Main content -->
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header">
            <div class="row">
              <div class="col-sm-6">
                <h3 class="card-title">Server Akses</h3>
              </div>
              <div class="col-sm-6">
                <ol class="float-sm-right mb-0">
                  <!--<a type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#staticBackdrop">Tambah</a>-->
                </ol>
              </div>
              <!-- Modal Tambah -->
              <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header">
                        <h5 class="modal-title" id="staticBackdropLabel">Tambah Server Aplikasi</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                      </div>
                      <div class="modal-body">
                        <div class="row">
                          <div class="col-sm-6">
                            <div class="card-body pb-0">
                              <div class="form-group">
                                <label>Nama Server</label>
                                <input type="text" class="form-control" name="nsv" required="required">
                              </div>
                              <div class="form-group">
                                <label>Nama Pemilik</label>
                                <input type="text" class="form-control" name="npl" required="required">
                              </div>
                              <div class="form-group">
                                <label>Nomor WhatsApp</label>
                                <input type="text" class="form-control" name="nwa" required="required">
                              </div>
                              <div class="form-group">
                                <label>Alamat</label>
                                <input type="text" class="form-control" name="alt" required="required">
                              </div>
                              <div class="form-group">
                                <label>Username</label>
                                <input type="text" class="form-control" name="usm" required="required">
                              </div>
                              <div class="form-group">
                                <label>Password</label>
                                <input type="text" class="form-control" name="psw" required="required">
                              </div>
                            </div>
                          </div>
                          <div class="col-sm-6">
                            <div class="card-body pb-0">
                              <div class="form-group">
                                <label>Harga Sewa</label>
                                <input type="text" class="form-control rupiah" id="rupiah0"  name="hsw" required="required">
                              </div>
                              <label>List Akses</label><br>
                              <div class="row">
                              <?php
                                $db = mysqli_query($con, "SELECT * FROM master_menu WHERE master_akses = '1' ORDER BY urutan");
                                while ($menu = mysqli_fetch_assoc($db)) {
                                  $menu_id = htmlspecialchars($menu['id']);
                                  echo '<div class="col-6">';
                                  echo '<div class="form-group form-check">';
                                  echo '<input type="checkbox" class="form-check-input" value="' . $menu_id . '" name="menu_ids[' . $menu_id . '][menu]" checked>';
                                  echo '<label class="form-check-label" for="exampleCheck' . $menu['id'] . '">' . $menu['nama'] . '</label>';
                                  echo '</div>';
                                  echo '</div>';
                                }
                              ?>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" name="tambah" class="btn btn-primary" value="Tambah">
                      </div>
                    </form>
                  </div>
                </div>
              </div>
              <!-- END Modal Tambah -->
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
            <table id="example2" class="table table-bordered table-striped">
              <thead>
              <tr>
                <th>No</th>
                <th>Nama Server</th>
                <th>Alamat</th>
                <th>Nama Admin</th>
                <th>Nomor WhatsApp</th>
                <th>Harga Sewa</th>
                <th>Status</th>
                <th>Expired</th>
                <th>Action</th>
              </tr>
              </thead>
              <tbody>
              <?php
                $no = 1;
                $aserver = mysqli_query($con,"SELECT * FROM data_server WHERE id !='1' ORDER BY expaired_date DESC");
                while ($server = mysqli_fetch_assoc($aserver)) 
                {
              ?>
              <tr>
                <td><?php echo $no; ?></td>
                <td><?php echo $server['nama_server']; ?></td>
                <td style="max-width : 130px;"><?php echo $server['alamat']; ?></td>
                <td><?php echo $server['nama_pemilik']; ?></td>
                <td style="max-width : 100px;"><?php echo $server['nomor_whatsapp']; ?></td>
                <td>Rp. <?php echo number_format($server['harga_sewa']); ?></td>
                <td><?php  
                  if ($server['expaired_date'] >= date('Y-m-d')) { ?>
                  <span class="badge badge-success">Aktif</span>  
                  <?php } else { ?> 
                  <span class="badge badge-danger">Tidak Aktif</span>
                  <?php } ?>
                </td>
                <td><?php echo formatIndo($server['expaired_date']); ?></td>
                <td>
                  <form method="post" enctype="multipart/form-data">
                    <a href="?<?php echo encrypt_url('detail_data_server|'.$server['id']); ?>" class="btn btn-info btn-sm m-1">Detail</a>
                    <a type="button" class="btn btn-secondary btn-sm m-1" data-toggle="modal" data-target="#modal-edit<?php echo $server['id'];?>">Edit
                    </a>
                    <input type="submit" name="hapus<?php echo $server['id'];?>" class="btn btn-danger btn-sm m-1" value="Hapus">
                  </form>
                </td>
              </tr>
              <!-- Modal Edit -->
              <div class="modal fade" id="modal-edit<?php echo $server['id'];?>" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header">
                        <h5 class="modal-title" id="staticBackdropLabel">Tambah Server Aplikasi</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                      </div>
                      <div class="modal-body">
                        <div class="row">
                          <div class="col-sm-6">
                            <div class="card-body pb-0">
                              <div class="form-group">
                                <label>Nama Server</label>
                                <input type="text" class="form-control" value="<?php echo $server['nama_server']; ?>" name="nsv" required="required">
                              </div>
                              <div class="form-group">
                                <label>Nama Pemilik</label>
                                <input type="text" class="form-control" value="<?php echo $server['nama_pemilik']; ?>" name="npl" required="required">
                              </div>
                              <div class="form-group">
                                <label>Nomor WhatsApp</label>
                                <input type="text" class="form-control" value="<?php echo $server['nomor_whatsapp']; ?>" name="nwa" required="required">
                              </div>
                              <div class="form-group">
                                <label>Alamat</label>
                                <input type="text" class="form-control" value="<?php echo $server['alamat']; ?>" name="alt" required="required">
                              </div>
                              <div class="form-group">
                                <label>Username</label>
                                <input type="text" class="form-control" value="<?php echo $server['username']; ?>" name="usm" required="required">
                              </div>
                            </div>
                          </div>
                          <div class="col-sm-6">
                            <div class="card-body pb-0">
                              <div class="form-group">
                                <label>Harga Sewa</label>
                                <input type="text" class="form-control rupiah" id="rupiah0" value="<?php echo $server['harga_sewa']; ?>" name="hsw" required="required">
                              </div>
                              <div class="form-group">
                                <label>Status Aplikasi</label>
                                <select class="form-control" name="stt">
                                  <option value="Aktif" <?php if($server['status'] == 'Aktif') { echo "selected";} ?>>Aktif</option>
                                  <option value="Tidak Aktif" <?php if($server['status'] == 'Tidak Aktif') { echo "selected";} ?>>Tidak Aktif</option>
                                </select>
                              </div>
                              <label>List Akses</label><br>
                              <div class="row">
                                <?php
                                    // Query untuk mendapatkan data dari database
                                    $db = mysqli_query($con, "SELECT * FROM master_menu WHERE master_akses = '1' AND master = '0' ORDER BY urutan");

                                    if ($db) {
                                        // JSON data (pastikan JSON ini berasal dari sumber yang benar)
                                        $json_data = $server['akses'];
                                        
                                        // Decode JSON data
                                        $json_array = json_decode($json_data, true);
                                        // echo "<pre>";
                                        // print_r($json_array);
                                        // echo "</pre>";

                                        while ($menu = mysqli_fetch_assoc($db)) {
                                            $menu_id = htmlspecialchars($menu['id']);
                                            $menu_name = htmlspecialchars($menu['nama']);
                                            $user_menu = !empty($menu['user_menu']) ? explode("_", $menu['user_menu']) : [];

                                            $checked_menu = isset($json_array[$menu_id]);

                                            echo '<div class="col-6">';
                                            echo '    <div class="form-group form-check">';
                                            echo '        <input type="checkbox" class="form-check-input" value="' . $menu_id . '" name="menu_ids[' . $menu_id . '][menu]" ' . ($checked_menu ? 'checked' : '') . '>';
                                            echo '        <label class="form-check-label" for="exampleCheck' . $menu_id . '">' . $menu_name . '</label>';
                                            echo '    </div>';
                                            echo '</div>';
                                        }

                                        // Pastikan untuk membebaskan hasil query
                                        mysqli_free_result($db);
                                    } else {
                                        echo 'Error executing query: ' . mysqli_error($con);
                                    }

                                    // Tutup koneksi
                                    // mysqli_close($con);
                                    ?>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" name="edit<?php echo $server['id'];?>" class="btn btn-warning" value="Edit">
                      </div>
                    </form>
                    <?php
                    if (isset($_POST['edit'.$server['id']])) 
                    {
                      $menu_ids = $_POST['menu_ids'];
                      $db = mysqli_query($con, "SELECT * FROM master_menu");
                      if ($db) {
                          while ($menu = mysqli_fetch_assoc($db)) {
                              $menuid = $menu['id'];
                              if (isset($menu_ids[$menuid])) {
                                  $menutam = !empty($menu['user_menu']) ? explode("_", $menu['user_menu']) : [];
                                  if (isset($menu_ids[$menuid]['sub_menu']) && is_array($menu_ids[$menuid]['sub_menu'])) {
                                      foreach ($menutam as $key) {
                                          if (!in_array($key, $menu_ids[$menuid]['sub_menu'])) {
                                              $menu_ids[$menuid]['sub_menu'][] = $key;
                                          }
                                      }
                                  } else {
                                      $menu_ids[$menuid]['sub_menu'] = $menutam;
                                  }
                              }
                          }
                          $json_string = json_encode($menu_ids);
                      }
                      
                        $hashedPassword = password_hash($_POST[psw], PASSWORD_DEFAULT);
                      $nominal = preg_replace("/[^0-9]/","",$_POST['hsw']);
                      $input = mysqli_query($con,"UPDATE data_server SET 
                        nama_server='$_POST[nsv]',
                        nama_pemilik='$_POST[npl]',
                        nomor_whatsapp='$_POST[nwa]',
                        alamat='$_POST[alt]',
                        username='$_POST[usm]',
                        harga_sewa='$nominal',
                        akses='$json_string',
                        status='$_POST[stt]' 
                        WHERE id = '$server[id]' ");
                      if ($input) 
                      {
                        sweetAlert("Data telah di ubah", "success");
                      }
                    }
                    if (isset($_POST['hapus'.$server['id']])) {
                      $iddata = $server['id'];
                      deleteAlert("data_server", $iddata);
                    }
                    ?>
                  </div>
                </div>
              </div>
              <!-- END Modal Edit -->
            <?php $no++; } ?>
              </tbody>
            </table>
          </div>
          <!-- /.card-body -->
        </div>
        <!-- /.card -->
      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  </div>
  <!-- /.container-fluid -->
</section>
<!-- /.content -->