<?php
session_start();

// Conectar ao banco de dados SQLite
$databaseFile = './api/db/studiolivecode_dns.db';

try {
    $conn = new PDO("sqlite:$databaseFile");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Consulta para obter os valores da coluna name_server
    $query = $conn->query("SELECT title FROM dns");
    $dnsOptions = $query->fetchAll(PDO::FETCH_COLUMN);

} catch (PDOException $e) {
    echo "Erro ao conectar ao banco de dados: " . $e->getMessage();
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0 10px;
      background: url('https://source.unsplash.com/1600x900/?programming') center/cover no-repeat fixed;
    }

    #container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }

    #form-container {
      background-color: rgba(255, 255, 255, 0.8);
      padding: 20px;
      border-top: 5px solid #0A38D1;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      max-width: 400px;
      width: 100%;
      text-align: center;
    }

    h2 {
      text-align: center;
      margin-bottom: 20px;
    }

    label {
      display: block;
      text-align: left;
      margin-top: 5px;
      margin-left: 20px;
    }

    input, select {
      width: calc(100% - 40px);
      padding: 15px 10px;
      margin-top: 5px;
      margin-bottom: 15px;
      box-sizing: border-box;
      border-radius: 5px;
      border: 1px solid #ccc;
    }

    .input-group {
      position: relative;
      width: calc(100% - 40px);
      margin: 0 auto 15px;
    }

    .input-group input {
      width: 100%;
      padding-right: 40px;
    }

    .input-group .toggle-password {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-80%);
      cursor: pointer;
      color: #0A38D1;
    }

    .input-group .toggle-password i {
      font-size: 18px; 
    }

    button {
      width: 100%;
      margin-top: 10px;
      padding: 15px 10px;
      border-radius: 5px;
      background-color: #0A38D1;
      color: #ffffff;
      border: none;
      cursor: pointer;
    }

    button:hover {
      background-color: #0529a3;
    }

    #logo {
      max-width: 100%;
      height: auto;
      margin: 0 auto 20px;
    }

    #macModal, #successModal, #errorModal, #invalidUserPassModal {
      display: none;
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 300px;
      text-align: center;
      border-radius: 10px;
    }

    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }
  </style>
  <title>Adicionar Playlist</title>
</head>
<body>
  <div id="macModal">
    <div class="modal-content">
      <h3>Chave do Dispositivo</h3>
      <input type="text" id="modalIdInput" placeholder="Digite a Chave do Dispositivo" oninput="formatarId(this)">
      <button onclick="verificarId()">Confirmar</button>
    </div>
  </div>

  <div id="successModal">
    <div class="modal-content">
      <span class="close" onclick="closeSuccessModal()">&times;</span>
      <h2>Sucesso!</h2>
      <p>Dados inseridos com sucesso. Redirecionando...</p>
    </div>
  </div>

  <div id="errorModal">
    <div class="modal-content">
      <span class="close" onclick="closeErrorModal()">&times;</span>
      <h2>Erro!</h2>
      <p>ID inválido. Tente novamente.</p>
    </div>
  </div>

  <div id="invalidUserPassModal">
    <div class="modal-content">
      <span class="close" onclick="closeInvalidUserPassModal()">&times;</span>
      <h2>Erro!</h2>
      <p>Usuário ou senha está errado. Tente novamente.</p>
    </div>
  </div>

  <div id="container">
    <div id="form-container">
      <h2>Adicionar Dispositivo</h2>

      <img id="logo" style="width:60px" src="./assets/images/logo.png" alt="Logo">

      <form method="post" action="authqr.php" id="loginForm">
        <label for="dns">Conexão:</label>
        <select id="dns" name="dns" required>
          <?php
          foreach ($dnsOptions as $index => $dnsOption) {
              $selected = $index === 0 ? 'selected' : '';
              echo "<option value=\"$dnsOption\" $selected>$dnsOption</option>";
          }
          ?>
        </select>

        <input type="hidden" id="id" name="id" placeholder="Digite o ID" required oninput="formatarId(this)">

        <input type="hidden" id="nomePlaylist" name="nomePlaylist" value="Usuário login web">

        <label for="usuario">Usuário:</label>
        <input type="text" id="usuario" name="usuario" placeholder="Digite o seu usuário" required>

        <label for="senha">Senha:</label>
        <div class="input-group">
          <input type="password" id="senha" name="senha" placeholder="Digite a sua senha" required>
          <span class="toggle-password" onclick="toggleSenha()">
            <i class="fa fa-eye-slash" id="toggleIcon"></i>
          </span>
        </div>

        <button class="input-group" type="submit">Enviar</button>
      </form>
      <label for="mac" id="statusMessage"></label>
    </div>
  </div>

  <script>
    function formatarId(input) {
      // Aqui você pode adicionar formatação específica para o ID, se necessário
    }

    function verificarId() {
      var idInput = document.getElementById('modalIdInput').value;

      if (idInput) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "verificar_id.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4) {
            console.log(xhr.responseText); // Mensagem de depuração
            if (xhr.status === 200 && xhr.responseText.trim() === "true") {
              document.getElementById('id').value = idInput;
              closeMacModal();
            } else {
              showErrorModal();
            }
          }
        };
        xhr.send("id=" + encodeURIComponent(idInput));
      }
    }

    function closeMacModal() {
      document.getElementById('macModal').style.display = 'none';
    }

    function closeSuccessModal() {
      document.getElementById('successModal').style.display = 'none';
    }

    function closeErrorModal() {
      document.getElementById('errorModal').style.display = 'none';
    }

    function closeInvalidUserPassModal() {
      document.getElementById('invalidUserPassModal').style.display = 'none';
    }

    function showErrorModal() {
      document.getElementById('errorModal').style.display = 'block';
    }

    function showInvalidUserPassModal() {
      document.getElementById('invalidUserPassModal').style.display = 'block';
    }

    function toggleSenha() {
      var senha = document.getElementById('senha');
      var toggleIcon = document.getElementById('toggleIcon');
      if (senha.type === "password") {
        senha.type = "text";
        toggleIcon.classList.remove('fa-eye-slash');
        toggleIcon.classList.add('fa-eye');
      } else {
        senha.type = "password";
        toggleIcon.classList.remove('fa-eye');
        toggleIcon.classList.add('fa-eye-slash');
      }
    }

    window.onload = function() {
      document.getElementById('macModal').style.display = 'block';
      <?php if (isset($_SESSION['success_message'])): ?>
        document.getElementById('successModal').style.display = 'block';
        setTimeout(function() {
          window.location.href = "./loginqr.php";
        }, 5000);
        <?php unset($_SESSION['success_message']); ?>
      <?php endif; ?>
      <?php if (isset($_SESSION['error_message'])): ?>
        showInvalidUserPassModal();
        <?php unset($_SESSION['error_message']); ?>
      <?php endif; ?>
    };
  </script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</body>
</html>
