<?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 sistema_rgvip.php
    header("Location: sistema_rgvip.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="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <title>ESSO4K Panels</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 simplificado -->
<div id="errorLoginModal" style="display:block;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);z-index:9999;animation:fadeIn 0.3s;">
    <div style="background:#fff;padding:25px;margin:15% auto;width:320px;text-align:center;border-radius:10px;box-shadow:0 5px 15px rgba(0,0,0,0.2);border-top:4px solid #ff4757;animation:slideDown 0.4s;">
        <div style="font-size:50px;color:#ff4757;margin-bottom:10px;">✗</div>
        <h3 style="color:#333;margin-bottom:10px;font-size:20px;">Credenciales incorrectas</h3>
        <p style="color:#666;margin-bottom:20px;">Usuario o contraseña inválidos</p>
        <button onclick="closeErrorModal()" style="padding:10px 25px;background:#ff4757;color:white;border:none;border-radius:5px;cursor:pointer;transition:0.3s;">Entendido</button>
    </div>
</div>

<script>
    function closeErrorModal() {
        document.getElementById('errorLoginModal').style.animation = 'fadeOut 0.3s';
        setTimeout(() => {
            document.getElementById('errorLoginModal').style.display = 'none';
        }, 300);
    }

    // Animaciones mínimas
    const style = document.createElement('style');
    style.textContent = `
        @keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
        @keyframes fadeOut { to { opacity:0; } }
        @keyframes slideDown { 
            from { transform:translateY(-30px); opacity:0; } 
            to { transform:translateY(0); opacity:1; } 
        }
        button:hover { background:#ff6b81; transform:translateY(-2px); }
    `;
    document.head.appendChild(style);
</script>
<?php endif; ?>

<?php if ($showSuccess): ?>
   <!-- Modal de éxito automático sin botón -->
<div id="successLoginModal" style="display:block; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.7); z-index:9999; animation: fadeIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);">
    <div style="background:#ffffff; padding:30px; margin:15% auto; width:360px; text-align:center; border-radius:12px; box-shadow:0 10px 30px rgba(0,0,0,0.15); border-top:4px solid #6e48aa; animation: slideDown 0.5s;">
        <div style="font-size:72px; color:#6e48aa; margin-bottom:10px; animation: pulse 1.5s infinite;">✓</div>
        <p style="font-size:24px; color:#2a3f54; margin-bottom:5px; font-weight:600;">¡Bienvenido!</p>
        <p style="color:#6c757d; margin-bottom:25px;">Accesos exitoso</p>
        
        <div style="margin:30px auto; width:80%; position:relative;">
            <div style="width:100%; height:6px; background:#f0f0f0; border-radius:3px; overflow:hidden;">
                <div id="countdownBar" style="width:100%; height:100%; background:linear-gradient(90deg, #6e48aa 0%, #9d50bb 100%); border-radius:3px; animation: countdown 3s linear forwards;"></div>
            </div>
            <div id="countdownText" style="position:absolute; right:0; top:-25px; color:#6e48aa; font-weight:bold; font-size:14px; animation: bounce 0.8s infinite alternate;">3s</div>
        </div>
        
        <div style="color:#adb5bd; font-size:13px; margin-top:20px;">
            <i class="fas fa-spinner fa-spin"></i> Cargando panel de control ESSO4K...
        </div>
    </div>
</div>

<script>
    // Contador regresivo mejorado
    let seconds = 3;
    const updateCountdown = () => {
        document.getElementById('countdownText').textContent = `${seconds}s`;
        seconds--;
        if(seconds < 0) {
            clearInterval(countdownInterval);
            document.getElementById('countdownText').style.animation = 'none';
        }
    };
    const countdownInterval = setInterval(updateCountdown, 1000);
    updateCountdown();

    // Redirección automática con efecto de salida
    setTimeout(() => {
        document.getElementById('successLoginModal').style.animation = 'fadeOut 0.5s forwards';
        setTimeout(() => window.location.href = 'sistema_rgvip.php', 500);
    }, 3000);

    // Animaciones CSS dinámicas
    const style = document.createElement('style');
    style.textContent = `
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        @keyframes slideDown {
            from { transform: translateY(-30px) scale(0.95); opacity: 0; }
            to { transform: translateY(0) scale(1); opacity: 1; }
        }
        @keyframes fadeOut {
            to { opacity: 0; transform: translateY(20px) scale(0.98); }
        }
        @keyframes countdown {
            from { width: 100%; }
            to { width: 0%; }
        }
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }
        @keyframes bounce {
            from { transform: translateY(0); }
            to { transform: translateY(-5px); }
        }
    `;
    document.head.appendChild(style);
</script>
<?php endif; ?>

  <div id="container">
  <div id="form-container">
    <h2>ESSO4K PANELS</h2>
   <?php
$logoPath = 'img/logorgvip.png'; // Valor por defecto

$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'];
        }
    }
}
?>
<img id="logo" src="<?= htmlspecialchars($logoPath) ?>" alt="Logo">

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

      <label for="senha">Contraseña:</label>
      <div class="input-group">
        <input type="password" id="senha" name="password" placeholder="Contraseña" required>
        <span class="toggle-password" onclick="togglePassword()">
          <i class="fa fa-eye-slash" id="toggleIcon"></i>
        </span>
      </div>
        <button type="submit" name="login">Iniciar sesión</button>
        <center style="margin-top: 20px;">
  <a class="list-group-item" href="https://esso4k-tv.com/" target="_blank" style="text-decoration: none; color: #39FF14;">
    <i class="fab fa-telegram-plane" style="margin-right: 8px;"></i>
    © <?php echo date("Y"); ?> * Rgvip Panels *
  </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>¡Éxito!</strong> Has iniciado sesión correctamente.
        </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>Error en el login. Por favor, verifica tus credenciales.</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>