<?php
// Inclui fun��es e inicia a sess�o
include "includes/functions.php";

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Verifica se o usu�rio est� logado
$log_check = $db->select("users", "*", "id = :id", "", [":id" => 1]);
$loggedinuser = !empty($log_check) ? $log_check[0]["username"] : NULL;
if (!empty($loggedinuser) && isset($_SESSION["name"]) && $_SESSION["name"] === $loggedinuser) {
    header("Location: dash.php");
    exit;
}

// Insere o usu�rio admin se n�o existir
$data = ["id" => "1", "username" => "admin", "password" => "admin"];
$db->insertIfEmpty("users", $data);

// Processa o login
$login_error = ""; // Vari�vel para mensagem de erro
if (isset($_POST["login"])) {
    $username = $_POST["username"];
    $userData = $db->select("users", "*", "username = :username", "", [":username" => $username]);
    if ($userData) {
        $storedPassword = $userData[0]["password"];
        if ($_POST["password"] === $storedPassword) {
            session_regenerate_id();
            $_SESSION["loggedin"] = true;
            $_SESSION["name"] = $_POST["username"];
            header($_POST["username"] == "admin" ? "Location: user.php" : "Location: dash.php");
            exit;
        } else {
            $login_error = "Contrasena incorreta!";
        }
    } else {
        $login_error = "Usuario nao encontrado!";
    }
    $db->close();
}

$file_name = './codigo_json.json';
$json_data = file_get_contents($file_name);

if ($json_data === false) {
    die("Erro ao ler o arquivo JSON.");
}

$data = json_decode($json_data, true);
$codigo = $data['codigo'];

// HTML da p�gina
echo <<<HTML
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="author" content="JS5Rebrands">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <title>JS5Rebrands Aplicaciones - Login</title>
    <style>
        :root {
            --dark-background: #000000;
            --form-background: rgba(30, 0, 0, 0.7);
            --input-background: rgba(50, 0, 0, 0.5);
            --input-border: #660000;
            --primary-red: #FF0000;
            --primary-dark-red: #990000;
            --text-light: #FFFFFF;
            --text-dark: #CCCCCC;
            --text-highlight: #FF3333;
            --error-color: #FF0000;
        }

        * {
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            font-family: 'Poppins', sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: linear-gradient(135deg, #000000 0%, #330000 50%, #000000 100%);
            color: var(--text-light);
            overflow-x: hidden;
            position: relative;
            touch-action: manipulation;
        }

        /* Part�culas */
        #particles-js {
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: 0;
            background: transparent;
        }

        .login-container {
            display: flex;
            flex-direction: column;
            width: 100%;
            max-width: 100%;
            background-color: transparent;
            border-radius: 0;
            overflow: hidden;
            padding: 15px;
            position: relative;
            z-index: 1;
        }

        .left-section {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 15px 0;
            text-align: center;
            width: 100%;
        }

        .left-section h1 {
            font-size: 1.5rem;
            color: var(--text-light);
            margin-bottom: 15px;
            font-weight: 600;
            line-height: 1.3;
            padding: 0 10px;
            text-shadow: 0 0 10px var(--primary-red);
        }

        .left-section .astronaut-img {
            max-width: 80%;
            height: auto;
            margin-top: 15px;
            filter: drop-shadow(0 0 10px var(--primary-red));
        }

        .right-section {
            width: 100%;
            background-color: var(--form-background);
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(255, 0, 0, 0.3);
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 15px;
            border: 1px solid var(--primary-red);
            backdrop-filter: blur(5px);
        }

        .right-section h2 {
            font-size: 1.3rem;
            color: var(--primary-red);
            margin-bottom: 20px;
            font-weight: 700;
            letter-spacing: 1px;
            text-transform: uppercase;
            text-shadow: 0 0 5px var(--primary-red);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .error-message {
            color: var(--error-color);
            background-color: rgba(255, 0, 0, 0.1);
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            width: 100%;
            text-align: center;
            font-size: 0.85rem;
            font-weight: 500;
            border: 1px solid var(--error-color);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .form-group {
            width: 100%;
            margin-bottom: 15px;
            position: relative;
        }

        .form-group label {
            display: block;
            font-size: 0.85rem;
            color: var(--text-light);
            margin-bottom: 8px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px 12px 40px;
            border: 1px solid var(--input-border);
            border-radius: 8px;
            background-color: var(--input-background);
            color: var(--text-light);
            font-size: 0.95rem;
            outline: none;
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }

        .form-control::placeholder {
            color: var(--text-dark);
            opacity: 0.8;
        }

        .form-control:focus {
            border-color: var(--primary-red);
            box-shadow: 0 0 0 3px rgba(255, 0, 0, 0.2);
        }

        .input-icon {
            position: absolute;
            left: 12px;
            top: 38px;
            color: var(--text-dark);
            font-size: 1rem;
        }

        .btn-login {
            width: 100%;
            padding: 12px;
            border: none;
            border-radius: 8px;
            background: linear-gradient(to right, var(--primary-dark-red), var(--primary-red));
            color: var(--text-light);
            font-size: 1rem;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 10px;
            box-shadow: 0 0 10px rgba(255, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-login:hover, .btn-login:active {
            background: linear-gradient(to right, var(--primary-red), var(--primary-dark-red));
            transform: translateY(-2px);
            box-shadow: 0 0 15px rgba(255, 0, 0, 0.7);
        }

        .btn-download-app {
            width: 100%;
            padding: 12px;
            border: 1px solid var(--primary-red);
            border-radius: 8px;
            background-color: transparent;
            color: var(--primary-red);
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 15px;
            text-align: center;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .btn-download-app:hover, .btn-download-app:active {
            background-color: rgba(255, 0, 0, 0.1);
            color: var(--text-light);
            transform: translateY(-2px);
            box-shadow: 0 0 10px rgba(255, 0, 0, 0.3);
        }

        /* Media Queries para telas maiores */
        @media (min-width: 480px) {
            .login-container {
                padding: 20px;
            }
            
            .left-section h1 {
                font-size: 1.7rem;
            }
        }

        @media (min-width: 768px) {
            .login-container {
                flex-direction: row;
                max-width: 900px;
                padding: 30px;
                border-radius: 20px;
            }

            .left-section {
                flex: 1;
                align-items: flex-start;
                text-align: left;
                padding-right: 30px;
            }

            .left-section h1 {
                font-size: 1.8rem;
                padding: 0;
            }

            .left-section .astronaut-img {
                max-width: 85%;
                margin-top: 25px;
            }

            .right-section {
                flex: 0.7;
                margin-top: 0;
                padding: 25px;
            }

            .right-section h2 {
                font-size: 1.5rem;
            }
        }

        @media (min-width: 992px) {
            .left-section h1 {
                font-size: 2.2rem;
            }
            
            .login-container {
                padding: 40px;
            }
        }

        /* Ajustes para telas muito pequenas */
        @media (max-width: 360px) {
            .left-section h1 {
                font-size: 1.3rem;
            }
            
            .right-section {
                padding: 15px;
            }
            
            .form-control {
                padding: 10px 15px 10px 35px;
            }
            
            .input-icon {
                font-size: 0.9rem;
                top: 35px;
            }
        }
    </style>
</head>
<body>
    <div id="particles-js"></div>
    
    <div class="login-container">
        <div class="left-section">
            <h1><i class="fas fa-rocket" style="color: var(--primary-red);"></i> Inicia sesión para unirte a nuestro equipo</h1>
            <img src="./img/logo.png" alt="Gato Astronauta" class="astronaut-img">
        </div>

        <div class="right-section">
            <h2><i class="fas fa-sign-in-alt"></i> LOGIN</h2>
HTML;

// Exibe mensagem de erro se existir
if (!empty($login_error)) {
    $icon = $login_error === "Contrasena incorreta!" ? "fa-lock" : "fa-user-times";
    echo '<div class="error-message"><i class="fas ' . $icon . '"></i>' . htmlspecialchars($login_error) . '</div>';
}

echo <<<HTML
            <form method="post">
                <div class="form-group">
                    <label for="username"><i class="fas fa-user"></i> Usuario</label>
                    <i class="fas fa-user input-icon"></i>
                    <input type="text" id="username" class="form-control" placeholder="Digite seu usuario" name="username" required autofocus>
                </div>
                <div class="form-group">
                    <label for="password"><i class="fas fa-lock"></i> Contrasena </label>
                    <i class="fas fa-lock input-icon"></i>
                    <input type="password" id="password" class="form-control" placeholder="Digite sua senha" name="password" required>
                </div>
                <button type="submit" class="btn-login" name="login">
                    <i class="fas fa-sign-in-alt"></i> ENTRAR
                </button>
                <a class="btn-download-app" href="./meu/new_ibo_app.apk" download>
                    <i class="fas fa-download"></i> DESCARGAR APLICACION
                </a>
            </form>
        </div>
    </div>

    <!-- Script para as part�culas -->
    <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Verifica se � um dispositivo m�vel
            function isMobile() {
                return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
            }
            
            // Configuraciones optimizadas para mobile
            var config = {
                "particles": {
                    "number": {
                        "value": isMobile() ? 40 : 80,
                        "density": {
                            "enable": true,
                            "value_area": isMobile() ? 600 : 800
                        }
                    },
                    "color": {
                        "value": "#ff0000"
                    },
                    "shape": {
                        "type": "circle"
                    },
                    "opacity": {
                        "value": 0.5,
                        "random": true
                    },
                    "size": {
                        "value": isMobile() ? 2 : 3,
                        "random": true
                    },
                    "line_linked": {
                        "enable": true,
                        "distance": isMobile() ? 120 : 150,
                        "color": "#ff0000",
                        "opacity": 0.4,
                        "width": 1
                    },
                    "move": {
                        "enable": true,
                        "speed": isMobile() ? 1.5 : 2,
                        "direction": "none",
                        "out_mode": "out"
                    }
                },
                "interactivity": {
                    "detect_on": "window",
                    "events": {
                        "onhover": {
                            "enable": !isMobile(),
                            "mode": "grab"
                        },
                        "onclick": {
                            "enable": true,
                            "mode": "push"
                        }
                    },
                    "modes": {
                        "grab": {
                            "distance": 140,
                            "line_linked": {
                                "opacity": 1
                            }
                        },
                        "push": {
                            "particles_nb": isMobile() ? 2 : 4
                        }
                    }
                },
                "retina_detect": true
            };
            
            particlesJS('particles-js', config);
            
            // Melhorias para touch em dispositivos m�veis
            if (isMobile()) {
                document.querySelectorAll('input').forEach(input => {
                    input.addEventListener('focus', function() {
                        setTimeout(() => {
                            window.scrollTo({
                                top: this.getBoundingClientRect().top + window.pageYOffset - 100,
                                behavior: 'smooth'
                            });
                        }, 300);
                    });
                });
            }
        });
    </script>
</body>
</html>
HTML;
?>