Update Voucher , Tiket , Dashboard

membuat perubahan dan update
This commit is contained in:
YanDrs
2025-07-15 00:30:19 +07:00
parent 84c697516e
commit 0f32cf00ad
23 changed files with 2086 additions and 513 deletions
+277 -140
View File
@@ -1,6 +1,8 @@
<?php
$apaket = mysqli_query($con,"SELECT * FROM profile_paket WHERE id = '$page[1]'");
$paket = mysqli_fetch_assoc($apaket);
$data = json_decode($paket['radius_data']);
?>
<!-- Main content -->
<section class="content">
@@ -26,7 +28,7 @@ $paket = mysqli_fetch_assoc($apaket);
<div class="card-body">
<div class="form-group">
<label>Nama Server</label>
<select class="form-control" name="ids">
<select class="form-control" name="ids" disabled>
<?php
$List = new Listdata();
$List->set_list("data_server",$SqlDataWH);
@@ -35,28 +37,43 @@ $paket = mysqli_fetch_assoc($apaket);
<?php endforeach ?>
</select>
</div>
<div class="form-group">
<label>Radius Server</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="radiuscek" value="1" id="checkbox1-0" <?= (empty($paket['radius_data'])) ? "" : "checked"; ?> disabled>
<label class="form-check-label" for="checkbox1">
Menggunakan Radius
</label>
</div>
<i class="text-danger"><small>Saat ini radius hanya digunakan untuk Autentikasi saja, untuk limit masih di sisi mikrotik</small></i>
</div>
<div class="form-group">
<label>Jenis Profile</label>
<select class="form-control" name="jenis" data-select="jenis-select1" required>
<select class="form-control" name="jenis" data-select="jenis-select1" disabled>
<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>
<option value="DHCP" id="group-dhcp" <?php if($paket['jenis_profile'] == 'DHCP') { echo "selected";} ?>>DHCP IP Address</option>
</select>
</div>
<div class="form-group">
<div class="form-group" id="group-jenis0">
<label>Nama Profile Di Mikrotik</label>
<input type="text" class="form-control" value="<?php echo $paket['nama_profile']; ?>" name="profile" required>
<input type="text" class="form-control" value="<?php echo $paket['nama_profile']; ?>" name="profile">
</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">
<select class="form-control" id="jenis-select2" name="jenishs" data-select="jenis-select2" disabled>
<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>
<input type="hidden" name="ids" value="<?= $paket['id_data_server']; ?>">
<input type="hidden" name="radiuscek" value="<?= (empty($paket['radius_data'])) ? "" : 1 ; ?>">
<input type="hidden" name="jenis" value="<?= $paket['jenis_profile']; ?>">
<input type="hidden" name="jenishs" value="<?= $paket['status']; ?>">
</div>
</div>
<div class="col-md-6">
@@ -79,6 +96,26 @@ $paket = mysqli_fetch_assoc($apaket);
<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 class="form-group" id="group-use">
<label>Limit Pengguna / Device</label>
<input type="text" class="form-control" name="use_limit" value="<?= $data->use_limit ?>">
</div>
<div class="form-group" id="group-pool">
<label>IP Pool</label>
<input type="text" class="form-control" name="ip_pool" value="<?= $data->ip_pool ?>">
</div>
<div class="form-group" id="group-rate">
<label>Rate Limit</label>
<input type="text" class="form-control" name="rate_limit" placeholder="( Opsional )" value="<?= $data->rate_limit ?>">
</div>
<div class="form-group" id="group-session">
<label>Session Timeout</label>
<input type="text" class="form-control" name="session_time" placeholder="( Opsional )" value="<?= $data->session_time ?>">
</div>
<div class="form-group" id="group-idle">
<label>Idle Timeout</label>
<input type="text" class="form-control" name="idle_time" placeholder="( Opsional )" value="<?= $data->idle_time ?>">
</div>
</div>
</div>
</div>
@@ -96,110 +133,161 @@ $paket = mysqli_fetch_assoc($apaket);
<?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;
// === Validasi perubahan data ===
$changes = [];
$messages = [];
$rollbackServers = [];
// Ambil server dari database
$newNama = $_POST['nama'];
$newProfile = $_POST['profile'];
$newDurasi = $_POST['durasi'];
$newHarga = preg_replace("/[^0-9]/", "", $_POST['harga']);
$newFee = preg_replace("/[^0-9]/", "", $_POST['fee']);
$newStatus = $_POST['status'] ?? NULL;
if ($newNama !== $paket['nama']) $changes['nama'] = $newNama;
if ($newProfile !== $paket['nama_profile']) $changes['nama_profile'] = $newProfile;
if ($newDurasi !== $paket['durasi']) $changes['durasi'] = $newDurasi;
if ($newHarga != $paket['harga_paket']) $changes['harga_paket'] = $newHarga;
if ($newFee != $paket['vi_agen']) $changes['vi_agen'] = $newFee;
if ($newStatus != $paket['status']) $changes['status'] = $newStatus;
// === Radius Data ===
$groupname = preg_replace('/\s+/', '-', strtolower(trim(preg_replace('/[^a-z0-9 ]/i', '', $_POST['jenis'] . ' ' . $newNama)))) . '-' . $SvId;
$groupnameold = $data->{'groupname'};
$radiusPayload = [
'groupnameold' => $groupnameold,
'data' => [
'jenis' => $_POST['jenis'],
'groupname' => $groupname,
'profile' => $_POST['profile'] ?? '',
'use_limit' => $_POST['use_limit'] ?? '',
'rate_limit' => $_POST['rate_limit'] ?? '',
'session_time' => $_POST['session_time'] ?? '',
'ip_pool' => $_POST['ip_pool'] ?? '',
'idle_time' => $_POST['idle_time'] ?? ''
]];
// print_r($radiusPayload);
$currentRadiusData = json_decode($paket['radius_data'], true);
if ($radiusPayload['data'] != $currentRadiusData) {
$changes['radius_data'] = json_encode($radiusPayload['data']);
}
// === TRANSAKSI DB ===
$pdo->beginTransaction();
// === Update Radius jika perlu ===
if (isset($changes['radius_data']) && !empty($_POST['radiuscek'])) {
$radius = new CrudRadiusServer();
$radius->request('update_paket', 'PUT', $radiusPayload);
}
// === Update ke Database hanya jika ada perubahan ===
if (!empty($changes)) {
$updateFields = [];
foreach ($changes as $key => $value) {
// Pastikan tidak ada field yang dilarang ikut
if (!in_array($key, ['id_data_server', 'radiuscek', 'jenis', 'jenishs'])) {
$updateFields[] = "$key = :$key";
}
}
if (!empty($updateFields)) {
$sql = "UPDATE profile_paket SET " . implode(', ', $updateFields) . " WHERE id = :id";
$stmt = $pdo->prepare($sql);
foreach ($changes as $key => $value) {
if (!in_array($key, ['id_data_server', 'radiuscek', 'jenis', 'jenishs'])) {
$stmt->bindValue(":$key", $value);
}
}
$stmt->bindValue(':id', $page[1]);
$stmt->execute();
}
}
// === Update ke Mikrotik ===
$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'];
$profileFound = false;
$poolFound = false;
if ($_POST['jenis'] == 'PPPOE') {
// Cek profil PPPOE
$profiles = $API->comm('/ppp/profile/print');
$found = false;
// === CEK PROFILE & UPDATE SCRIPT ===
$profileFound = true; // Default true (kalau jenis bukan PPPoE/Hotspot tidak perlu dicek)
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.";
}
if (!empty($_POST['profile'])) {
if ($_POST['jenis'] == 'PPPOE') {
$profiles = $API->comm('/ppp/profile/print');
} elseif ($_POST['jenis'] == 'Hotspot') {
$profiles = $API->comm('/ip/hotspot/user/profile/print');
} else {
$messages[] = "Profil Hotspot <b>$profileName</b> di <b>$mikrotikName</b> tidak ada.";
$profiles = []; // DHCP tidak cek profile
}
$profileFound = false;
foreach ($profiles as $p) {
if ($p['name'] === $newProfile) {
$profileFound = true;
// === UPDATE SCRIPT (HANYA HOTSPOT) ===
if ($_POST['jenis'] == 'Hotspot' && $newStatus == 1 && empty($_POST['radiuscek'])) {
$interval = intervalFormat($_POST['durasi']);
$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;}';
$API->comm('/ip/hotspot/user/profile/set', [
'.id' => $p['.id'],
'on-login' => $onLoginScript,
]);
}
break;
}
}
if (!$profileFound) {
$messages[] = "Profil <b>$newProfile</b> di <b>$mikrotikName</b> tidak ditemukan.";
break;
}
}
// === CEK IP POOL ===
if (!empty($_POST['ip_pool']) && $_POST['jenis'] == 'DHCP') {
$poolcek = $API->comm('/ip/pool/print');
foreach ($poolcek as $pool) {
if ($pool['name'] === $_POST['ip_pool']) {
$poolFound = true;
break;
}
}
if (!$poolFound) {
$messages[] = "IP Pool <b>{$_POST['ip_pool']}</b> di <b>$mikrotikName</b> tidak ditemukan.";
break;
}
}
$rollbackServers[] = $server; // Catat untuk rollback jika error
} else {
$messages[] = "Gagal terhubung ke MikroTik <b>$mikrotikName</b>.";
break;
}
}
// 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'));
$pdo->commit();
sweetAlert("Profile Paket berhasil diperbarui", "success", "?" . encrypt_url('profile_paket'));
} else {
$pdo->rollBack();
$message = implode("<br>", $messages);
detailAlert($message, strpos($message, 'tidak ada') !== false || strpos($message, 'Gagal') !== false);
detailAlert($message, true);
}
} catch (PDOException $e) {
// Menangani kesalahan
$pdo->rollBack();
sweetAlert("Terjadi kesalahan: " . $e->getMessage(), "error");
}
}
@@ -207,67 +295,116 @@ if (isset($_POST['edit'])) {
<script>
const jenisSelects = document.querySelectorAll('[data-select]');
// Ambil semua elemen dropdown & checkbox dalam halaman
const jenisSelects = document.querySelectorAll('[data-select]');
const radiusCheckbox = document.querySelector('input[name="radiuscek"]');
// Sembunyikan semua grup pada awalnya
document.querySelectorAll('[id^="group-"]').forEach(group => {
// 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 group0 = document.getElementById('group-jenis0');
const group1 = document.getElementById('group-jenis1');
const group2 = document.getElementById('group-jenis2');
const group3 = document.getElementById('group-jenis3');
const groupdhcp = document.getElementById('group-dhcp');
const radiusUse = document.getElementById('group-use');
const radiusRate = document.getElementById('group-rate');
const radiusSession = document.getElementById('group-session');
const radiusIdle = document.getElementById('group-idle');
const groupPool = document.getElementById('group-pool');
const fee = document.getElementById('fee');
const durasi = document.getElementById('durasi');
// Helper untuk reset grup
function resetGroup(group, resetValue = true) {
if (resetValue) {
const inputs = group.querySelectorAll('select, input');
inputs.forEach(input => {
if (input.type === 'checkbox' || input.type === 'radio') {
input.checked = false;
} else {
input.value = '';
}
});
}
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);
});
// Reset semua grup dulu
const allGroups = [
group0, group1, group2, group3,
groupdhcp, groupPool,
radiusUse, radiusRate, radiusSession, radiusIdle
];
allGroups.forEach(g => resetGroup(g, false));
// Memanggil fungsi untuk memperbarui tampilan berdasarkan nilai yang sudah ada
jenisSelects.forEach(select => {
if (select.value) {
updateGroupVisibility({ target: select });
// Tampilkan grup sesuai dropdown jenis
if (jenisSelect.value === "Hotspot") {
group0.style.display = 'block';
group1.style.display = 'block';
group1.querySelector('select').required = true;
} else if (jenisSelect.value === "PPPOE") {
group0.style.display = 'block';
} else if (jenisSelect.value === "DHCP") {
groupPool.style.display = 'block';
}
// Tampilkan grup sesuai jenishs select
if (jenisSelect.value === "Hotspot" && jenishsSelect.value === "1") {
group2.style.display = 'block';
group3.style.display = 'block';
if (fee) fee.required = true;
if (durasi) durasi.required = true;
} else {
if (fee) fee.required = false;
if (durasi) durasi.required = false;
}
// Tampilkan grup sesuai checkbox radius
if (radiusCheckbox && radiusCheckbox.checked) {
groupdhcp.style.display = 'block';
if (jenisSelect.value === "PPPOE") {
radiusUse.style.display = 'block';
radiusRate.style.display = 'block';
} else if (jenisSelect.value === "Hotspot") {
radiusUse.style.display = 'block';
radiusSession.style.display = 'block';
radiusRate.style.display = 'block';
radiusIdle.style.display = 'block';
} else if (jenisSelect.value === "DHCP") {
radiusRate.style.display = 'block';
groupPool.style.display = 'block';
}
});
} else {
// Hanya reset grup radius & dhcp
[radiusUse, radiusRate, radiusSession, radiusIdle, groupdhcp, groupPool].forEach(g => resetGroup(g));
// Jika jenisSelect saat ini DHCP, reset ke kosong supaya tidak memicu tampil lagi
if (jenisSelect.value === "DHCP") {
jenisSelect.selectedIndex = 0;
}
}
}
// Jalankan inisialisasi saat halaman sudah siap
document.addEventListener('DOMContentLoaded', function () {
updateGroupVisibility(); // Jalankan sekali saat halaman pertama kali dibuka
});
// Tambahkan event listener untuk setiap dropdown
jenisSelects.forEach(select => {
select.addEventListener('change', updateGroupVisibility);
});
// Tambahkan event listener untuk checkbox radius
if (radiusCheckbox) {
radiusCheckbox.addEventListener('change', updateGroupVisibility);
}
</script>