<?php

$conPelanggan = $koneksi->query("SELECT * FROM tbl_penggunamikrotik");
$checkUser = $conPelanggan->fetch_assoc();

if ($checkUser['status'] == 'ya') {
    $sql_mikrotik = "SELECT * FROM tbl_mikrotik WHERE id_mikrotik = 1";
    $result = mysqli_query($koneksi, $sql_mikrotik);
    $row = mysqli_fetch_assoc($result);

    $API = new RouterosAPI();
    if ($API->connect($row['ip'], $row['username'], $row['password'])) {
        $API->write('/ppp/secret/print');
        $pppSecret = $API->read();

        $API->write('/ppp/profile/print');
        $pppProfile = $API->read();
    }
}
?>

<div class="row">

    <div class="col-md-6">

        <div class="box box-primary">

            <div class="box-header with-border">
                <h3 class="box-title">Tambah Data Pelanggan</h3>
            </div>

            <form method="POST" enctype="multipart/form-data">
                <div class="box-body">

                    <?php
                    $cek = $koneksi->query("SELECT * FROM tb_user WHERE level = 'user'");
                    $existingNames = array();

                    // Mengumpulkan nama yang sudah ada di dalam database ke dalam array
                    while ($row = $cek->fetch_assoc()) {
                        $existingNames[] = $row['username'];
                    }
                    ?>

                    <?php if ($checkUser['status'] == 'ya') { ?>
                        <div class="form-group">
                            <label>Ambil Data Dari Mikrotik</label>
                            <select class="form-control" id="getPMikrotik">
                                <option value="" data-nama="">Pilih Pelanggan</option>
                                <?php foreach ($pppSecret as $ps) {
                                    $name = $ps['name'];

                                    // Periksa apakah name sudah ada di dalam database
                                    $isNameExist = in_array($name, $existingNames);

                                    // Hanya tampilkan opsi jika name belum ada di dalam database
                                    if (!$isNameExist) {
                                ?>
                                        <option data-nama="<?= $ps['name'] ?>" data-profile="<?= $ps['profile'] ?>" data-username="<?= $ps['name'] ?>" data-password="<?= $ps['password'] ?>"><?= $ps['name'] ?></option>
                                <?php
                                    }
                                } ?>
                            </select>
                        </div>
                    <?php } ?>


                    <?php if ($checkUser['ippelanggan'] == 'statik') { ?>
                        <div class="form-group">
                            <label>LOCAL ADDRESS</label>
                            <input type="text" name="ip_address" class="form-control">
                        </div>
                        <div class="form-group">
                            <label>REMOTE ADDRESS</label>
                            <input type="text" name="ip_address" class="form-control">
                        </div>
                    <?php } ?>
                    <div class="form-group">
                        <label>Jenis Pelanggan</label>
                        <select name="jenis_pelanggan" id="jenis_pelanggan" class="form-control" required onchange="toggleIPField()">
                            <option value="">-- Pilih Jenis Pelanggan --</option>
                            <option value="PPoE">PPoE</option>
                            <option value="Hotspot">Hotspot</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>NIK KTP <small style="color: red;">*Kosongkan Jika Tidak Ada</small></label>
                        <input type="text" name="nik" id="nik" class="form-control">
                    </div>
                    <div class="form-group">
                        <label>Kode Pelanggan</label>
                        <input type="text" id="kode_pelanggan" name="kode_pelanggan" class="form-control" disabled>



                        <!-- Hidden field untuk dikirim ke database -->
                        <input type="hidden" name="kode_pelanggan" id="kode_pelanggan_hidden">
                    </div>
                    <div class="form-group">
                        <?php if ($checkUser['ippelanggan'] == 'dynamic' || $checkUser['addppsecret'] == 'ya') { ?>
                            <label>Username (Pastikan Username Sama Dengan Nama PPP Secret Di Mikrotik)</label>
                        <?php } else { ?>
                            <label>Username</label>
                        <?php } ?>
                        <input type="text" name="username" id="username" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <?php if ($checkUser['ippelanggan'] == 'dynamic' || $checkUser['addppsecret'] == 'ya') { ?>
                            <label>Password PPoE (Pastikan Password Sama Dengan Nama PPP Secret Di Mikrotik)</label>
                        <?php } else { ?>
                            <label>Password</label>
                        <?php } ?>
                        <input type="text" name="password" id="password" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label>Password Aplikasi</label>
                        <input type="text" name="password_aplikasi" id="password_aplikasi" class="form-control" value="1234" disabled>

                        <!-- Hidden input agar nilai tetap terkirim ke server -->
                        <input type="hidden" name="password_aplikasi" value="1234">
                    </div>
                    <div class="form-group">
                        <label>IP Address</label>
                        <input type="text" name="ip_address" id="ip_address" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label for="mac_address">MAC Address</label>
                        <input type="text" class="form-control" name="mac_address" id="mac_address" placeholder="Masukkan MAC Address">
                    </div>

                    <div class="form-group">
                        <label>Nama Pelanggan</label>
                        <input type="text" name="nama" id="nama_pelanggan" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Alamat </label>
                        <textarea class="form-control" rows="3" name="alamat"></textarea>
                    </div>

                    <div class="form-group">
                        <label>No Telp (Contoh 089612345678)</label>
                        <input type="text" name="no_telp" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <input type="hidden" name="mapping" class="form-control" id="coordinates">
                    </div>

                    <div class="form-group">

                        <label>Paket :</label> <br>
                        <select class="form-control" name="paket" id="profile">

                            <?php

                            $query = $koneksi->query("SELECT * FROM tb_paket ORDER by id_paket");

                            while ($tampil_t = $query->fetch_assoc()) {
                                echo "<option value='$tampil_t[id_paket]'> $tampil_t[nama_paket]</option>";
                            }

                            ?>

                        </select>

                    </div>

                    <div class="form-group">

                        <label>Perangkat Modem :</label> <br>
                        <select class="form-control" name="nama_perangkat" id="perangkat">
                            <option value="NULL">== Jangan Sebutkan ==</option>
                            <?php

                            $queryy = $koneksi->query("SELECT * FROM tb_perangkat ORDER BY id_perangkat");

                            while ($tampil_tt = $queryy->fetch_assoc()) {
                                echo "<option value='$tampil_tt[id_perangkat]'> $tampil_tt[nama_perangkat]</option>";
                            }

                            ?>

                        </select>

                    </div>

                    <div class="form-group">

                        <label>Dari ODP</label> <br>
                        <select class="form-control" name="odp">
                            <option value="NULL">== Tidak Ada ==</option>
                            <?php

                            $queryy = $koneksi->query("SELECT * FROM tbl_odp ORDER BY id_odp");

                            while ($tampil_tt = $queryy->fetch_assoc()) {
                                echo "<option value='$tampil_tt[id_odp]'> $tampil_tt[nama_odp]</option>";
                            }

                            ?>

                        </select>

                    </div>

                </div>
                <div class="modal-footer">

                    <button type="submit" name="tambah" class="btn btn-block btn-primary btn-lg">Simpan</button>

                </div>
            </form>

        </div>

    </div>

    <?php if ($checkUser['mapping'] == 'aktif') { ?>
        <div class="col-md-6">
            <div class="box box-primary">

                <div class="box-header with-border">
                    <h3 class="box-title">Lokasi Pelanggan</h3>
                </div>

                <div class="box-body">
                    <div id="map" style="height: 600px;"></div>
                </div>
            </div>
        </div>
    <?php } ?>

</div>

<?php
if (isset($_POST['tambah'])) {

    $password = htmlspecialchars(strip_tags($_POST['password'])); // Simpan ke tb_pelanggan
    $password_aplikasi = htmlspecialchars(strip_tags($_POST['password_aplikasi'])); // Simpan ke tb_user
    $nik = !empty($_POST['nik']) ? htmlspecialchars(strip_tags($_POST['nik'])) : '-';
    $jenis_pelanggan = htmlspecialchars(strip_tags($_POST['jenis_pelanggan']));
    $nama = htmlspecialchars(strip_tags($_POST['nama']));
    $tgl_pemasangan = (new DateTime())->format('Y-m-d H:i');
    $alamat = htmlspecialchars(strip_tags($_POST['alamat']));
    $no_telp = htmlspecialchars(strip_tags($_POST['no_telp']));
    $paket = $_POST['paket'];
    $odp = $_POST['odp'];
    $perangkat = ($_POST['nama_perangkat'] !== 'NULL') ? $_POST['nama_perangkat'] : NULL;
    $ip_address = !empty($_POST['ip_address']) ? $_POST['ip_address'] : '-';
    $mapping = $_POST['mapping'] ?: NULL;
    $mac_address = !empty($_POST['mac_address']) ? $_POST['mac_address'] : '-';
    $tgl_pemasangan_obj = new DateTime($tgl_pemasangan);
    $tgl_pemasangan_obj->modify('+1 Month');
    $jam_sekarang = date('H:i:00');
    $tgl_jatuh_tempo = $tgl_pemasangan_obj->format('Y-m-d') . ' ' . $jam_sekarang;

    if ($jenis_pelanggan === 'Hotspot' && empty($_POST['ip_address'])) {
        echo "<script>alert('IP Address wajib diisi untuk pelanggan Hotspot'); window.history.back();</script>";
        exit;
    }

    // Ambil data paket
    $getPaket = $koneksi->query("SELECT * FROM tb_paket WHERE id_paket=$paket");
    $checkPaket = $getPaket->fetch_assoc();
    $id_profile = $checkPaket['id_pmikrotik'];
    $namaPaket = $checkPaket['nama_paket'];

    // Cek port ODP
    $cek = $koneksi->query("SELECT port_odp FROM tbl_odp WHERE id_odp = $odp");
    $cekk = $cek->fetch_assoc();
    $maxPort = $cekk['port_odp'];

    $sql1 = $koneksi->query("SELECT COUNT(*) AS total_odp FROM tb_pelanggan WHERE odp = $odp");
    $count = $sql1->fetch_assoc();
    $total_odp = $count['total_odp'];

    if ($total_odp >= $maxPort) {
        echo "<script>
            swal({
                title: 'Gagal',
                text: 'Melebihi Batas Port ODC',
                type: 'error'
            }, function() {
                window.location = '?page=pelanggan';
            });
        </script>";
        return;
    }

    // Generate kode pelanggan
    $prefix = ($jenis_pelanggan === 'Hotspot') ? 'HSP' : 'POE';
    do {
        $getKode = $koneksi->query("SELECT MAX(kode_pelanggan) AS kode_terakhir 
                                       FROM tb_pelanggan 
                                    WHERE kode_pelanggan LIKE '$prefix%'");
        $kode_terakhir = $getKode->fetch_assoc()['kode_terakhir'];
        $urutan = ($kode_terakhir) ? (int)substr($kode_terakhir, 3) + 1 : 1;
        $kode_pelanggan = $prefix . str_pad($urutan, 3, '0', STR_PAD_LEFT);

        // Pastikan tidak duplikat
        $insertPelanggan = $koneksi->query("INSERT INTO tb_pelanggan (
    nik, jenis_pelanggan, nama_pelanggan, alamat, no_telp, paket, ip_address,
    mac_address, tgl_pemasangan, jatuh_tempo, location, id_perangkat, odp, kode_pelanggan
    ) VALUES (
    '$nik', '$jenis_pelanggan', '$nama', '$alamat', '$no_telp', '$paket', '$ip_address',
    '$mac_address', '$tgl_pemasangan', '$tgl_jatuh_tempo', '$mapping', '$perangkat', '$odp', '$kode_pelanggan'
)");
    } while (!$insertPelanggan);

    $id_pelanggan = $koneksi->insert_id;

    // Username ikut kode_pelanggan jika Hotspot
    $username = ($jenis_pelanggan === 'Hotspot') ? $kode_pelanggan : htmlspecialchars(strip_tags($_POST['username']));

    // Cek username jika PPPoE
    if ($jenis_pelanggan !== 'Hotspot') {
        $sql3 = $koneksi->query("SELECT * FROM tb_user WHERE username='$username'");
        if ($sql3->num_rows > 0) {
            echo "<script>alert('Username sudah terdaftar!'); window.history.back();</script>";
            return;
        }
    }

    // Insert ke tb_user
    $sql = $koneksi->query("INSERT INTO tb_user (
        username, nama_user, password, password_aplikasi,  level, foto, id_pelanggan
    ) VALUES (
        '$username', '$nama', '$password', '$password_aplikasi', 'user', 'admin.png', '$id_pelanggan'
    )");

    // Tambahkan ke mikrotik jika PPPoE
    if ($checkUser['addppsecret'] == 'ya' && $jenis_pelanggan === 'PPPoE') {
        $sql_mikrotik = "SELECT * FROM tbl_mikrotik WHERE id_mikrotik = 1";
        $result = mysqli_query($koneksi, $sql_mikrotik);
        $row = mysqli_fetch_assoc($result);

        $API = new RouterosAPI();
        if ($API->connect($row['ip'], $row['username'], $row['password'])) {

            // Cek apakah sudah ada di Mikrotik
            $cek_user_mikrotik = $API->comm("/ppp/secret/print", [
                "?name" => $username
            ]);

            if (empty($cek_user_mikrotik)) {
                // Belum ada, tambahkan
                $API->comm("/ppp/secret/add", array(
                    "name" => $username,
                    "password" => $password,
                    "service" => 'pppoe',
                    "profile" => $id_profile,
                ));
            } else {
                // Sudah ada, tidak perlu ditambahkan ke Mikrotik
                // Tapi tetap lanjut karena database lokal tetap perlu
            }
        }
    }

    //pengecekan untuk hotspot
    if ($checkUser['addppsecret'] == 'ya' && $jenis_pelanggan === 'Hotspot') {
        $hotspotConf = $koneksi->query("SELECT * FROM tbl_hotspot_config LIMIT 1")->fetch_assoc();

        $serverHotspot = $hotspotConf['server_hotspot'];
        $serverDHCP = $hotspotConf['server_dhcp'];
        $rateLimit = $hotspotConf['rate_limit'];
        $insertBefore = $hotspotConf['insert_queue_before'];
        $parentQueue = $hotspotConf['parent_queue'];

        $sql_mikrotik = "SELECT * FROM tbl_mikrotik WHERE id_mikrotik = 1";
        $result = mysqli_query($koneksi, $sql_mikrotik);
        $row = mysqli_fetch_assoc($result);

        $API = new RouterosAPI();
        if ($API->connect($row['ip'], $row['username'], $row['password'])) {
            // Tambah DHCP Lease
            $API->comm("/ip/dhcp-server/lease/add", array(
                "address" => $ip_address,
                "mac-address" => $mac_address,
                "server" => $serverDHCP,
                "use-src-mac" => "yes",
                "rate-limit" => $rateLimit,
                "insert-queue-before" => $insertBefore,
                "parent-queue" => $parentQueue
            ));

            // Tambah Hotspot IP-Binding
            $API->comm("/ip/hotspot/ip-binding/add", array(
                "address" => $ip_address,
                "to-address" => $ip_address,
                "mac-address" => $mac_address,
                "server" => $serverHotspot,
                "type" => "bypassed"
            ));
        }
    }


    // Kirim notifikasi
    $checkNotif = $koneksi->query("SELECT * FROM tbl_npemasangan");
    $notifikasi = $checkNotif->fetch_assoc();
    $pesan = str_replace(
        ['$nama', '$alamat', '$no_telp', '$paket', '$tgl_pemasangan', '$username', '$password'],
        [$nama, $alamat, $no_telp, $namaPaket, $tgl_pemasangan, $username, $password],
        $notifikasi['pesan_notif']
    );

    if ($notifikasi['status_notif'] == 'aktif') {
        $sql_token = "SELECT * FROM tbl_token WHERE id_token = 1";
        $result = mysqli_query($koneksi, $sql_token);
        $row = mysqli_fetch_assoc($result);
        $authorizationToken = $row['token'];

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api.fonnte.com/send',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array(
                'target' => $no_telp,
                'message' => $pesan,
            ),
            CURLOPT_HTTPHEADER => array(
                'Authorization: ' . $authorizationToken
            ),
        ));
        curl_exec($curl);
        curl_close($curl);
    }

    // Tampilkan notifikasi sukses
    echo "<script>
        setTimeout(function() {
            swal({
                title: 'Data Pelanggan',
                text: 'Berhasil Disimpan!',
                type: 'success'
            }, function() {
                window.location = '?page=pelanggan';
            });
        }, 300);
    </script>";
}

?>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        const jenisSelect = document.getElementById("jenis_pelanggan");
        const usernameInput = document.querySelector("input[name='username']");
        const kodeField = document.getElementById("kode_pelanggan");
        const kodeHidden = document.getElementById("kode_pelanggan_hidden");
        const ipField = document.getElementById("ip_address");
        const macField = document.getElementById("mac_address");
        const password = document.getElementById("password");

        function toggleFields() {
            const jenis = jenisSelect.value;

            // Toggle IP Address
            ipField.disabled = (jenis !== "Hotspot");

            // Toggle MAC Address
            macField.disabled = (jenis !== "Hotspot");
            password.disabled = (jenis !== "PPoE");
            // Toggle Username
            if (jenis === "Hotspot") {
                // Jika kode sudah ada, gunakan sebagai username
                if (kodeField.value) {
                    usernameInput.value = kodeField.value;
                }
                usernameInput.disabled = true;
            } else {
                usernameInput.disabled = false;
                usernameInput.value = "";
            }
        }

        jenisSelect.addEventListener("change", function() {
            const jenis = this.value;

            // Ambil kode pelanggan
            fetch("page/pelanggan/generate_kode.php?jenis=" + jenis)
                .then(response => response.text())
                .then(kode => {
                    kodeField.value = kode;
                    kodeHidden.value = kode;

                    if (jenis === "Hotspot") {
                        usernameInput.value = kode;
                    }
                });

            toggleFields();
        });

        toggleFields(); // Panggil saat load awal
    });
</script>

<script>
    function toggleIPField() {
        const jenis = document.getElementById("jenis_pelanggan").value;
        const ipField = document.getElementById("ip_address");

        if (jenis === "Hotspot") {
            ipField.disabled = false;
        } else {
            ipField.disabled = true;
            ipField.value = ''; // Kosongkan jika bukan hotspot
        }
    }

    // Trigger awal saat halaman dimuat
    document.addEventListener("DOMContentLoaded", function() {
        toggleIPField();
    });
</script>