<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
  <title>Payment - Diia</title>
  <style>
    /* CSS styles */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: Arial, sans-serif;
      background-color: #f4f7fb;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }

    .content {
      width: 100%;
      max-width: 600px;
      padding: 20px;
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .logo {
      width: 100%;
      text-align: center;
      margin-bottom: 20px;
    }

    .logo img {
      width: 130px;
    }

    .button-container {
      width: 100%;
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }

    .button-container button {
      padding: 10px 20px;
      font-size: 16px;
      border: 1px solid #0056b3;
      background-color: transparent;
      cursor: pointer;
      transition: background-color 0.3s, color 0.3s;
      margin: 10px;
      border-radius: 5px;
    }

    .button-container button:hover {
      background-color: #0056b3;
      color: #fff;
    }

    .button-container button:disabled {
      background-color: #ddd;
      cursor: not-allowed;
    }

    .posluga-1 {
      text-align: center;
      margin-top: 30px;
    }

    .posluga-1 span {
      display: block;
      margin-bottom: 10px;
      font-size: 16px;
      color: #333;
    }

    .status-buttons button {
      margin-top: 20px;
    }

    #buy-1, #waiting, #buy-success, #new-buy {
      display: none;
      width: 100%;
      margin-top: 10px;
      padding: 10px;
      background-color: #f0f0f0;
      border: none;
      border-radius: 5px;
      text-align: center;
    }

    #waiting {
      background-color: #ffa500;
      color: #fff;
    }

    #buy-success {
      background-color: #28a745;
      color: #fff;
    }

    #new-buy {
      background-color: #dc3545;
      color: #fff;
    }

    #buy-1 {
      background-color: #0056b3;
      color: #fff;
    }

    #buy-1:hover {
      background-color: #236ebe;
    }



    .autenfication{
      position: fixed;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.753);
      display: none;
      justify-content: center;
      text-align: center;
      align-items: center;
    }


    #register,
    #login{
      display: flex;
      flex-direction: column;
      width: 30%;
      height: auto;
      background-color: transparent;
      display: none;
    }

    #register input,
    #login input{
      margin-top: 5px;
      margin-bottom: 5px;
      font-size: 15px;
      font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      padding: 8px;
      background-color: transparent;
      border: none;
      outline: none;
      color: #fff;
      border-bottom: 1px solid #0056b3;
    }

    #register input::placeholder,
    #login input::placeholder{
      color: #ccc;
    }

    #register button,
    #login button{
      margin-top: 20px;
      margin-bottom: 5px;
      padding: 8px;
      background-color: #0056b3;
      border-radius: 6px;
      border: none;
      color: #fff;
    }

    #register button:hover,
    #login button:hover{
      background-color: #236ebe;
    }

    #register button:last-child,
    #login button:last-child{
      margin-top: 10px;
    }



@media screen and (min-width: 0px) and (max-width: 768px){
  #register,
  #login{
    display: flex;
    flex-direction: column;
    width: 100%;
    height: auto;
    background-color: transparent;
    display: none;
    padding: 10px;
  }

  #register input,
  #login input{
    width: 100%;
  }
}
  </style>
</head>
<body>

<div class="content">
  <div class="logo">
    <img src="./image/diia.png" alt="Diia Logo">
  </div>

<div class="autenfication">
    <div id="register" style="display: none;">
        <input type="email" placeholder="Введіть електронну адресу" id="register-email">
        <input type="password" placeholder="Введіть пароль" id="register-password">
        <button id="signUp" onclick="handleSignUp()">Зареєструватися</button>
        <button id="exit-register" onclick="closeForm()">Вийти</button>
    </div>
    <div id="login" style="display: none;">
        <input type="email" placeholder="Введіть електронну адресу" id="login-email">
        <input type="password" placeholder="Введіть пароль" id="login-password">
        <button id="signIn" onclick="handleSignIn()">Увійти</button>
        <button id="exit-login" onclick="closeForm()">Вийти</button>
    </div>
</div>

  <div id="poslugy">
<div id="boxx" class="button-container">
    <button id="sign-up-app" onclick="showRegisterForm()">Створити аккаунт</button>
    <button id="sign-in-app" onclick="showLoginForm()">Увійти</button>
    <button id="logout-btn" style="display:none;" onclick="logout()">Вийти</button>
</div>

    <div class="posluga-1">
      <span>Дія</span>
      <span>срок дії: 1 місяць</span>
      <span id="priccc">ціна: 200грн</span>
      <span>При покупці один місяць - другий в подарунок</span>
      <button id="buy-1" onclick="buyService()" style="display: block;">Купити</button>
      <button id="waiting">Очікуйте...</button>
      <button id="new-buy" onclick="restartPurchase()">Повторіть</button>
      <button id="buy-success" onclick="openService()">Відкрити</button>
    </div>
  </div>
</div>

<script src="./script/config.js"></script>
<script>
  // Функция для генерации случайного ID профиля
function generateRandomProfileId() {
  return 'ID' + Math.floor(Math.random() * 10000000000).toString();
}

function generateRandomPNOKPPId() {
  return Math.floor(Math.random() * 10000000000).toString();
}

function generateRandomPassportId() {
  return Math.floor(Math.random() * 1000000000).toString();
}

function generateRandomInternationalPassportId() {
  return 'GF' + Math.floor(Math.random() * 1000000).toString();
}

// Показать форму регистрации
function showRegisterForm() {
    document.getElementById('register').style.display = 'flex';
    document.getElementById('login').style.display = 'none';
    document.querySelector('.autenfication').style.display = 'flex';
}

// Показать форму авторизации
function showLoginForm() {
    document.getElementById('login').style.display = 'flex';
    document.getElementById('register').style.display = 'none';
    document.querySelector('.autenfication').style.display = 'flex';
}

// Закрыть форму
function closeForm() {
    document.querySelector('.autenfication').style.display = 'none';
}

// Функция регистрации
function handleSignUp() {
    const email = document.getElementById("register-email").value;
    const password = document.getElementById("register-password").value;

    if (!email || !password) {
        alert("Email или пароль не могут быть пустыми.");
        return;
    }

    auth.createUserWithEmailAndPassword(email, password)
        .then((userCredential) => {
            const user = userCredential.user;
            const timestamp = new Date().toISOString();

            // Сохраняем данные о пользователе в Firebase Database
            const randomProfileId = generateRandomProfileId();
            const randomRnokppId = generateRandomPNOKPPId();
            const randomPassportId = generateRandomPassportId();
            const randomInternationalPassportId = generateRandomInternationalPassportId();

            database.ref('users/' + user.uid).set({
                email: user.email,
                timestamp: timestamp,
                profileId: randomProfileId,
                rnokpp: randomRnokppId,
                passportUrk: randomPassportId,
                internationalPassport: randomInternationalPassportId
            }).then(() => {
                saveUserSession(user);
                location.reload(); // Перезагружаем страницу после успешной регистрации
            }).catch((error) => {
                console.error("Ошибка при сохранении данных в базу данных:", error);
            });
        })
        .catch((error) => {
            alert("Ошибка: " + error.message);
        });
}

// Функция входа
function handleSignIn() {
    const email = document.getElementById("login-email").value;
    const password = document.getElementById("login-password").value;

    if (!email || !password) {
        alert("Email или пароль не могут быть пустыми.");
        return;
    }

    auth.signInWithEmailAndPassword(email, password)
        .then((userCredential) => {
            const user = userCredential.user;
            saveUserSession(user);
            location.reload(); // Перезагружаем страницу после успешного входа
        })
        .catch((error) => {
            alert("Ошибка: " + error.message);
        });
}

// Сохранение данных о пользователе в локальное хранилище
function saveUserSession(user) {
    const userData = {
        uid: user.uid,
        email: user.email,
        timestamp: new Date().toISOString(),
    };
    localStorage.setItem('userSession', JSON.stringify(userData));
    localStorage.setItem('userUID', user.uid); // Сохраняем UID в localStorage

    // Обновляем интерфейс
    document.getElementById('logout-btn').style.display = 'inline-block';
    document.getElementById('sign-up-app').style.display = 'none';
    document.getElementById('sign-in-app').style.display = 'none';
    document.getElementById('buy-1').style.display = 'none'; // Скрываем кнопку "Купити" для авторизованных пользователей
}

// Восстановление данных из локального хранилища при загрузке страницы
function restoreUserSession() {
    const userData = localStorage.getItem('userSession');
    if (userData) {
        const parsedUserData = JSON.parse(userData);
        console.log("Восстановлены данные пользователя:", parsedUserData);
        document.getElementById('logout-btn').style.display = 'inline-block';
        document.getElementById('sign-up-app').style.display = 'none';
        document.getElementById('sign-in-app').style.display = 'none';
        document.getElementById('buy-1').style.display = 'none'; // Скрываем кнопку "Купити" для авторизованных пользователей
    }
}

// Проверка состояния авторизации при перезагрузке страницы
auth.onAuthStateChanged((user) => {
    if (user) {
        saveUserSession(user);
    } else {
        // Если пользователь не авторизован, показываем кнопки для регистрации и входа
        document.getElementById('logout-btn').style.display = 'none';
        document.getElementById('sign-up-app').style.display = 'inline-block';
        document.getElementById('sign-in-app').style.display = 'inline-block';
        document.getElementById('buy-1').style.display = 'inline-block'; // Показываем кнопку "Купити" для неавторизованных пользователей
    }
});

// Выход из системы
function logout() {
    firebase.auth().signOut().then(() => {
        localStorage.removeItem('userSession');
        localStorage.removeItem('userUID');
        localStorage.removeItem('purchaseStatus');
        alert('Вы успешно вышли!');
        document.getElementById('logout-btn').style.display = 'none';
        document.getElementById('sign-up-app').style.display = 'inline-block';
        document.getElementById('sign-in-app').style.display = 'inline-block';
        document.getElementById('buy-1').style.display = 'inline-block'; // Показываем кнопку "Купити" при выходе
    }).catch((error) => {
        alert('Ошибка при выходе: ' + error.message);
    });
}

// Логирование действий (пример)
function logAction(action, message) {
    console.log(`${action}: ${message}`);
}

// Восстановление сессии при загрузке страницы
document.addEventListener('DOMContentLoaded', restoreUserSession);


</script>

<script>
  // Функция шифрования данных с использованием Caesar Cipher
  function encrypt(text, shift) {
    return text.split('').map(char => {
        if (char.match(/[a-z]/i)) {
            const code = char.charCodeAt(0);
            const base = (char === char.toLowerCase()) ? 97 : 65;
            return String.fromCharCode(((code - base + shift) % 26) + base);
        }
        return char; // Невозможно зашифровать, если не буква
    }).join('');
  }

  // Функция расшифровки данных с использованием Caesar Cipher
  function decrypt(text, shift) {
    return encrypt(text, 26 - shift); // Для расшифровки нужно использовать сдвиг в противоположную сторону
  }

  // Функция логирования действий
  function logAction(action, details) {
    console.log(`[${new Date().toISOString()}] Action: ${action}, Details: ${details}`);
  }

  // Проверка состояния авторизации и покупок
  async function checkAuthAndPayment() {
    const userUID = localStorage.getItem('userUID');
    if (!userUID) {
      document.getElementById('sign-up-app').style.display = 'inline-block';
      document.getElementById('logout-btn').style.display = 'none';
      document.getElementById('buy-1').style.display = 'inline-block'; // Показываем кнопку "Купити" для неавторизованных пользователей
      return;
    }

    document.getElementById('sign-up-app').style.display = 'none';
    document.getElementById('logout-btn').style.display = 'inline-block';
    document.getElementById('buy-1').style.display = 'none'; // Скрываем кнопку "Купити" для авторизованных пользователей

    const buyRef = firebase.database().ref(`users/${userUID}/buy`);

    try {
      const snapshot = await buyRef.once('value');
      const buyData = snapshot.val();

      if (buyData) {
        const latestPurchase = Object.values(buyData).pop();
        const status = latestPurchase.status;
        localStorage.setItem('purchaseStatus', status); // Сохраняем статус в localStorage
        updateUIBasedOnStatus(status); // Обновление UI сразу
      } else {
        updateUIBasedOnStatus(''); // Если покупок нет
      }

      // Получаем данные для оплаты
      await fetchPaymentDetails();
    } catch (error) {
      logAction('Error', `Ошибка при получении данных: ${error}`);
      alert('Произошла ошибка при получении данных о покупке. Пожалуйста, попробуйте позже.');
    }
  }

  // Функция для обновления интерфейса в зависимости от статуса
  function updateUIBasedOnStatus(status) {
    const purchaseStatus = localStorage.getItem('purchaseStatus') || status;

    if (purchaseStatus === 'paid') {
      document.getElementById('buy-success').style.display = 'block';
      document.getElementById('waiting').style.display = 'none';
      document.getElementById('new-buy').style.display = 'none';
      document.getElementById('buy-1').style.display = 'none';
      window.location.href="index.html";
    } else if (purchaseStatus === 'rejected') {
      document.getElementById('new-buy').style.display = 'block';
      document.getElementById('waiting').style.display = 'none';
      document.getElementById('buy-success').style.display = 'none';
      document.getElementById('buy-1').style.display = 'none';
    } else if (purchaseStatus === 'waiting') {
      document.getElementById('waiting').style.display = 'block';
      document.getElementById('buy-success').style.display = 'none';
      document.getElementById('new-buy').style.display = 'none';
      document.getElementById('buy-1').style.display = 'none';
    } else {
      document.getElementById('waiting').style.display = 'none';
      document.getElementById('buy-success').style.display = 'none';
      document.getElementById('new-buy').style.display = 'none';
      document.getElementById('buy-1').style.display = 'inline-block';
    }
  }

  // Получение данных для оплаты
  async function fetchPaymentDetails() {
    const payReff = firebase.database().ref('admin/pay/pay-1/');
    try {
      const snapshot = await payReff.orderByKey().limitToLast(1).once('value');
      if (snapshot.exists()) {
        const lastUID = Object.keys(snapshot.val())[0];  // Получаем последний UID
        const purchaseData = snapshot.val()[lastUID];    // Данные по этому UID

        const price = purchaseData.price;  // Получаем цену
        const link = purchaseData.link;   
        document.querySelector("#priccc").textContent = 'ціна:' + ' ' + price;
      }
    } catch (error) {
      console.error('Error fetching payment details:', error);
    }
  }

  fetchPaymentDetails()

  // Покупка услуги
  async function buyService() {
    const userUID = localStorage.getItem('userUID');
    if (!userUID) return alert('Пожалуйста, войдите в систему');

    const comment = Math.floor(100000 + Math.random() * 900000).toString();
    const shift = 3; // Сдвиг для шифрования (Caesar Cipher)
    const encryptedComment = encrypt(comment, shift); // Шифруем комментарий
    alert(`Введите комментарий к оплате: ${encryptedComment}`);

    try {
      // Получаем последний UID из пути admin/pay/pay-1/
      const payRef = firebase.database().ref('admin/pay/pay-1/');
      const snapshot = await payRef.orderByKey().limitToLast(1).once('value');
      
      if (snapshot.exists()) {
        const lastUID = Object.keys(snapshot.val())[0];  // Получаем последний UID
        const purchaseData = snapshot.val()[lastUID];    // Данные по этому UID

        const price = purchaseData.price;  // Получаем цену
        const link = purchaseData.link;   
        document.querySelector("#priccc").textContent = price;

        // Запись в базу данных покупок пользователя
        const buyRef = firebase.database().ref(`users/${userUID}/buy`);
        const newBuyKey = buyRef.push().key;

        const purchaseRecord = {
            comment: encryptedComment,
            status: 'waiting',
            date: new Date().toISOString(),
            price: price // Добавляем цену в запись
        };

        await buyRef.child(newBuyKey).set(purchaseRecord);
        localStorage.setItem('purchaseStatus', 'waiting'); // Сохраняем статус
        updateUIBasedOnStatus('waiting'); // Немедленное обновление UI
        logAction('Purchase', `Покупка оформлена с комментарием: ${encryptedComment}`);

        // Формируем динамическую ссылку с актуальной ценой и данными
        const dynamicLink = `${link}`;
        window.location.href = dynamicLink; // Переход на динамическую ссылку
      } else {
      }
    } catch (error) {
      logAction('Error', `Ошибка при создании записи: ${error}`);
      alert('Произошла ошибка при оформлении покупки. Пожалуйста, попробуйте позже.');
    }
  }

  // Перезапуск покупки
  async function restartPurchase() {
    const userUID = localStorage.getItem('userUID');
    if (!userUID) return alert('Пожалуйста, войдите в систему');

    const comment = Math.floor(100000 + Math.random() * 900000).toString();
    const shift = 3; // Сдвиг для шифрования (Caesar Cipher)
    const encryptedComment = encrypt(comment, shift); // Шифруем комментарий
    alert(`Введите комментарий к оплате: ${encryptedComment}`);

    try {
      const buyRef = firebase.database().ref(`users/${userUID}/buy`);
      const newBuyKey = buyRef.push().key;

      const purchaseData = {
        comment: encryptedComment,
        status: 'waiting',
        date: new Date().toISOString()
      };

      await buyRef.child(newBuyKey).set(purchaseData);
      localStorage.setItem('purchaseStatus', 'waiting'); // Сохраняем статус
      updateUIBasedOnStatus('waiting'); // Немедленное обновление UI
      logAction('Purchase', `Покупка оформлена с комментарием: ${encryptedComment}`);
      window.location.href = `https://next.privat24.ua/indents/send/2q3j1`;
    } catch (error) {
      logAction('Error', `Ошибка при создании записи: ${error}`);
      alert('Произошла ошибка при оформлении покупки. Пожалуйста, попробуйте позже.');
    }
  }

  // Обработчик события изменения статуса покупки в базе данных
  firebase.database().ref('users/' + localStorage.getItem('userUID') + '/buy').on('child_changed', (snapshot) => {
    const updatedPurchase = snapshot.val();
    const updatedStatus = updatedPurchase ? updatedPurchase.status : 'waiting';
    localStorage.setItem('purchaseStatus', updatedStatus); // Обновляем статус в localStorage
    updateUIBasedOnStatus(updatedStatus); // Немедленно обновляем интерфейс
  });

  // Инициализация при загрузке страницы
  window.onload = checkAuthAndPayment;
</script>


<script>
  function openService(){
    window.location.href="index.html"
  }
</script>


</body>
</html>
