<!-- 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">Profile Paket</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-lg">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header bg-primary">
                        <h5 class="modal-title" id="staticBackdropLabel">Tambah Profile Paket</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-md-6">
                                <div class="card-body">
                                    <div class="form-group">
                                        <label>Nama Server</label>
                                        <select class="form-control" name="ids" required>
                                            <option value="">Pilih</option>
                                            <?php 
                                            $List = new Listdata();
                                            $List->set_list("data_server", $SqlDataWH);
                                            foreach ($List->get_list() as $key => $value): ?>
                                                <option value="<?php echo $value['id']; ?>"><?php echo $value['nama_server']; ?></option>
                                            <?php endforeach ?>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label>Jenis Profile</label>
                                        <select class="form-control" name="jenis" data-select="jenis-select1" required>
                                            <option value="">Pilih</option>
                                            <option value="PPPOE">PPPOE</option>
                                            <option value="Hotspot">Hotspot</option>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                      <label>Nama Profile Di Mikrotik</label>
                                      <input type="text" class="form-control" name="profile" required>
                                      <i class="text-danger"><small>Nama Profile Harus sama dengan yang ada di Mikrotik</small></i>
                                    </div>
                                    <div class="form-group" id="group-jenis1">
                                        <label>Jenis Hotspot</label>
                                        <select class="form-control" name="jenishs" id="jenis-select2" data-select="jenis-select2">
                                            <option value="">Pilih</option>
                                            <option value="1">Sekali Pakai</option>
                                            <option value="0">Berulangkali</option>
                                        </select>
                                        <i class="text-danger"><small>Pilih <b>Berulangkali</b> jika user hotspot di tagihan setiap bulan</small></i>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card-body">
                                    <div class="form-group">
                                        <label>Nama Paket</label>
                                        <input type="text" class="form-control" name="nama" required>
                                    </div>
                                    <div class="form-group">
                                        <label>Harga Paket</label>
                                        <input type="text" class="form-control rupiah" name="harga" required>
                                    </div>
                                    <div class="form-group" id="group-jenis3">
                                        <label>Fee Agen Voucher</label>
                                        <input type="text" class="form-control rupiah" name="fee" id="fee">
                                        <i class="text-danger">Isi jika menggunakan Aplikasi Agen Voucher</i>
                                    </div>
                                    <div class="form-group" id="group-jenis2">
                                        <label>Durasi</label>
                                        <input type="text" class="form-control" name="durasi" placeholder="6H" id="durasi">
                                        <i class="text-danger">Contoh : 3H => 3 Jam , 1D => 1 Hari </i>
                                    </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>
                    <?php 
if (isset($_POST['tambah'])) {
    try {
        // Ambil dan sanitasi data dari form
        $status = ($_POST['jenishs'] == 1) ? 1 : NULL;
        $nominal = preg_replace("/[^0-9]/", "", $_POST['harga']);
        $cekfee = preg_replace("/[^0-9]/", "", $_POST['fee']);
        $fee = (!empty($cekfee)) ? $cekfee : NULL;

        // Ambil server dari database
        $stmt = $pdo->prepare("SELECT * FROM setting_mikrotik WHERE id_data_server = :id_data_server");
        $stmt->execute([':id_data_server' => $_POST['ids']]);
        $servers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $messages = []; // Array untuk menyimpan pesan

        foreach ($servers as $server) {
            $mikrotikName = $server['nama'];
            $API = new RouterosAPI();
            $API->debug = false;

            // Koneksi ke MikroTik
            if ($API->connect2($server['ip_address'], $server['username'], $server['password'], $server['port_api'])) {
                $profileName = $_POST['profile'];

                if ($_POST['jenis'] == 'PPPOE') {
                    // Cek profil PPPOE
                    $profiles = $API->comm('/ppp/profile/print');
                    $found = false;

                    foreach ($profiles as $profile) {
                        if ($profile['name'] === $profileName) {
                            $found = true;
                            break;
                        }
                    }

                    if (!$found) {
                        $messages[] = "Profil PPPOE <b>$profileName</b> di <b>$mikrotikName</b> tidak ada.";
                    }
                } else {
                    // Cek profil Hotspot
                    $profiles = $API->comm('/ip/hotspot/user/profile/print');
                    $found = false;
                    $profileId = null;

                    foreach ($profiles as $profile) {
                        if ($profile['name'] === $profileName) {
                            $profileId = $profile['.id'];
                            $found = true;
                            break;
                        }
                    }

                    if ($found) {
                        // Jika status sama dengan 1
                        if ($status == 1 ) {
                            // Pastikan intervalFormat() sudah terdefinisi
                            $interval = intervalFormat($_POST['durasi']);
                            
                            // Skrip On Login yang akan dipasang
                            $onLoginScript = ':local nama $user; :local tanggal [/system clock get date]; :local waktu [/system clock get time]; :if ([/ip hotspot user get [find name=$nama] comment] = "") do={/ip hotspot user set [find name=$nama] comment="Login.$tanggal $waktu"; :log warning ("User " . $nama . " berhasil login.")} else={:log warning ("User " . $nama . " berhasil melakukan login ulang.")}; :if ([/system schedule find name=$nama] = "") do={/system schedule add name=$nama interval='.$interval.' on-event="/ip hotspot active remove [find user=$nama]; /ip hotspot user remove [find name=$nama]; /system schedule remove [find name=$nama]" start-date=$tanggal start-time=$waktu;}';

                            // Update skrip On Login
                            $API->comm('/ip/hotspot/user/profile/set', [
                                '.id' => $profileId,
                                'on-login' => $onLoginScript,
                            ]);
                        } 
                        // else {
                        //     $messages[] = "Gagal Upload Script: Profil Hotspot <b>$profileName</b> di <b>$mikrotikName</b> tidak aktif atau status tidak sesuai.";
                        // }
                    } else {
                        $messages[] = "Profil Hotspot <b>$profileName</b> di <b>$mikrotikName</b> tidak ditemukan.";
                    }
                }
            } else {
                $messages[] = "Gagal terhubung ke MikroTik <b>$mikrotikName</b>.";
            }
        }

        // Cek pesan sebelum menyimpan ke database
        if (empty($messages)) {
            $stmt = $pdo->prepare("INSERT INTO profile_paket 
                (id_data_server, jenis_profile, nama_profile, durasi, nama, harga_paket, vi_agen, status) 
                VALUES (:id_data_server, :jenis_profile, :nama_profile, :durasi, :nama, :harga_paket, :vi_agen, :status)");
            $stmt->bindParam(':id_data_server', $_POST['ids']);
            $stmt->bindParam(':jenis_profile', $_POST['jenis']);
            $stmt->bindParam(':nama_profile', $_POST['profile']);
            $stmt->bindParam(':durasi', $_POST['durasi']);
            $stmt->bindParam(':nama', $_POST['nama']);
            $stmt->bindParam(':harga_paket', $nominal);
            $stmt->bindParam(':vi_agen', $fee);
            $stmt->bindParam(':status', $status);
            $stmt->execute();
            sweetAlert("Profile Paket Telah ditambahkan", "success");
        } else {
            // Menampilkan pesan error jika ada
            $message = implode("<br>", $messages);
            detailAlert($message, strpos($message, 'tidak ada') !== false || strpos($message, 'Gagal') !== false);
        }

    } catch (PDOException $e) {
        // Menangani kesalahan dalam koneksi database atau query
        sweetAlert("Terjadi kesalahan: " . $e->getMessage(), "error");
    } catch (Exception $e) {
        // Menangani kesalahan umum
        sweetAlert("Terjadi kesalahan: " . $e->getMessage(), "error");
    }
}
?>


                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
            <table id="example2" class="table table-bordered table-striped">
              <thead>
              <tr>
                <th>Nama Server</th>
                <th>Jenis Profile</th>
                <th>Nama Profile Mikrotik</th>
                <th>Nama Paket</th>
                <th>Harga Paket</th>
                <th>Status</th>
                <th>Action</th>
              </tr>
              </thead>
              <tbody>
              <?php
                $apaket = mysqli_query($con,"SELECT * FROM profile_paket $SqlDataWHId ORDER BY nama ASC");
                while ($paket = mysqli_fetch_assoc($apaket)) 
                { 
              ?>
              <tr>
                <td>
                  <?php
                    $asv = mysqli_query($con,"SELECT nama_server FROM data_server WHERE id = '$paket[id_data_server]'");
                    $sv = mysqli_fetch_assoc($asv);
                      echo $sv['nama_server']; 
                  ?>
                </td>
                <td><?php echo $paket['jenis_profile']; ?></td>
                <td><?php echo $paket['nama_profile']; ?></td>
                <td><?php echo $paket['nama']; ?></td>
                <td><?php echo "Rp. ".number_format($paket['harga_paket']);
                if ($paket['vi_agen'] != NULL ) {
                   echo '<br><i class="text-danger">Fee Agen Rp. '.number_format($paket['vi_agen']).'</i>';
                 } ?>
                </td>
                <td><?php if($paket['status'] == 1 ){ echo "Sekali Pakai";} ?></td>
                <td>
                <form method="post" enctype="multipart/form-data">
                  <a href="?<?php echo encrypt_url('profile_paket_edit|'.$paket['id']);?>" class="btn btn-secondary btn-sm">Edit
                  </a>
                  <input type="submit" name="hapus<?php echo $paket['id'];?>" class="btn btn-danger btn-sm m-1" value="Hapus">
                </form>
                </td>
              </tr>
              <?php 
                if (isset($_POST['hapus'.$paket['id']])) 
                {
                    $iddata = $paket['id'];
                    deleteAlert("profile_paket", $iddata);
                } 
              }
              ?>
              </tbody>
            </table>
          </div>
          <!-- /.card-body -->
        </div>
        <!-- /.card -->
      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  </div>
  <!-- /.container-fluid -->
</section>
<!-- /.content -->

<script>
// Ambil semua elemen dropdown dalam modal
const jenisSelects = document.querySelectorAll('[data-select]');

// Sembunyikan semua grup pada awalnya
document.querySelectorAll('[id^="group-"]').forEach(group => {
    group.style.display = 'none';
});

// Fungsi untuk mengupdate tampilan grup
function updateGroupVisibility() {
    const jenisSelect = document.querySelector('select[name="jenis"]');
    const jenishsSelect = document.querySelector('select[name="jenishs"]');
    const group1 = document.getElementById('group-jenis1');
    const group2 = document.getElementById('group-jenis2');
    const group3 = document.getElementById('group-jenis3');
    const select2 = document.getElementById('jenis-select2');
    const fee = document.getElementById('fee');
    const durasi = document.getElementById('durasi');

    // Reset nilai input grup
    function resetGroup(group) {
        const input = group.querySelector('select, input');
        if (input) {
            input.value = '';
        }
        group.style.display = 'none';
    }

    // Tampilkan grup berdasarkan pilihan di dropdown
    if (jenisSelect.value === "Hotspot") {
        group1.style.display = 'block';
        group1.querySelector('select').required = true; 
    } else {
        resetGroup(group1);
    }

    if (jenishsSelect) {
        if (jenishsSelect.value === "1") {
            group2.style.display = 'block'; 
            group3.style.display = 'block'; 
            jenishsSelect.required = true; 
            fee.required = true;
            durasi.required = true;
        } else {
            resetGroup(group2);
            resetGroup(group3);
            jenishsSelect.required = false; 
            fee.required = false;
            durasi.required = false;
        }
    }
}


// Cek apakah select sudah ada isinya dan update tampilan
function initializeGroupVisibility() {
    const jenisSelect = document.querySelector('select[name="jenis"]');
    const jenishsSelect = document.querySelector('select[name="jenishs"]');

    if (jenisSelect.value) {
        updateGroupVisibility();
    }

    if (jenishsSelect && jenishsSelect.value) {
        updateGroupVisibility();
    }
}

// Tambahkan event listener untuk setiap dropdown
jenisSelects.forEach(select => {
    select.addEventListener('change', updateGroupVisibility);
});

// Inisialisasi tampilan grup pada load
initializeGroupVisibility();
</script>
