<?php 
    // // Proses OTP di sini
    // $otp = $_POST['otp'];
    // // Lakukan validasi atau penyimpanan OTP sesuai kebutuhan
    // echo "OTP yang dimasukkan: " . htmlspecialchars($otp)."<br>";
    // $randomCode = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
    // echo "Kode Acak: " . $randomCode;
    // // Tambahkan logika tambahan untuk memproses OTP
// print_r($_SESSION);
$logo = 'images/white_logo.png';
?>
<!DOCTYPE html>
<html lang="en">
  <head>
        <!-- basic -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- mobile metas -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1">
    <!-- site metas -->
    <title>Agen Hotspot</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="css/fontawesome-free/css/all.min.css">
    <!-- icheck bootstrap -->
    <link rel="stylesheet" href="https://bilspro.com/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="https://bilspro.com/dist/css/adminlte.min.css">
    <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 style="zoom: 80%;">
<!--d-md-none d-lg-none d-xl-none-->
<div class="container p-0" style="height: 100%">
  <div class="card" style="height: 600px; background-color: #fca503; border-bottom-left-radius: 40px; border-bottom-right-radius: 40px;" >
    <center>
        <img src="<?php echo $logo; ?>" alt="logo" width="150" style="margin-top: 80px; margin-bottom: 10px;">
        <h3  style="margin-bottom: 120px; color: white;">Reset Password</h3>
      </center>
    <div class="card" style="margin: 20px; border-radius: 10px;">
      <div class="card-body">
        <?php if ($_SESSION['cek_status'] === "dikirim") { ?>
        <center>
          <h6>Masukan Kode OTP</h6><br>
          <form id="otpForm" method="POST" action="">
            <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>
        </center>
        <?php } elseif($_SESSION['cek_status'] === "ganti_password") { ?>
          <form method="post">
            <div class="form-group">
              <label style="font-style: normal;">Password Baru</label>
              <div class="input-group mb-4">
                  <input type="password" class="form-control form-control-lg" name="new_password" placeholder="Password Baru">
                  <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>
            <div class="form-group">
              <label style="font-style: normal;">Ulangi Password Baru</label>
              <div class="input-group mb-4">
                  <input type="password" class="form-control form-control-lg" name="confirm_password" placeholder="Ulangi Password">
                  <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><br>
            <input type="submit" name="ubah" value="Ubah Password" class="btn btn-warning btn-md btn-block" style="border-radius: 40px;">
          </form>

        <?php } else { ?>
        <center>
          <form method="post">
            <div class="form-group m-4">
              <label>Masukan Nomor WhatsApp Terdaftar</label>
              <input type="number" name="nomor_whatsapp" class="form-control" required="required">
            </div>
            <input type="submit" name="cek" value="Submit" class="btn btn-warning btn-rounded btn-md">
          </form>
        </center>
        <?php } ?>
        <center><br><br>
          <a href="index.php">Kembali Login</a>
        </center>
      </div>
    </div>
          <?php 
          if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if (isset($_POST['cek'])) {
                // Query untuk data_server
                if (substr($_POST['nomor_whatsapp'], 0, 2) == '62') {
                    $handphone = $_POST['nomor_whatsapp'];
                } else {
                    $handphone = '62' . substr($_POST['nomor_whatsapp'], 1);
                }
                // $handphone = $_POST['nomor_whatsapp'];
                
                $stmt = $pdo->prepare("SELECT id_data_server, nomor_whatsapp FROM agen_voucher WHERE nomor_whatsapp = :handphone");
                $stmt->bindParam(':handphone', $handphone, PDO::PARAM_STR);
                $stmt->execute();
                $user = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($user) {
                    // Generate random 5-digit code
                    $randomCode = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
                    
                    // Update OTP in the database
                    $stmt = $pdo->prepare("UPDATE agen_voucher SET otp = :otp WHERE nomor_whatsapp = :handphone");
                    $stmt->bindParam(':otp', $randomCode, PDO::PARAM_STR); // Ubah PARAM_INT menjadi PARAM_STR
                    $stmt->bindParam(':handphone', $handphone, PDO::PARAM_STR);
                    $stmt->execute();

                    // Kirim Pesan WhatsApp
                    $Pesan = "*".$randomCode."* adalah kode verifikasi Anda. Demi keamanan, jangan bagikan kode ini.";
                    $Nomor = array($handphone);
                    $APIwa = new PesanWA();
                    $APIwa->Send_Pesan($user['id_data_server'], 'sendMessage', $Nomor, $Pesan);

                    $_SESSION['cek_status'] = 'dikirim';
                    sweetAlert("Kode Verifikasi akan di kirim ke nomor anda", "success");
                } else {
                    sweetAlert("Nomor WhatsApp Anda Tidak Terdaftar", "error", baseurl());
                }
              }

              if (isset($_POST['otp'])) {
                $OTP = htmlspecialchars($_POST['otp']);
                $stmt = $pdo->prepare("SELECT id,otp FROM agen_voucher WHERE otp = :otp");
                $stmt->bindParam(':otp', $OTP, PDO::PARAM_STR);
                $stmt->execute();
                $ada = $stmt->fetch(PDO::FETCH_ASSOC);
                if ($ada) {
                  $_SESSION['cek_status'] = 'ganti_password';
                  $_SESSION['id_agen'] = $ada['id'];
                  sweetAlert("Verifikasi Berhasil","success");
                } else {
                  sweetAlert("Verifikasi Gagal, Kode salah", "error");
                }
              }

              if (isset($_POST['ubah'])) {
                if ($_POST['new_password'] === $_POST['confirm_password']) {
                  $password = $_POST['new_password'];
                  $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                  $stmt = $pdo->prepare("UPDATE agen_voucher SET password = :password WHERE id = :id");
                  $stmt->bindParam(':password', $hashedPassword, PDO::PARAM_STR); // Ubah PARAM_INT menjadi PARAM_STR
                  $stmt->bindParam(':id', $_SESSION['id_agen'], PDO::PARAM_STR);
                  $stmt->execute();
                  session_destroy();
                  sweetAlert("Password Anda Berhasil diubah, silahkan login dengan password baru anda", "success", baseurl());
                } else {
                  sweetAlert("Password tidak sama, silahkan periksa kembali", "error");
                }
              }
            }
          ?>
  <div class="text-center">
  <br><br><br><br>
  <p><i>Versi 2.1.1 @2024</i></p>
</div>
</div></div>
<!-- jQuery -->
<script src="https://bilspro.com/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="https://bilspro.com/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="https://bilspro.com/dist/js/adminlte.min.js"></script>

<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>
<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> 