 <?php 

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 class="hold-transition login-page">
<div class="login-box" style="zoom : 115%;">
  <!-- /.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"><br>
      <p><small>Managemen Jaringan Propesional</small></p>
    </div>
    <div class="card-body">
      <center>
        <h5>Pulihkan Password</h5><hr>
      </center>
      <p class="login-box-msg">Masukan Nomor WhatApp Terdaftar</p>
      <form method="post" enctype="multipart/fomr-data">
        <div class="input-group mb-4">
          <input type="text" class="form-control" id="nomor" name="nomor" placeholder="Nomor WhatsApp">
          <div class="input-group-append">
            <div class="input-group-text">
              <span class="fas fa-phone"></span>
            </div>
          </div>
        </div>
        <hr>
        <div class="row">
          <div class="col-12 text-center">
            <input type="submit" name="pulihkan" class="btn btn-primary btn-block mb-4" value="Submit"/>
            <small>
              <a href="login">Kembali Login</a>
            </small>
          </div>
          <!-- /.col -->
        </div>
      </form><br>
      <?php
        if (isset($_POST['pulihkan'])) {
            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);

                // Buat kode verifikasi acak
                $randomCode = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
                $kodeRendom = password_hash($randomCode, PASSWORD_DEFAULT);

                // Cek di tabel data_server
                $stmt = $pdo->prepare("SELECT username FROM data_server WHERE whatsapp = :whatsapp");
                $stmt->bindParam(':whatsapp', $nomor, PDO::PARAM_STR);
                $stmt->execute();
                $user = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($user) {
                    $_SESSION['data_forget'] = array("akunMaster", $nomor, $kodeRendom, '1', $user['username']);
                    $_SESSION['status_forget'] = "verif";
                } else {
                    // Cek di tabel user_akses
                    $stmt = $pdo->prepare("SELECT username FROM user_akses WHERE nomor_whatsapp = :whatsapp");
                    $stmt->bindParam(':whatsapp', $nomor, PDO::PARAM_STR);
                    $stmt->execute();
                    $user1 = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($user1) {
                        $_SESSION['data_forget'] = array("akunUser", $nomor, $kodeRendom, '1', $user1['username']);
                        $_SESSION['status_forget'] = "verif";
                    } else {
                        sweetAlert("Nomor WhatsApp tidak terdaftar", "error");
                        session_destroy();
                        exit;
                    }
                }

                // Kirim pesan verifikasi
                $Pesan = "*$randomCode* adalah kode verifikasi Anda. Demi keamanan, jangan bagikan kode ini.";
                $Nomor = array($nomor);
                $APIwa = new PesanWA();
                $APIwa->Send_Pesan('1', 'sendMessage', $Nomor, $Pesan);
                sweetAlert("Kode Verifikasi akan di kirim ke nomor anda", "success");


            } catch (PDOException $e) {
                // Tangani kesalahan
                sweetAlert("Terjadi kesalahan saat Verifikasi: " . $e->getMessage(), "error");
            }
          }


          if (isset($_POST['otp'])) {
            if (password_verify($_POST['otp'], $_SESSION['data_forget'][2])) {
              $_SESSION['status_forget'] = "newpassword";
              sweetAlert("Verifikasi Berhasil..!", "success");
            } else {
              if ($_SESSION['data_forget'][3] < 2) {
                sweetAlert("Masukan kode dengan benar", "error");
                $_SESSION['data_forget'][3] = $_SESSION['data_forget'][3] + 1;
              } else {
                session_destroy();
                sweetAlert("Verifikasi Gagal", "error");
              }
            }
          }

          if (isset($_POST['simpanPassword'])) {
            if ($_POST['password'] == $_POST['confirm_password']) {

              $hashedPassword = password_hash($_POST['password'], PASSWORD_DEFAULT);
              $nomorWhatsapp = $_SESSION['data_forget'][1];
              $username = $_SESSION['data_forget'][4];

              try {
                if($_SESSION['data_forget'][0] == 'akunMaster'){
                  $stmt = $pdo->prepare("UPDATE data_server SET password = :passwordNew WHERE whatsapp = :whatsapp AND username = :username");
                  $stmt->bindParam(':passwordNew', $hashedPassword, PDO::PARAM_STR);
                  $stmt->bindParam(':whatsapp', $nomorWhatsapp, PDO::PARAM_STR);
                  $stmt->bindParam(':username', $username, PDO::PARAM_STR);
                  $stmt->execute();
                  session_destroy();
                  sweetAlert("Password telah di ubah, Silahkan Login Kembali", "success", baseurl('../login'));
                } else {
                  $stmt = $pdo->prepare("UPDATE user_akses SET password = :passwordNew WHERE nomor_whatsapp = :whatsapp AND username = :username");
                  $stmt->bindParam(':passwordNew', $hashedPassword, PDO::PARAM_STR);
                  $stmt->bindParam(':whatsapp', $nomorWhatsapp, PDO::PARAM_STR);
                  $stmt->bindParam(':username', $username, PDO::PARAM_STR);
                  $stmt->execute();
                  session_destroy();
                  sweetAlert("Password telah di ubah, Silahkan Login Kembali", "success", baseurl('../login'));
                }

              } catch (PDOException $e) {
                sweetAlert("Terjadi kesalahan : " . $e->getMessage(), "error");
              }
            } else {
              sweetAlert("Password tidak sesuai, mohon periksa kembali", "info");
            }
          }
        ?>
    </div>
    <!-- /.card-body -->
  </div>
  <!-- /.card -->
</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>
</body>
</html>
<?php

if (isset($_SESSION['data_forget']) && $_SESSION['status_forget'] == 'verif' && 
    ($_SESSION['data_forget'][0] == 'akunMaster' || $_SESSION['data_forget'][0] == 'akunUser')) {
?>
    <!-- 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 aktif</h5>
                  </center>
                </div>
            </div>
        </div>
    </div>

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

<?php

if (isset($_SESSION['data_forget']) && $_SESSION['status_forget'] == 'newpassword' && 
    ($_SESSION['data_forget'][0] == 'akunMaster' || $_SESSION['data_forget'][0] == 'akunUser')) {
 
?>
    <!-- Modal HTML -->
    <div class="modal fade" id="newPassword" tabindex="-1" role="dialog" aria-labelledby="newPasswordLabel" 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="newPasswordLabel" style="margin: auto;"><b><?php echo $_SESSION['data_forget'][4] ?></b> adalah Username anda</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>
                    <h5>Buat Password Baru</h5>
                    <form method="POST" action="" style="margin: 30px">
                      <div class="input-group mb-4">
                          <input type="password" class="form-control" name="password" placeholder="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 class="input-group mb-4">
                          <input type="password" class="form-control" 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><hr>
                      <input type="submit" name="simpanPassword" class="btn btn-primary btn-block" style="border-radius: 30px;" value="Simpan Perubahan">
                    </form>
                  </center>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Menampilkan modal saat halaman dimuat
        $(document).ready(function() {
            $('#newPassword').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>
<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>