<?php
require_once 'auth.php';
if (isLoggedIn()) {
    header("Location: dashboard.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TecnoTrack - ACCESO AL SISTEMA</title>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-dark: #050a10;
            --cyan-glow: #00f2ff;
            --glass-bg: rgba(10, 25, 47, 0.7);
            --glass-border: rgba(0, 242, 255, 0.2);
            --text-main: #e6f1ff;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Outfit', sans-serif;
            background: var(--bg-dark);
            background-image: radial-gradient(circle at 50% 50%, rgba(0, 242, 255, 0.05) 0%, transparent 60%);
            color: var(--text-main);
            min-height: 100vh;
            margin: 0;
            display: flex;
            flex-direction: column;
            overflow-x: hidden;
        }

        .login-container {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .login-card {
            background: var(--glass-bg);
            padding: 40px;
            border-radius: 20px;
            border: 1px solid var(--glass-border);
            width: 100%;
            max-width: 400px;
            text-align: center;
            backdrop-filter: blur(10px);
            box-shadow: 0 0 50px rgba(0, 242, 255, 0.1);
            animation: float 6s ease-in-out infinite;
        }

        h1 {
            color: var(--cyan-glow);
            font-weight: 800;
            letter-spacing: 2px;
            margin-bottom: 10px;
            text-shadow: 0 0 15px rgba(0, 242, 255, 0.5);
        }

        p.subtitle {
            color: #8892b0;
            font-size: 0.9rem;
            margin-bottom: 30px;
        }

        .input-group {
            margin-bottom: 20px;
            text-align: left;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-size: 0.8rem;
            color: var(--cyan-glow);
            font-weight: 600;
        }

        input {
            width: 100%;
            padding: 12px;
            background: rgba(0, 0, 0, 0.3);
            border: 1px solid var(--glass-border);
            border-radius: 8px;
            color: #fff;
            font-family: inherit;
            transition: all 0.3s;
        }

        input:focus {
            outline: none;
            border-color: var(--cyan-glow);
            box-shadow: 0 0 15px rgba(0, 242, 255, 0.2);
        }

        button {
            width: 100%;
            padding: 15px;
            background: rgba(0, 242, 255, 0.1);
            border: 1px solid var(--cyan-glow);
            color: var(--cyan-glow);
            font-weight: 800;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-top: 10px;
        }

        button:hover {
            background: var(--cyan-glow);
            color: var(--bg-dark);
            box-shadow: 0 0 30px rgba(0, 242, 255, 0.4);
        }

        .error-msg {
            color: #ff4d4d;
            font-size: 0.85rem;
            margin-top: 15px;
            min-height: 20px;
            display: none;
        }

        @keyframes float {
            0%, 100% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-10px);
            }
        }

        /* PARTICLE CANVAS */
        #particlesCanvas {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1;
            background: radial-gradient(circle at 50% 50%, #0a192f 0%, #050a10 100%);
        }
    </style>
</head>

<body>
    <?php include 'header.php'; ?>
    
    <canvas id="particlesCanvas"></canvas>

    <div class="login-container">
        <div class="login-card">
            <img src="img/logo_login.png" alt="Tecnotrack" style="max-width: 100%; height: auto; margin-bottom: 20px;">

            <form id="loginForm" onsubmit="handleLogin(event)">
                <div class="input-group">
                    <label>USUARIO</label>
                    <input type="text" id="username" autocomplete="off" required>
                </div>
                <div class="input-group">
                    <label>CLAVE DE ACCESO</label>
                    <input type="password" id="password" required>
                </div>

                <div style="text-align: left; margin-bottom: 20px; display: flex; align-items: center; gap: 10px;">
                    <input type="checkbox" id="rememberMe" style="width: auto;">
                    <label for="rememberMe" style="margin: 0; cursor: pointer; color: #8892b0; font-size: 0.85rem;">Recordar
                        mis datos</label>
                </div>

                <button type="submit">INGRESAR</button>
                <div style="margin-top: 20px; font-size: 0.9rem;">
                    <a href="register.php"
                        style="color: var(--cyan-glow); text-decoration: none; border-bottom: 1px dashed var(--cyan-glow);">Solicitar
                        Acceso (Registro)</a>
                </div>
                <div id="errorMsg" class="error-msg">Credenciales incorrectas</div>
            </form>
        </div>
    </div>
    
    <?php include 'footer.php'; ?>

    <script>
        // Load saved credentials on startup
        document.addEventListener('DOMContentLoaded', () => {
            const savedUser = localStorage.getItem('buque_user');
            const savedPass = localStorage.getItem('buque_pass');
            // Decode simple base64 to avoid plain text visual (not secure, just obfuscation)
            if (savedUser && savedPass) {
                document.getElementById('username').value = atob(savedUser);
                document.getElementById('password').value = atob(savedPass);
                document.getElementById('rememberMe').checked = true;
            }
        });

        async function handleLogin(e) {
            e.preventDefault();
            const user = document.getElementById('username').value;
            const pass = document.getElementById('password').value;
            const remember = document.getElementById('rememberMe').checked;

            const errorEl = document.getElementById('errorMsg');
            const btn = e.target.querySelector('button');

            btn.disabled = true;
            btn.textContent = "Verificando...";
            errorEl.style.display = 'none';

            try {
                const response = await fetch('api/login.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ user, pass })
                });
                const result = await response.json();

                if (result.success) {
                    if (remember) {
                        // Simple base64 encoding for storage
                        localStorage.setItem('buque_user', btoa(user));
                        localStorage.setItem('buque_pass', btoa(pass));
                    } else {
                        localStorage.removeItem('buque_user');
                        localStorage.removeItem('buque_pass');
                    }
                    window.location.href = 'dashboard.php';
                } else {
                    errorEl.textContent = "Acceso Denegado: Credenciales invalidas";
                    errorEl.style.display = 'block';
                    btn.textContent = "INGRESAR";
                    btn.disabled = false;
                }
            } catch (error) {
                console.error(error);
                errorEl.textContent = "Error de conexi??n";
                errorEl.style.display = 'block';
                btn.textContent = "INGRESAR";
                btn.disabled = false;
            }
        }

        // PARTICLE SYSTEM (SENSOR NETWORK THEME)
        const canvas = document.getElementById('particlesCanvas');
        const ctx = canvas.getContext('2d');
        let particles = [];
        const particleCount = 80;
        const connectionDistance = 150;
        const mouse = { x: null, y: null, radius: 150 };

        window.addEventListener('mousemove', (e) => {
            mouse.x = e.x;
            mouse.y = e.y;
        });

        class Particle {
            constructor() {
                this.x = Math.random() * canvas.width;
                this.y = Math.random() * canvas.height;
                this.size = Math.random() * 2 + 1;
                this.speedX = Math.random() * 1 - 0.5;
                this.speedY = Math.random() * 1 - 0.5;
                this.baseX = this.x;
                this.baseY = this.y;
                this.density = (Math.random() * 30) + 1;
            }

            draw() {
                ctx.fillStyle = 'rgba(0, 242, 255, 0.5)';
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                ctx.closePath();
                ctx.fill();

                // Sensor "Glow"
                ctx.shadowBlur = 10;
                ctx.shadowColor = 'rgba(0, 242, 255, 0.5)';
            }

            update() {
                // Movement
                this.x += this.speedX;
                this.y += this.speedY;

                // Screen bounce
                if (this.x > canvas.width || this.x < 0) this.speedX = -this.speedX;
                if (this.y > canvas.height || this.y < 0) this.speedY = -this.speedY;

                // Mouse interaction
                let dx = mouse.x - this.x;
                let dy = mouse.y - this.y;
                let distance = Math.sqrt(dx * dx + dy * dy);
                if (distance < mouse.radius) {
                    const forceDirectionX = dx / distance;
                    const forceDirectionY = dy / distance;
                    const force = (mouse.radius - distance) / mouse.radius;
                    const directionX = forceDirectionX * force * this.density;
                    const directionY = forceDirectionY * force * this.density;
                    this.x -= directionX;
                    this.y -= directionY;
                }
            }
        }

        function init() {
            if (!canvas) return;
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            particles = [];
            for (let i = 0; i < particleCount; i++) {
                particles.push(new Particle());
            }
        }

        function connect() {
            for (let a = 0; a < particles.length; a++) {
                for (let b = a; b < particles.length; b++) {
                    let dx = particles[a].x - particles[b].x;
                    let dy = particles[a].y - particles[b].y;
                    let distance = Math.sqrt(dx * dx + dy * dy);

                    if (distance < connectionDistance) {
                        let opacity = 1 - (distance / connectionDistance);
                        ctx.strokeStyle = `rgba(0, 242, 255, ${opacity * 0.2})`;
                        ctx.lineWidth = 1;
                        ctx.beginPath();
                        ctx.moveTo(particles[a].x, particles[a].y);
                        ctx.lineTo(particles[b].x, particles[b].y);
                        ctx.stroke();
                    }
                }
            }
        }

        function animate() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.shadowBlur = 0; // Reset shadow for lines
            for (let i = 0; i < particles.length; i++) {
                particles[i].draw();
                particles[i].update();
            }
            connect();
            requestAnimationFrame(animate);
        }

        window.addEventListener('resize', () => {
            init();
        });

        init();
        animate();
    </script>
</body>
</html>


