<?php 
$apaket = mysqli_query($con,"SELECT * FROM profile_paket WHERE id = '$page[1]'");
$paket = mysqli_fetch_assoc($apaket);
?>
<!-- Main content -->
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header bg-secondary">
            <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">
                </ol>
              </div>
            </div>
          </div>
          <form method="post">
          <div class="card-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">
                          <?php 
                          $List = new Listdata();
                          $List->set_list("data_server",$SqlDataWH);
                          foreach ($List->get_list() as $key => $value): ?>
                          <option value="<?php echo $value['id']; ?>" <?php if($paket['id_data_server'] == $value['id']) { echo "selected";} ?>><?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" <?php if($paket['jenis_profile'] == 'PPPOE') { echo "selected";} ?>>PPPOE</option>
                              <option value="Hotspot" <?php if($paket['jenis_profile'] == 'Hotspot') { echo "selected";} ?>>Hotspot</option>
                          </select>
                      </div>
                      <div class="form-group">
                        <label>Nama Profile Di Mikrotik</label>
                        <input type="text" class="form-control" value="<?php echo $paket['nama_profile']; ?>" name="profile" required>
                      </div>
                      <i class="text-danger"><small>Nama Profile Harus sama dengan yang ada di Mikrotik</small></i>
                      <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" <?php if($paket['status'] == '1') { echo "selected";} ?>>Sekali Pakai</option>
                              <option value="0" <?php if($paket['status'] == NULL) { echo "selected";} ?>>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" value="<?php echo $paket['nama']; ?>" name="nama">
                      </div>
                      <div class="form-group">
                        <label>Harga Paket</label>
                        <input type="text" class="form-control rupiah" id="rupiah0" value="<?php echo $paket['harga_paket']; ?>" name="harga">
                      </div>
                      <div class="form-group" id="group-jenis3">
                        <label>Fee Agen Voucher</label>
                        <input type="text" class="form-control rupiah" id="rupiah0" value="<?php echo $paket['vi_agen']; ?>" 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" value="<?php echo $paket['durasi']; ?>" placeholder="6H" id="durasi">
                          <i class="text-danger">Contoh : 3H => 3 Jam , 1D => 1 Hari </i>
                      </div>
                  </div>
              </div>
            </div>
          </div>
          <div class="card-footer">
            <input type="submit" class="btn btn-sm btn-secondary m-1" name="edit" value="Simpan Perubahan">
          </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</section>

<?php 
if (isset($_POST['edit'])) {
    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;

                    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 ada.";
                    }
                }
            } else {
                $messages[] = "Gagal terhubung ke MikroTik <b>$mikrotikName</b>.";
            }
        }

        // Cek pesan sebelum menyimpan ke database
        if (empty($messages)) {
            $stmt = $pdo->prepare("UPDATE profile_paket SET 
                id_data_server = :id_data_server, 
                jenis_profile = :jenis_profile, 
                nama_profile = :nama_profile, 
                durasi = :durasi, 
                nama = :nama, 
                harga_paket = :harga_paket, 
                vi_agen = :vi_agen,
                status = :status 
                WHERE id = :id");
            $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->bindParam(':id', $page[1]);
            $stmt->execute();
            sweetAlert("Profile Paket Telah di Ubah", "success", "?".encrypt_url('profile_paket'));
        } else {
            $message = implode("<br>", $messages);
            detailAlert($message, strpos($message, 'tidak ada') !== false || strpos($message, 'Gagal') !== false);
        }

    } catch (PDOException $e) {
        // Menangani kesalahan
        sweetAlert("Terjadi kesalahan: " . $e->getMessage(), "error");
    }
}
?>


<script>
    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;
            }
        }
    }

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

    // Memanggil fungsi untuk memperbarui tampilan berdasarkan nilai yang sudah ada
    jenisSelects.forEach(select => {
        if (select.value) {
            updateGroupVisibility({ target: select });
        }
    });
</script>
