<?php
@session_start();
include('includes/config.php');

$db = new SQLite3('./api/.db.db');
$db->exec("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY,username TEXT ,password TEXT)");
$db->exec("CREATE TABLE IF NOT EXISTS subscription(id INTEGER PRIMARY KEY, mac_address TEXT, expire_date TEXT)");
$db->exec("CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,mac_address VARCHAR(100),username VARCHAR(100),password VARCHAR(100),expire_date VARCHAR(100),url VARCHAR(100),title VARCHAR(100),created_at VARCHAR(100))");

// Comprobación de si ya hay un usuario logueado
$log_check = $db->query("SELECT * FROM users WHERE id='1'");
$roe = $log_check->fetchArray();
$loggedinuser = @$roe['username'];

if (isset($_SESSION['name']) && $_SESSION['name'] === $loggedinuser) {
    // Si el usuario ya está logueado, redirigir a user.php
    header("Location: user.php");
    exit;
}

$rows = $db->query("SELECT COUNT(*) as count FROM users");
$row = $rows->fetchArray();
$numRows = $row['count'];
if ($numRows == 0) {
    $db->exec("INSERT INTO users(id ,username, password) VALUES('1' ,'admin', 'admin')");
}

// Esta variable se utiliza para mostrar el modal de éxito solo cuando el login es exitoso
$showSuccess = false;

if (isset($_POST["login"])) {
    // Prevenir inyección SQL usando parámetros preparados
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Consulta a la base de datos para verificar las credenciales del usuario
    $sql = 'SELECT * FROM users WHERE username=:username';
    $stmt = $db->prepare($sql);
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $result = $stmt->execute();
    
    $row = $result->fetchArray();
    if ($row && $row['password'] === $password) {
        // Login exitoso
        session_regenerate_id();
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['name'] = $username;
        $showSuccess = true;
    } else {
        // Credenciales incorrectas
        $showError = true;  // Mostrar el mensaje de error
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <title>IBO 4K2 PANEL</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <style>
    /* Estilos generales */
   body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  background: url('https://i.gifer.com/PSAp.gif') no-repeat center center fixed;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
    #container {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100vh;
      box-sizing: border-box;
    }

    #form-container {
      background-color: #1e1e2f;
      padding: 20px;
      border-top: 5px solid #0A38D1;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      max-width: 350px;
      width: 100%;
      text-align: center;
      animation: neonGlowCard 3s ease-in-out infinite alternate;
    }

    /* Animación de resplandor para la tarjeta del formulario */
    @keyframes neonGlowCard {
      0% {
        filter: drop-shadow(0 0 5px #9b59b6) drop-shadow(0 0 10px #9b59b6) drop-shadow(0 0 15px #9b59b6);
        transform: scale(1);
      }
      50% {
        filter: drop-shadow(0 0 10px #9b59b6) drop-shadow(0 0 20px #9b59b6) drop-shadow(0 0 30px #9b59b6);
        transform: scale(1.05);
      }
      100% {
        filter: drop-shadow(0 0 5px #9b59b6) drop-shadow(0 0 10px #9b59b6) drop-shadow(0 0 15px #9b59b6);
        transform: scale(1);
      }
    }

    h2 {
      font-size: 22px;
      color: white;
      margin-bottom: 20px;
    }

    label {
      display: block;
      text-align: left;
      margin-top: 10px;
      margin-left: 20px;
    }

    input, select {
      width: calc(100% - 40px);
      padding: 10px;
      margin-top: 5px;
      margin-bottom: 10px;
      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: 90%;
      padding: 10px;
      border-radius: 30px;
      background-color: #0A38D1;
      color: #ffffff;
      border: none;
      cursor: pointer;
    }

    button:hover {
      background-color: #0529a3;
    }

     #logo {
      max-width: 30%;
      height: auto;
      margin: 0 auto 20px;
      animation: neonGlow 1.5s ease-in-out infinite alternate;
    }

    /* Animación de resplandor para el logo */
    @keyframes neonGlow {
      0% {
        filter: drop-shadow(0 0 5px #0A38D1) drop-shadow(0 0 10px #0A38D1) drop-shadow(0 0 20px #0A38D1);
        transform: scale(1);
      }
      50% {
        filter: drop-shadow(0 0 15px #0A38D1) drop-shadow(0 0 30px #0A38D1) drop-shadow(0 0 50px #0A38D1);
        transform: scale(1.05);
      }
      100% {
        filter: drop-shadow(0 0 5px #0A38D1) drop-shadow(0 0 10px #0A38D1) drop-shadow(0 0 20px #0A38D1);
        transform: scale(1);
      }
    }
    .alert-error {
  background-color: #e74c3c;
  color: white;
  padding: 12px 20px;
  border-radius: 5px;
  text-align: center;
  font-weight: bold;
  margin-top: 15px;
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-5px); }
  to { opacity: 1; transform: translateY(0); }
}

    /* Estilos para los modales */
    .modal {
      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;
    }

    /* Estilos para las alertas de éxito y error */
    .alert {
      display: none;
      padding: 15px;
      margin-top: 20px;
      border-radius: 5px;
      text-align: center;
    }

    .alert-success {
      background-color: #4CAF50;
      color: white;
    }

    .alert-error {
      background-color: #f44336;
      color: white;
    }
  </style>
</head>
<body>
<?php if ($showError): ?>
    <!-- Modal de error -->
    <div id="errorLoginModal" style="display:block; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999;">
        <div style="background:#fff; padding:20px; margin:15% auto; width:300px; text-align:center; border-radius:10px;">
            <p style="font-size:18px; color:red;">❌ Wrong Credentials!</p>
            <button onclick="closeErrorModal()" style="margin-top:10px;">Try Again</button>
        </div>
    </div>
    <script>
        function closeErrorModal() {
            document.getElementById('errorLoginModal').style.display = 'none';
        }
    </script>
<?php endif; ?>

<?php if ($showSuccess): ?>
    <!-- Modal de éxito -->
    <div id="successLoginModal" style="display:block; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999;">
        <div style="background:#fff; padding:20px; margin:15% auto; width:300px; text-align:center; border-radius:10px;">
            <p style="font-size:18px;">✅ Login Successful!</p>
            <button onclick="closeSuccessModal()" style="margin-top:10px;">Go to Panel</button>
        </div>
    </div>
    <script>
        function closeSuccessModal() {
            document.getElementById('successLoginModal').style.display = 'none';
            window.location.href = 'user.php';  // Redirige después de cerrar el modal
        }
    </script>
<?php endif; ?>

  <div id="container">
  <div id="form-container">
    <h2>IBO 4K2 PANEL</h2>
    <?php
    $logoPath = ''; // Inicializa vacío

    $jsonPath = './logo/filenames.json';
    if (file_exists($jsonPath)) {
        $jsonData = file_get_contents($jsonPath);
        $imageData = json_decode($jsonData, true);

        if (!empty($imageData[0]['ImageName'])) {
            if ($imageData[0]['Upload_type'] === 'by_file') {
                $logoPath = './logo/' . $imageData[0]['ImageName'];
            } elseif ($imageData[0]['Upload_type'] === 'by_url') {
                $logoPath = $imageData[0]['ImageName'];
            }
        }
    }
    ?>
    <?php if (!empty($logoPath)): ?>
      <img id="logo" src="<?= htmlspecialchars($logoPath) ?>" alt="Logo">
    <?php endif; ?>

    <form method="POST" id="loginForm">
      <label for="usuario">User:</label>
      <input type="text" id="usuario" name="username" placeholder="User" required>

      <label for="senha">Password:</label>
      <div class="input-group">
        <input type="password" id="senha" name="password" placeholder="Password" required>
        <span class="toggle-password" onclick="togglePassword()">
          <i class="fa fa-eye-slash" id="toggleIcon"></i>
        </span>
      </div>
        <button type="submit" name="login">Login</button>
        <center style="margin-top: 20px;">
  <a class="list-group-item" href="https://t.me/MyApp_Personalizada/" target="_blank" style="text-decoration: none; color: #39FF14;">
    <i class="fab fa-telegram-plane" style="margin-right: 8px;"></i>
    © <?php echo date("Y"); ?> * MÁS APPS *
  </a>
</center>
      </form>

      <?php if (!empty($message)) echo $message; ?>

      <?php if (isset($loginSuccess) && $loginSuccess): ?>
        <div id="successAlert" class="alert alert-success" style="display:block;">
          <strong>Success!</strong> You have successfully logged in.
        </div>
      <?php elseif (isset($loginSuccess) && !$loginSuccess): ?>
        <div id="errorAlert" class="alert alert-error" style="display:block;">
          <strong>Error!</strong> <?= htmlspecialchars($message) ?>
        </div>
      <?php endif; ?>
    </div>
  </div>

<!-- Modal de Error -->
<div id="errorModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Login error. Please verify your credentials..</p>
  </div>
</div>
  <script>
    // Función para mostrar u ocultar la contraseña
    function togglePassword() {
      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');
      }
    }
    
  </script>
  <script>
  function showModal(id) {
    document.getElementById(id).style.display = "block";
  }

  function closeModal(id) {
    document.getElementById(id).style.display = "none";
  }

  // Cierra el modal si se hace clic fuera de él
  window.onclick = function(event) {
    const successModal = document.getElementById("successModal");
    const errorModal = document.getElementById("errorModal");

    if (event.target === successModal) {
      closeModal("successModal");
    }
    if (event.target === errorModal) {
      closeModal("errorModal");
    }
  };
</script>
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const loginSuccess = <?= isset($loginSuccess) && $loginSuccess ? 'true' : 'false' ?>;
    const loginFailed = <?= isset($loginSuccess) && !$loginSuccess ? 'true' : 'false' ?>;

    if (loginSuccess) {
      showModal("successModal");
    } else if (loginFailed) {
      showModal("errorModal");
    }
  });
</script>

  <!-- Bootstrap opcional si decides usar componentes -->
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>

</body>
</html>