<nav class="navbar fixed-top">
    <div id="specificCard" class="card col-12" style="border-radius: 20px; background: none; border: none; margin-top: 10px;">
        <div class="row">
            <div class="col-6 icon-container">
                <a href="index.php" class="fa fa-arrow-left text-light"></a>
            </div>
            <div class="col-6 text-right">
                <h6 class="text-light mt-2 mb-2">Setting Akun</h6>
            </div>
        </div>
    </div>
</nav>
<div class="card" style="border-radius: 0px; background: none; border: none; margin-top: 100px;">
  <div class="card-body">
      
<!--<button onclick="tampilkanNama()">Tampilkan Nama</button>-->
  </div>
</div>
<div class="card" id="2" style="border-top-right-radius: 40px; border-top-left-radius: 40px; min-height: 800px; border: none; z-index: 1;">
  <div class="card-body m-4">
    <center>
      <img id="profileImage" src="profile/<?php echo $pcmem['profile']; ?>" class="rounded-circle" width="130px" onclick="document.getElementById('fileInput').click();">
      <form action="" method="post" enctype="multipart/form-data" style="display:none;">
          <input type="file" name="profile" id="fileInput" accept="image/*" onchange="this.form.submit();">
      </form><br>
      <i><small>Klik untuk ubah</small></i><br><hr>
    </center>
    <form method="post" enctype="multipart/form-data">
      <div class="form-group">
          <label><small>Email Pengguna</small></label>
          <input type="email" name="email" class="form-control" style="border-top: none;border-left: none;border-right: none;" required="required" value="<?php echo $pcmem['email']; ?>" disabled>
      </div>
      <div class="form-group">
          <label><small>Nama Pengguna</small></label>
          <input type="text" name="nama" class="form-control" style="border-top: none;border-left: none;border-right: none;" required="required" value="<?php echo $pcmem['nama']; ?>" disabled>
      </div>
      <div class="form-group">
          <label><small>Alamat Pengguna</small></label>
          <input type="text" name="alamat" class="form-control" style="border-top: none;border-left: none;border-right: none;" required="required" value="<?php echo $pcmem['alamat']; ?>" disabled>
      </div>
      <div class="form-group">
          <label><small>Nomor Telepon</small></label>
          <input type="text" name="nohp" class="form-control" style="border-top: none;border-left: none;border-right: none;" required="required" value="<?php echo $pcmem['nomor_whatsapp']; ?>" disabled>
      </div><br>
      <center><p><u>Ubah Password</u></p></center>
      <div class="form-group">
        <label><small>Password Baru</small></label>
        <div class="input-group mb-4">
            <input type="password" class="form-control" name="new_password" style="border-top: none;border-left: none;border-right: none;">
            <div class="input-group-append">
                <div class="input-group-text" style="background: none; border-top: none;border-left: none;border-right: none;">
                    <span class="fas fa-eye toggle-password" style="cursor: pointer;"></span>
                </div>
            </div>
        </div>
      </div>
      <div class="form-group">
        <label><small>Ulangi Password Baru</small></label>
        <div class="input-group mb-4">
            <input type="password" class="form-control" name="confirm_password" style="border-top: none;border-left: none;border-right: none;">
            <div class="input-group-append">
                <div class="input-group-text" style="background: none; border-top: none;border-left: none;border-right: none;">
                    <span class="fas fa-eye toggle-password" style="cursor: pointer;"></span>
                </div>
            </div>
        </div>
      </div>
      <input type="submit" name="update" style="border-radius: 20px; margin-top: 50px; margin-bottom: 50px;" class="btn btn-warning btn-rouded btn-block" value="Simpan Perubahan" />
    <!--<p id="deviceInfo">Loading device info...</p>-->
    
<!--<p id="token"></p>-->
<!--<p id="handphone"></p>-->

    
    </form>
  </div>
</div>

<?php
// Proses upload gambar
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if(isset($_POST['update'])) { 
    if (!empty($_POST['new_password']) || !empty($_POST['confirm_password'])) {
      if ($_POST['new_password'] === $_POST['confirm_password']) {
        $password = $_POST['new_password'];
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $isNewPassword = true; // Menandakan bahwa password baru digunakan
      } else {
        sweetAlert("Password tidak sama, silahkan periksa kembali", "error");
        exit; // Menghentikan eksekusi lebih lanjut jika password tidak cocok
      }
    } else {
      $hashedPassword = $pcmem['password']; // Menggunakan password lama jika tidak ada yang diinput
      $isNewPassword = false; // Tidak ada password baru
    }
    if (substr($_POST['nohp'], 0, 2) == '62') {
        $handphone = $_POST['nohp'];
    } else {
        $handphone = '62' . substr($_POST['nohp'], 1);
    }
    try {
    //   $stmt = $pdo->prepare("UPDATE agen_voucher SET email = :email, nama = :nama, alamat = :alamat, nomor_whatsapp = :nomor_whatsapp, password = :password WHERE id = :id");
      
    //   $stmt->bindParam(':email', $_POST['email']);
    //   $stmt->bindParam(':nama', $_POST['nama']);
    //   $stmt->bindParam(':alamat', $_POST['alamat']);
    //   $stmt->bindParam(':nomor_whatsapp', $handphone);
    //   $stmt->bindParam(':password', $hashedPassword);
    //   $stmt->bindParam(':id', $_SESSION['agen'], PDO::PARAM_INT);
      
      $stmt = $pdo->prepare("UPDATE agen_voucher SET password = :password WHERE id = :id");
      
      $stmt->bindParam(':password', $hashedPassword);
      $stmt->bindParam(':id', $_SESSION['agen'], PDO::PARAM_INT);

      if ($stmt->execute()) {
        if ($isNewPassword) {
          session_destroy(); // Hancurkan sesi jika password baru diubah
          sweetAlert("Data Berhasil diubah, silahkan Login Kembali", "success");
        } else {
          sweetAlert("Data Berhasil diubah", "success");
        }
      } else {
        sweetAlert("Gagal memperbarui data, silahkan coba lagi", "error");
      }
    } catch (PDOException $e) {
      sweetAlert("Terjadi kesalahan: " . $e->getMessage(), "error");
    }
  } else {
    $target_dir = "profile/";
    $imageFileType = strtolower(pathinfo($_FILES["profile"]["name"], PATHINFO_EXTENSION));
    
    // Membuat nama file baru
    $new_file_name = "profile_" . date('YmdHis') . "." . $imageFileType;
    $target_file = $target_dir . $new_file_name;
    $uploadOk = 1;

    // Cek apakah file gambar adalah gambar yang sebenarnya
    $check = getimagesize($_FILES["profile"]["tmp_name"]);
    if ($check === false) {
        sweetAlert("File bukan gambar.","error");
        $uploadOk = 0;
    }

    // Cek ukuran file
    if ($_FILES["profile"]["size"] > 10000000) {
        sweetAlert("Maaf, ukuran file terlalu besar.","error");
        $uploadOk = 0;
    }

    // Cek format file
    if (!in_array($imageFileType, ["jpg", "png", "jpeg", "gif"])) {

      sweetAlert("Maaf, hanya file JPG, JPEG, PNG & GIF yang diperbolehkan.","error");
        $uploadOk = 0;
    }

    // Jika semua baik-baik saja, maka upload file
    if ($uploadOk == 1) {
        if (move_uploaded_file($_FILES["profile"]["tmp_name"], $target_file)) {
            // Simpan nama file baru ke database
            $id = $_SESSION['agen'];
            $sql = "UPDATE agen_voucher SET profile = '$new_file_name' WHERE id = $id";
            if ($con->query($sql) === TRUE) {
              sweetAlert("Profile telah di ubah","success");
            } else {
              sweetAlert("Error: " . $sql . "<br>" . $conn->error,"error");
            }
        } else {

          sweetAlert("Maaf, terjadi kesalahan saat mengunggah file.","error");
        }
    }
  }
}
?>
<script>
    // Optional: Menampilkan preview gambar setelah pemilihan file
    document.getElementById('fileInput').addEventListener('change', function(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('profileImage').src = e.target.result;
            }
            reader.readAsDataURL(file);
        }
    });
</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>


    <script>
        // Retrieving data from localStorage
        var token = localStorage.getItem('token');
        var handphone = localStorage.getItem('handphone');

        // Displaying data in HTML elements
        document.getElementById('token').innerText = "Token: " + token;
        document.getElementById('handphone').innerText = "Handphone: " + handphone;
    </script>
    
    
    