<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">Setting Mikrotik</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>
                  <button id="syncBtn" class="btn btn-secondary btn-sm">Sync Data</button>
                </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 bg-primary">
                        <h5 class="modal-title" id="staticBackdropLabel">Tambah Mikrotik Router</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 Mikrotik</label>
                                <input type="text" class="form-control" name="nmk" required="required">
                              </div>
                              <div class="form-group">
                                <label>IP Address</label>
                                <input type="text" class="form-control" name="ipa" required="required">
                              </div>
                              <div class="form-group">
                                <label>Port API Mikrotik</label>
                                <input type="text" class="form-control" name="pam" required="required">
                              </div>
                              <div class="form-group">
                                <label>Port Remote Modem</label>
                                <input type="text" class="form-control" name="prm" required="required">
                              </div>
                            </div>
                          </div>
                          <div class="col-sm-6">
                            <div class="card-body pb-0">
                              <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 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 echo $value['nama_server']; ?></option>
                                  <?php endforeach ?>
                                </select>
                              </div>
                              <div class="form-group">
                                <label>Profile PPPOE Remote</label>
                                <input type="text" class="form-control" name="profile_remote" placeholder="Isi jika di perlukan">
                                <i class="text-danger">Khusus yang memiliki pelanggan hotspot bulanan, jika modem/router ingin bisa di remote oleh aplikasi menggunakan koneksi PPPOE</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'])) {
                        $user_remote = 'Test';
                        $last_remote = date('Y-m-d H:i:s');
                        try {
                            // Misalkan $pdo adalah koneksi PDO yang sudah dibuat sebelumnya
                            $stmt = $pdo->prepare("INSERT INTO setting_mikrotik 
                              (id_data_server, nama, ip_address, port_api, port_remote, username, password, profile_remote, user_remote, last_remote) 
                            VALUES (:id_data_server, :nama, :ip_address, :port_api, :port_remote, :username, :password, :profile_remote, :user_remote, :last_remote)");

                            $stmt->bindParam(':id_data_server', $_POST['ids']);
                            $stmt->bindParam(':nama', $_POST['nmk']);
                            $stmt->bindParam(':ip_address', $_POST['ipa']);
                            $stmt->bindParam(':port_api', $_POST['pam']);
                            $stmt->bindParam(':port_remote', $_POST['prm']);
                            $stmt->bindParam(':username', $_POST['usm']);
                            $stmt->bindParam(':password', $_POST['psw']);
                            $stmt->bindParam(':profile_remote', $_POST['profile_remote']);
                            $stmt->bindParam(':user_remote', $user_remote);
                            $stmt->bindParam(':last_remote', $last_remote);

                            if ($stmt->execute()) {
                                sweetAlert("Data telah ditambah", "success");
                            }
                        } catch (PDOException $e) {
                            // Menangani kesalahan dan menampilkan dengan sweetAlert
                            sweetAlert("Error: " . $e->getMessage(), "error");
                        }
                    }
                    ?>
                  </div>
                </div>
              </div>
              <!-- END Modal Tambah -->
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
            <table id="example1" class="table table-bordered table-striped">
              <thead>
              <tr>
                <th>Nama Mikrotik</th>
                <th>Ip Address</th>
                <th>Port API</th>
                <th>Board</th>
                <th>Uptime</th>
                <th>Action</th>
              </tr>
              </thead>
              <tbody>
              <?php
                $stmt = $pdo->prepare("SELECT * FROM setting_mikrotik $SqlDataWHId");
                $stmt->execute();
                $servers = $stmt->fetchAll(PDO::FETCH_ASSOC);
                foreach ($servers as $server) {
                  $s_time = strtotime($server['last_time']);
                  $b_time = strtotime(date('Y-m-d H:i:s')) - 60;
              ?>
              <tr>
                <td><?php echo $server['nama']; 
                  if ($s_time >= $b_time) { ?>
                  <span class="badge badge-success">Connected</span>  
                  <?php } else { ?> 
                  <span class="badge badge-danger">Disconnected</span>
                  <?php } ?>
                </td>
                <td><?php echo $server['ip_address']; ?></td>
                <td><?php echo $server['port_api']; ?></td>
                <td><?php echo $server['board_name']; ?></td>
                <td><?php echo $server['uptime']; ?></td>
                <td>
                  <form class="form-inline" method="post" enctype="multipart/form-data">
                    <div class="row">
                      <input type="submit" name="test<?php echo $server['id']; ?>" class="btn btn-primary btn-sm" value="Test">
                      <a type="button" class="btn btn-secondary btn-sm ml-1" data-toggle="modal" data-target="#modal-edit<?php echo $server['id'];?>">Edit
                      </a>
                      <input type="submit" name="hapus<?php echo $server['id'];?>" value="Hapus" class="btn btn-danger btn-sm ml-1" />
                    </div>
                  </form>
                    <?php
                      if (isset($_POST['test'.$server['id']])) 
                      {
                          $script = ':global hsa "";:global pppa "";:local id [/system license get software-id];:local idbm ($id."'.$server['id'].'");:local uptim [/system resource get uptime];:local bname [/system resource get board-name];:foreach i in=[/ppp active find] do={:local name [/ppp active get $i name];:local ip [/ppp active get $i address];:set $pppa ("$pppa$name_$ip|");};:foreach h in=[/ip hotspot user find comment!="" and uptime<20m] do={:local cek [:pick [/ip hotspot user get $h comment] 0 6];:if ($cek = "Login.") do={:local hsuser [/ip hotspot user get $h name];:local hscom [:pick [/ip hotspot user get $h comment] 6 50];:set $hsa ("$hsa$hsuser_$hscom|");}};/tool fetch url="https://manjapro.net/api/mikrotik.php" mode=https http-method=post http-data="{\"id\":\"$idbm\",\"bm\":\"$bname\",\"ut\":\"$uptim\",\"hsa\":\"$hsa\",\"pppa\":\"$pppa\"}" keep-result=no;:delay 1s;:set $pppa ("");:set $hsa ("");';
                        error_reporting(0);
                        {
                          $API = new RouterosAPI();
                          $API->debug = false;

                          if ($API->connect2($server['ip_address'], $server['username'], $server['password'],$server['port_api'] )) {

                          $API->write('/system/license/getall');

                          $READ = $API->read(false);
                          $ARRAY = $API->parseResponse($READ);
          
                          $arrsc=$API->comm('/system/scheduler/getall', 
                              array(
                            ".proplist"=> ".id",
                            "?name" => "SchBilsPro" ,
                            ));
                            $scd = $arrsc[0][".id"];
          
                            $arrs=$API->comm('/system/script/getall', 
                              array(
                            ".proplist"=> ".id",
                            "?name" => "BilsProAPI" ,
                            ));
                            $scp = $arrs[0][".id"];
          
          
                          if ($scd != '')
                          {
                            $API->comm("/system/scheduler/set",
                              array(
                                 ".id" => $scd,
                                 "interval"   => "40s",
                                 "on-event"   => "/system script run BilsProAPI",
                                 )
                              );
                          }
                          else
                          {
                          $API->comm('/system/scheduler/add', array(
                                "name"        => "SchBilsPro",
                                "interval"    => "40s",
                                "on-event"    => "/system script run BilsProAPI",
                            ));
                          }
          
                          if ($scp != '' )
                          {
                            $API->comm("/system/script/set",
                              array(
                                 ".id"      => $scp,
                                 "source"   => $script,
                                 )
                              );
                          }
                          else
                          {
                          $API->comm('/system/script/add', array(
                                "name"     => "BilsProAPI",
                                "source"   => $script,
                            ));
                          }

                          $API->disconnect();

                          }
                        }
                        if($ARRAY == "")
                        {
                          sweetAlert("Koneksi Mikrotik Gagal ..!!", "error");
                        }
                        else
                        {
                          $date = date('Y-m-d H:i:s');
                          $board_id = $ARRAY[0]['software-id'].$server['id'];
                          mysqli_query($con,"UPDATE setting_mikrotik SET board_id = '$board_id', last_time = '$date' WHERE id = '$server[id]' ");
                          sweetAlert("Koneksi Mikrotik Berhasil ..!!", "success");
                        }
                      } 
                    ?>
                </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 bg-secondary">
                        <h5 class="modal-title" id="staticBackdropLabel">Edit Mikrotik Router</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 Mikrotik</label>
                                <input type="text" class="form-control" value="<?php echo $server['nama']; ?>" name="nmk" required="required">
                              </div>
                              <div class="form-group">
                                <label>IP Address</label>
                                <input type="text" class="form-control" value="<?php echo $server['ip_address']; ?>" name="ipa" required="required">
                              </div>
                              <div class="form-group">
                                <label>Port API Mikrotik</label>
                                <input type="text" class="form-control" value="<?php echo $server['port_api']; ?>" name="pam" required="required">
                              </div>
                              <div class="form-group">
                                <label>Port Remote Modem</label>
                                <input type="text" class="form-control" value="<?php echo $server['port_remote']; ?>" name="prm" required="required">
                              </div>
                            </div>
                          </div>
                          <div class="col-sm-6">
                            <div class="card-body pb-0">
                              <div class="form-group">
                                <label>Username</label>
                                <input type="text" class="form-control" value="<?php echo $server['username']; ?>" name="usm" required="required">
                              </div>
                              <div class="form-group">
                                <label>Password</label>
                                <input type="text" class="form-control" value="<?php echo $server['password']; ?>" name="psw" required="required">
                              </div>
                              <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($server['id_data_server'] == $value['id']) { echo "selected"; } ?> ><?php echo $value['nama_server']; ?></option>
                                  <?php endforeach ?>
                                </select>
                              </div>
                              <div class="form-group">
                                <label>Profile PPPOE Remote</label>
                                <input type="text" class="form-control" value="<?php echo $server['profile_remote']; ?>" name="profile_remote" placeholder="Isi jika di perlukan">
                                <i class="text-danger">Khusus yang memiliki pelanggan hotspot bulanan, jika modem/router ingin bisa di remote oleh aplikasi menggunakan koneksi PPPOE</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="edit<?php echo $server['id'];?>" class="btn btn-warning" value="Edit">
                      </div>
                    </form>
                    <?php
                    if (isset($_POST['edit' . $server['id']])) {
                      try {
                        // Misalkan $pdo adalah koneksi PDO yang sudah dibuat sebelumnya
                        $stmt = $pdo->prepare("UPDATE setting_mikrotik SET 
                            id_data_server = :id_data_server, 
                            nama = :nama, 
                            ip_address = :ip_address, 
                            port_api = :port_api, 
                            port_remote = :port_remote, 
                            username = :username, 
                            password = :password,
                            profile_remote = :profile_remote
                            WHERE id = :id");

                        // Mengikat parameter
                        $stmt->bindParam(':id_data_server', $_POST['ids']);
                        $stmt->bindParam(':nama', $_POST['nmk']);
                        $stmt->bindParam(':ip_address', $_POST['ipa']);
                        $stmt->bindParam(':port_api', $_POST['pam']);
                        $stmt->bindParam(':port_remote', $_POST['prm']);
                        $stmt->bindParam(':username', $_POST['usm']);
                        $stmt->bindParam(':password', $_POST['psw']);
                        $stmt->bindParam(':profile_remote', $_POST['profile_remote']);
                        $stmt->bindParam(':id', $server['id']); // ID dari server yang ingin diupdate

                        // Eksekusi statement
                        if ($stmt->execute()) {
                            sweetAlert("Data telah diubah", "success");
                        }
                      } catch (PDOException $e) {
                          // Menangani kesalahan
                          sweetAlert("Error: " . $e->getMessage(), "error");
                      }
                    }

                    if (isset($_POST['hapus'.$server['id']]))
                    {
                      $iddata = $server['id'];
                      deleteAlert("setting_mikrotik",$iddata );
                    }
                    ?>
                  </div>
                </div>
              </div>
              <!-- END Modal Edit -->
            <?php } ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>


<script>
$('#syncBtn').on('click', function () {
    Swal.fire({
        title: 'Memproses...',
        text: 'Sinkronisasi sedang berjalan',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    $.get('load/sync_mikrotik.php?id=<?= $SvId; ?>', function (data) {
        Swal.fire({
            icon: 'success',
            title: 'Sinkronisasi Selesai!',
            html: data,
            confirmButtonText: 'OK'
        });
    }).fail(function () {
        Swal.fire({
            icon: 'error',
            title: 'Gagal!',
            text: 'Terjadi kesalahan saat sinkronisasi.',
            confirmButtonText: 'Tutup'
        });
    });
});
</script>