<?php 
if (isset($_SESSION['data_register']) && !empty($_SESSION['data_register'])) {
  $server = $_SESSION['data_register'][0];
  $nama = $_SESSION['data_register'][1];
  $nomor = $_SESSION['data_register'][2];
  $email = $_SESSION['data_register'][3];
  $passpost = $_SESSION['data_register'][4];
  $usernama = $_SESSION['data_register'][7];
  $harga_sewa = $_SESSION['paket'];
} else {
  $server = '';
  $nama = '';
  $nomor = '';
  $email = '';
  $passpost = '';
  $usernama = '';
  $harga_sewa = '';
}

$jam = date('H');
if ($jam >= 5 && $jam < 11) {
    $waktuSapa = "Selamat Pagi";
} elseif ($jam >= 11 && $jam < 15) {
    $waktuSapa = "Selamat Siang";
} elseif ($jam >= 15 && $jam < 18) {
    $waktuSapa = "Selamat Sore";
} else {
    $waktuSapa = "Selamat Malam";
}
$pesantext = $waktuSapa.', Ada yang mau saya tanyakan terkait Apklikasi ManjaPro';

include "config/connect.php";
include "config/whatsapp_api.php";
include 'list_data/sweetalert.php';
include "config/tanggal_indo.php";

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ManjaPro</title>

  <!-- Google Font: Source Sans Pro -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
  <!-- icheck bootstrap -->
  <link rel="stylesheet" href="plugins/icheck-bootstrap/icheck-bootstrap.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="dist/css/adminlte.min.css">
  <!-- Icon Aplikasi -->
  <link rel="icon" href="dist/img/logo-sm.png" type="image/gif" />
  <script src='https://cdn.jsdelivr.net/npm/sweetalert2@11'></script>
  <style>
      .otp-container {
          display: flex;
          justify-content: center;
          align-items: center;
          margin-top: 50px;
      }
      .otp-input {
          width: 50px;
          height: 50px;
          text-align: center;
          font-size: 24px;
          margin: 0 5px;
          border: 2px solid #ccc;
          border-radius: 5px;
      }
      .otp-input:focus {
          border-color: #007bff;
          outline: none;
      }
    </style>
</head>
<body>
<div class="container">
  <div class="card" style="margin-top: 30px;">
    <div class="card-body">
      <div class="row">
        <div class="col-md-6">
          <center>
          <div class="login-box mb-4">
            <!-- /.login-logo -->
            <div class="card card-outline card-primary">
              <div class="card-header text-center">
                <img src="dist/img/logo-login.png" width="150px" class="mt-4 mb-3"><br>
              </div>
              <div class="card-body">
                <p class="login-box-msg">Form Registerasi</p>
                <form method="post" enctype="multipart/fomr-data">
                  <div class="input-group mb-3">
                    <select class="form-control" name="paket" required>
                      <option value="">Pilih Paket</option>
                      <?php
                        $harga = [
                            ['Paket Basic', 200000],
                            ['Paket Intermediate', 300000],
                            ['Paket Advanced', 450000],
                            ['Paket Expert', 750000],
                            ['Paket Master', 1000000],
                        ];

                        foreach ($harga as $key) {
                        ?>
                            <option value="<?php echo $key[1]; ?>" <?php echo (isset($_SESSION['paket']) == $key[1]) ? 'selected' : ''; ?>>
                                <?php echo $key[0]; ?> (Rp. <?php echo number_format($key[1]); ?> / bln)
                            </option>
                        <?php
                        }
                        ?>
                    </select>
                    <div class="input-group-append">
                      <div class="input-group-text">
                        <span class="fas fa-cube"></span>
                      </div>
                    </div>
                  </div>
                  <div class="input-group mb-3">
                    <input type="text" class="form-control" id="server" value="<?php echo $server; ?>" name="server" placeholder="Server Name" required>
                    <div class="input-group-append">
                      <div class="input-group-text">
                        <span class="fas fa-server"></span>
                      </div>
                    </div>
                  </div>
                  <div class="input-group mb-3">
                    <input type="text" class="form-control" id="nama" value="<?php echo $nama; ?>" name="nama" placeholder="Full Name" required>
                    <div class="input-group-append">
                      <div class="input-group-text">
                        <span class="fas fa-user"></span>
                      </div>
                    </div>
                  </div>
                  <div class="input-group mb-3">
                    <input type="text" class="form-control" id="nomor" value="<?php echo $nomor; ?>" name="nomor" placeholder="Nomor WhatsApp" required>
                    <div class="input-group-append">
                      <div class="input-group-text">
                        <span class="fas fa-phone"></span>
                      </div>
                    </div>
                  </div>
                  <div class="input-group mb-3">
                    <input type="text" class="form-control" id="username" value="<?php echo $usernama; ?>" name="username" placeholder="Username" required>
                    <div class="input-group-append">
                      <div class="input-group-text">
                        <span class="fas fa-user"></span>
                      </div>
                    </div>
                  </div>
                  <div class="input-group mb-3">
                    <input type="email" class="form-control" id="email" value="<?php echo $email; ?>" name="email" placeholder="Email" required>
                    <div class="input-group-append">
                      <div class="input-group-text">
                        <span class="fas fa-envelope"></span>
                      </div>
                    </div>
                  </div>
                  <div class="input-group mb-4">
                      <input type="password" class="form-control" value="<?php echo $passpost; ?>" name="password" placeholder="Password" required>
                      <div class="input-group-append">
                          <div class="input-group-text">
                              <span class="fas fa-eye toggle-password" style="cursor: pointer;"></span>
                          </div>
                      </div>
                  </div>
                  <div class="input-group mb-4">
                      <input type="password" class="form-control" value="<?php echo $passpost; ?>" name="confirm_password" placeholder="Ulangi Password" required>
                      <div class="input-group-append">
                          <div class="input-group-text">
                              <span class="fas fa-eye toggle-password" style="cursor: pointer;"></span>
                          </div>
                      </div>
                  </div>
                  <hr>
                  <div class="row">
                    <div class="col-12">
                      <input type="submit" name="register" class="btn btn-primary btn-block" value="Registerasi Sekarang"/>
                    </div>
                  </div>
                </form><br>
              </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
          </center>
        </div>
        <div class="col-md-6">
          <div class="card">
            <div class="card-header bg-secondary">
              <h4 class="text-center"><b>INFORMASI</b></h4>
            </div>
            <div class="card-body mr-4">
              <h4>Mohon di Baca dengan teliti</h4><hr>
              <ul>
                <li><h5 style="text-align: justify;">Calon pengguna aplikasi, silakan lakukan registrasi terlebih dahulu. Setelah registrasi, Anda akan mendapatkan akses gratis selama 7 hari.</h5></li>
                <li><h5 style="text-align: justify;">Selama periode trial, Anda dapat berkonsultasi tentang penggunaan aplikasi. Kami sangat menghargai jika Anda bisa membagikan informasi mengenai kebutuhan Anda, agar kami dapat menyesuaikan aplikasi sesuai harapan Anda.</h5></li>
                <li><h5 style="text-align: justify;">Untuk pertanyaan lebih lanjut, silakan hubungi kami melalui WhatsApp di nomor di bawah ini.</h5></li>
              </ul>
              <hr>
              <center>
                <a href="https://wa.me/6281242659178?text=<?php echo $pesantext; ?>" target="_blank" class="btn btn-success mb-2" style="border-radius: 20px;"><i class="fab fa-whatsapp mr-3"></i>0812-4265-9178</a>
                <p>Atau</p>
                <a href="https://wa.me/6285603935233?text=<?php echo $pesantext; ?>" target="_blank" class="btn btn-success" style="border-radius: 20px;"><i class="fab fa-whatsapp mr-3"></i>0856-0393-5233</a>
              </center>
            </div>
          </div>
        </div>
      </div>
      <center>
        <!-- <input type="submit" name="register" class="btn btn-primary btn-block" value="Registerasi Sekarang"/> -->
        <a href="../">Kembali ke Halaman Utama</a>
      </center>
    </div>
  </div>
</div>
<!-- /.login-box -->

<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>

<script>
document.querySelectorAll('.toggle-password').forEach(function(toggle) {
    toggle.addEventListener('click', function() {
        // Mengambil elemen input yang bersangkutan
        const input = this.closest('.input-group').querySelector('input');
        
        // Mengubah tipe input
        if (input.type === 'password') {
            input.type = 'text';
            this.classList.remove('fa-eye');
            this.classList.add('fa-eye-slash');
        } else {
            input.type = 'password';
            this.classList.remove('fa-eye-slash');
            this.classList.add('fa-eye');
        }
    });
});
</script>
</body>
</html>

<?php

// Cek apakah status sesi sama dengan 'cekotp'
if (isset($_SESSION['status']) && $_SESSION['status'] == 'cekotp') {
?>
    <!-- Modal HTML -->
    <div class="modal fade" id="otpModal" tabindex="-1" role="dialog" aria-labelledby="otpModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title text-center" id="otpModalLabel" style="margin: auto;"><b>Verifikasi OTP</b></h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="margin-left: -20px;">
                    <span aria-hidden="true">&times;</span>
                  </button>
                </div>
                <div class="modal-body">
                  <center>
                    <h6>Masukkan kode OTP yang telah dikirimkan ke nomor WhatsApp anda.</h6>
                    <form id="otpForm" method="POST" action="" style="margin: 30px">
                      <input type="text" class="otp-input" id="otp1" maxlength="1" oninput="moveToNext(this, 'otp2')">
                      <input type="text" class="otp-input" id="otp2" maxlength="1" oninput="moveToNext(this, 'otp3')">
                      <input type="text" class="otp-input" id="otp3" maxlength="1" oninput="moveToNext(this, 'otp4')">
                      <input type="text" class="otp-input" id="otp4" maxlength="1" oninput="moveToNext(this, 'otp5')">
                      <input type="text" class="otp-input" id="otp5" maxlength="1" oninput="submitForm()">
                    </form>
                    <hr>
                    <h5>Pastikan nomor WhatsApp Anda benar dan aktif</h5>
                  </center>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Menampilkan modal saat halaman dimuat
        $(document).ready(function() {
            $('#otpModal').modal('show');
        });
    </script>
<?php
}
?>

<script>
    function moveToNext(currentInput, nextInputId) {
        if (currentInput.value.length === 1) {
            const nextInput = document.getElementById(nextInputId);
            if (nextInput) {
                nextInput.focus();
            }
        }
    }

    function submitForm() {
        const otpValues = Array.from(document.querySelectorAll('.otp-input')).map(input => input.value).join('');
        const form = document.getElementById('otpForm');

        // Create a hidden input to store the OTP value
        const otpInput = document.createElement('input');
        otpInput.type = 'hidden';
        otpInput.name = 'otp';
        otpInput.value = otpValues;

        form.appendChild(otpInput);
        form.submit();
    }
</script>

<?php

if (isset($_POST['otp'])) {
  if (password_verify($_POST['otp'], $_SESSION['data_register'][5])) {

    try {

    $stmt = $pdo->prepare("
        INSERT INTO data_server (nama_server,nama_pemilik, nomor_whatsapp, whatsapp, email, username, password, akses, status, pesan_kirim_tagihan, pesan_peringatan_tagihan, pesan_isolir_pelanggan, pesan_melunasi_tagihan, pesan_koneksi_off, pesan_registrasi, pesan_aktivasi,expaired_date,harga_sewa, backround_kwitansi, quick_setting)
        VALUES (:server, :nama, :nomor, :whatsapp, :email, :username, :password, :akses, 'Aktif', :pesan_kirim_tagihan, :pesan_peringatan_tagihan, :pesan_isolir_pelanggan, :pesan_melunasi_tagihan, :pesan_koneksi_off, :pesan_registrasi, :pesan_aktivasi, :expaired_date, :harga_sewa, 'default_kwitansi.png', 'on')
    ");

    // JSON access structure
    $akses = '{"23":{"menu":"23","sub_menu":[]},"18":{"menu":"18","sub_menu":["Survey","Tambah","Ubah","Hapus"]},"2":{"menu":"2","sub_menu":["Aktivasi","Tambah","Ubah","Hapus"]},"4":{"menu":"4","sub_menu":["Bayar","Tambah","Ubah","Hapus"]},"25":{"menu":"25","sub_menu":["Tambah","Ubah","Hapus"]},"41":{"menu":"41","sub_menu":["Isi Saldo","Ganerate","Tambah","Ubah","Hapus"]},"21":{"menu":"21","sub_menu":[]},"36":{"menu":"36","sub_menu":["Verifikasi","Tambah","Ubah","Hapus"]},"48":{"menu":"48","sub_menu":[]},"52":{"menu":"52","sub_menu":[]},"24":{"menu":"24","sub_menu":[]}}';

    // Example messages
    $pesan_kirim_tagihan = '*TAGIHAN LAYANAN INTERNET*\r\n\r\n#ket\r\nLimit Pembayaran tanggal #lmt\r\n\r\nNama : *#usr*\r\nLayanan : #lyn\r\n\r\nJumlah Tagihan : *Rp. #tot*\r\n\r\n_#Pesan Otomatis Sistem_';
    $pesan_peringatan_tagihan = 'Pelanggan yang terhormat,\r\na/n. *#usr*\r\n\r\nHari ini adalah hari terakhir untuk melakukan pembayaran internet dengan total perbayaran sebagai berikut :\r\nTotal Tagihan : *Rp. #tot*\r\n\r\n_#Pesan Otomatis Sistem_';
    $pesan_isolir_pelanggan = 'Pelanggan yang terhormat,\r\nMohon maaf saat ini internet kita matikan, karena anda belum melunasi tagihan. Lakukanlah pembayaran untuk terus menikmati layanan kami. \r\nTerimakasih..!!\r\n\r\n_#Pesan Otomatis Sistem_';
    $pesan_melunasi_tagihan = 'Terimakasih telah melakukan pembayaran tagihan layanan internet\r\n\r\n_#Pesan otomatis sistem_';
    $pesan_koneksi_off = 'Pelanggan yang terhormat,\r\nStatus koneksi anda termonitor OFF dari server kami beberapa menit lalu. Jika ada kendala silahkan hubungi atau informasikan kepada kami.\r\nTerimakasih..!!';
    $pesan_registrasi = '*REGISTRASI PELANGGAN BARU*\r\n\r\nAtas Nama : *#usr*\r\nAlamat : #add\r\n\r\nLayanan\r\nJenis Layanan : #jly\r\nPaket Berlanggaan : #lyn\r\nHarga Layanan : *#hly*\r\n\r\n#Status : *Pendaftaran berhasil*\r\n\r\n_#Pesan Otomatis Sistem_';
    $pesan_aktivasi = 'Pelanggan yang terhormat,\nLayanan anda telah di Aktivasi\n\nNama : *#usr*\nID : #ppp\n\nSelamat menikmati layanan internet kami \nTerimakasih.\n\n_#Pesan Otomatis Sistem_';

    $currentDate = new DateTime();
    $currentDate->modify('+7 days');
    $expaired_date = $currentDate->format('Y-m-d');
    $hashedPassword = password_hash($passpost, PASSWORD_DEFAULT);

    // Bind parameters
    $stmt->bindParam(':server', $server);
    $stmt->bindParam(':nama', $nama);
    $stmt->bindParam(':nomor', $nomor);
    $stmt->bindParam(':whatsapp', $nomor);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':username', $usernama);
    $stmt->bindParam(':password', $hashedPassword);
    $stmt->bindParam(':akses', $akses);
    $stmt->bindParam(':pesan_kirim_tagihan', $pesan_kirim_tagihan);
    $stmt->bindParam(':pesan_peringatan_tagihan', $pesan_peringatan_tagihan);
    $stmt->bindParam(':pesan_isolir_pelanggan', $pesan_isolir_pelanggan);
    $stmt->bindParam(':pesan_melunasi_tagihan', $pesan_melunasi_tagihan);
    $stmt->bindParam(':pesan_koneksi_off', $pesan_koneksi_off);
    $stmt->bindParam(':pesan_registrasi', $pesan_registrasi);
    $stmt->bindParam(':pesan_aktivasi', $pesan_aktivasi);
    $stmt->bindParam(':expaired_date', $expaired_date);
    $stmt->bindParam(':harga_sewa', $harga_sewa);

    // Execute the statement
    $stmt->execute();

    session_destroy();
    sweetAlert("Registrasi Berhasil", "success", baseurl('../login'));

    } catch (PDOException $e) {
        // Handle error
        sweetAlert("Error: " . $e->getMessage(), "error");
    }
  } else {
    if ($_SESSION['data_register'][6] < 2) {
      sweetAlert("Masukan kode dengan benar", "error");
      $_SESSION['data_register'][6] = $_SESSION['data_register'][6] + 1;
    } else {
      session_destroy();
      sweetAlert("Registrasi Gagal..! Periksa nomor WhatsApp anda", "error");
    }
  }
}


if (isset($_POST['register'])) {
    // Cek apakah password dan konfirmasi password sama
    if ($_POST['password'] === $_POST['confirm_password']) {
        try {
            // Mengatur nomor WhatsApp dengan prefix '62' jika belum ada
            $nomor = (substr($_POST['nomor'], 0, 2) === '62') ? $_POST['nomor'] : '62' . substr($_POST['nomor'], 1, 15);
            $email = $_POST['email'];
            $username = $_POST['username'];

            // Query untuk memeriksa keberadaan di data_server
            $stmt = $pdo->prepare("SELECT * FROM data_server WHERE email = :email OR username = :username OR whatsapp = :nomor_whatsapp");
            $stmt->bindParam(':email', $email);
            $stmt->bindParam(':username', $username);
            $stmt->bindParam(':nomor_whatsapp', $nomor);
            $stmt->execute();
            $sv_cek = $stmt->fetch(PDO::FETCH_ASSOC);

            // Query untuk memeriksa keberadaan di user_akses
            $stmt1 = $pdo->prepare("SELECT * FROM user_akses WHERE email = :email OR username = :username OR nomor_whatsapp = :nomor_whatsapp");
            $stmt1->bindParam(':email', $email);
            $stmt1->bindParam(':username', $username);
            $stmt1->bindParam(':nomor_whatsapp', $nomor);
            $stmt1->execute();
            $us_cek = $stmt1->fetch(PDO::FETCH_ASSOC);

            // Cek jika tidak ada data yang ditemukan di kedua tabel
            if (!$sv_cek && !$us_cek) {
                // Buat kode verifikasi acak
                $randomCode = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
                $kodeRendom = password_hash($randomCode, PASSWORD_DEFAULT);
                $_SESSION['data_register'] = array($_POST['server'], $_POST['nama'], $nomor, $email, $_POST['password'], $kodeRendom, '1', $username);
                $_SESSION['status'] = 'cekotp';
                $_SESSION['paket'] = $_POST['paket'];

                // Kirim pesan verifikasi
                $Pesan = "*$randomCode* adalah kode verifikasi Anda. Demi keamanan, jangan bagikan kode ini. Terimakasih sudah mendaftar";
                $Nomor = array($nomor);
                $APIwa = new PesanWA();
                $APIwa->Send_Pesan('1', 'sendMessage', $Nomor, $Pesan);
                sweetAlert("Kami akan memberikan kode Verifikasi, Lanjut ke Verifikasi", "success");
            } else {
                sweetAlert("Email, Username, atau Nomor WhatsApp sudah terdaftar", "error");
            }
        } catch (PDOException $e) {
            // Tangani kesalahan
            sweetAlert("Terjadi kesalahan saat mendaftar: " . $e->getMessage(), "error");
        }
    } else {
        sweetAlert("Password tidak sama", "error");
    }
}


?>