<?php
session_start();
include 'db.php';

// --- CHECK LOGIN STATUS ---
if (isset($_SESSION['user_id'])) {
    // If already logged in, check role and redirect accordingly
    if (isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'admin') {
        header("Location: admin.php");
    } else {
        header("Location: download.php");
    }
    exit();
}

$message = "";
$messageType = "";

// --- HANDLE FORM SUBMISSION ---
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // 1. REGISTRATION LOGIC
    if (isset($_POST['action']) && $_POST['action'] == 'register') {
        $name = $conn->real_escape_string($_POST['name']);
        $email = $conn->real_escape_string($_POST['email']);
        $password = $_POST['password'];

        // Check if email exists
        $check_sql = "SELECT id FROM users WHERE email='$email'";
        $check_result = $conn->query($check_sql);

        if ($check_result->num_rows > 0) {
            $message = "Account already exists! Please Sign In.";
            $messageType = "danger";
        } else {
            // Hash password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            // Insert new user (Role defaults to 'user' in DB)
            $sql = "INSERT INTO users (name, email, password) VALUES ('$name', '$email', '$hashed_password')";

            if ($conn->query($sql) === TRUE) {
                $message = "Success! Please Sign In.";
                $messageType = "success";
            } else {
                $message = "Error: " . $conn->error;
                $messageType = "danger";
            }
        }
    }

    // 2. LOGIN LOGIC
    if (isset($_POST['action']) && $_POST['action'] == 'login') {
        $email = $conn->real_escape_string($_POST['email']);
        $password = $_POST['password'];

        $result = $conn->query("SELECT * FROM users WHERE email='$email'");

        if ($result->num_rows == 1) {
            $user = $result->fetch_assoc();
            // Verify Password
            if (password_verify($password, $user['password'])) {
                // Set Session Variables
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user_role'] = $user['role']; // Save role for admin check

                // REDIRECT BASED ON ROLE
                if ($user['role'] == 'admin') {
                    header("Location: admin.php");
                } else {
                    header("Location: download.php");
                }
                exit();
            } else {
                $message = "Incorrect Password!";
                $messageType = "danger";
            }
        } else {
            $message = "User not found.";
            $messageType = "danger";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cosmic Access</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

    <style>
        :root {
            --primary-glow: #00d4ff;
            --secondary-glow: #bd00ff;
        }

        body {
            background: #020205;
            height: 100vh;
            margin: 0;
            overflow: hidden;
            font-family: 'Segoe UI', sans-serif;
        }

        .main-container {
            height: 100vh;
        }

        .left-panel {
            position: relative;
            overflow: hidden;
            background: radial-gradient(circle at center, #111, #000);
        }

        .right-panel {
            display: flex;
            justify-content: center;
            align-items: center;
            background: #050505;
            position: relative;
            z-index: 5;
        }

        /* --- 1. SOLAR SYSTEM (Left Panel) --- */
        .solar-system {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 100%;
            height: 100%;
            z-index: 2;
            pointer-events: none;
            opacity: 0;
            animation: fadeInSystem 2s ease-out 2.5s forwards;
        }

        .sun {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 80px;
            height: 80px;
            background: radial-gradient(circle at 30% 30%, #ffd700, #ff8c00, #ff4500);
            border-radius: 50%;
            box-shadow: 0 0 60px #ff8c00;
            z-index: 10;
        }

        .orbit {
            position: absolute;
            top: 50%;
            left: 50%;
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            transform: translate(-50%, -50%);
            animation: rotateOrbit linear infinite;
        }

        .planet {
            position: absolute;
            top: 50%;
            left: 100%;
            border-radius: 50%;
            transform: translate(-50%, -50%);
            z-index: 11;
        }

        .orbit-1 {
            width: 20vmin;
            height: 20vmin;
            animation-duration: 8s;
        }

        .planet-1 {
            width: 10px;
            height: 10px;
            background: #aaa;
        }

        .orbit-2 {
            width: 35vmin;
            height: 35vmin;
            animation-duration: 12s;
        }

        .planet-2 {
            width: 14px;
            height: 14px;
            background: #e3bb76;
        }

        .orbit-3 {
            width: 55vmin;
            height: 55vmin;
            animation-duration: 20s;
        }

        .planet-3 {
            width: 18px;
            height: 18px;
            background: #2f6a69;
            box-shadow: 0 0 10px cyan;
        }

        @keyframes rotateOrbit {
            to {
                transform: translate(-50%, -50%) rotate(360deg);
            }
        }

        @keyframes fadeInSystem {
            to {
                opacity: 1;
            }
        }

        /* --- 2. WARP SPEED CANVAS (Left Panel) --- */
        #warpCanvas {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1;
            /* Behind Solar System */
            opacity: 0;
            animation: fadeInSystem 2s ease-out 2.5s forwards;
        }

        /* --- 3. BLOOM EXPLOSION (Covers All) --- */
        .bloom-container {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 100;
            pointer-events: none;
            display: flex;
            justify-content: center;
            align-items: center;
            animation: hideBloom 0.1s linear 2.8s forwards;
        }

        .star-bloom {
            width: 0;
            height: 0;
            border-radius: 50%;
            background: radial-gradient(circle, #ffffff 0%, #00d4ff 30%, #bd00ff 60%, transparent 100%);
            animation: superNova 2.5s cubic-bezier(0.1, 0.8, 0.2, 1) forwards;
        }

        @keyframes superNova {
            0% {
                width: 0;
                height: 0;
                opacity: 1;
                box-shadow: 0 0 50px white;
            }

            30% {
                width: 150px;
                height: 150px;
                opacity: 1;
                box-shadow: 0 0 150px #00d4ff, 0 0 300px #bd00ff;
            }

            100% {
                width: 250vmax;
                height: 250vmax;
                opacity: 0;
            }
        }

        @keyframes hideBloom {
            to {
                display: none;
            }
        }

        /* --- 4. GLASS FORM (Right Panel) --- */
        .auth-card {
            width: 90%;
            max-width: 420px;
            background: rgba(255, 255, 255, 0.03);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            padding: 40px;
            color: white;
            box-shadow: 0 30px 60px rgba(0, 0, 0, 0.8);
            opacity: 0;
            transform: translateY(30px) scale(0.95);
            animation: revealForm 1.2s cubic-bezier(0.2, 0.8, 0.2, 1) 2s forwards;
        }

        @keyframes revealForm {
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .form-title {
            font-weight: 800;
            letter-spacing: 3px;
            text-transform: uppercase;
            margin-bottom: 10px;
            background: linear-gradient(to right, #fff, var(--primary-glow));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .form-control {
            background: rgba(0, 0, 0, 0.5);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: white;
            padding: 12px;
        }

        .form-control:focus {
            background: rgba(0, 0, 0, 0.7);
            border-color: var(--primary-glow);
            box-shadow: 0 0 15px rgba(0, 212, 255, 0.3);
            color: white;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary-glow), #005bea);
            border: none;
            padding: 12px;
            font-weight: 700;
            letter-spacing: 2px;
            box-shadow: 0 10px 30px rgba(0, 212, 255, 0.3);
        }

        .btn-primary:hover {
            transform: translateY(-3px);
            box-shadow: 0 20px 40px rgba(0, 212, 255, 0.5);
        }

        .toggle-link {
            color: var(--primary-glow);
            cursor: pointer;
            text-decoration: none;
            font-weight: bold;
        }

        .hidden {
            display: none;
        }

        .alert {
            background: rgba(255, 255, 255, 0.05);
            border: none;
            color: white;
        }
    </style>
</head>

<body>

    <div class="bloom-container">
        <div class="star-bloom"></div>
    </div>

    <div class="container-fluid main-container">
        <div class="row h-100">

            <div class="col-lg-7 p-0 left-panel">
                <canvas id="warpCanvas"></canvas>

                <div class="solar-system">
                    <div class="sun"></div>
                    <div class="orbit orbit-1">
                        <div class="planet planet-1"></div>
                    </div>
                    <div class="orbit orbit-2">
                        <div class="planet planet-2"></div>
                    </div>
                    <div class="orbit orbit-3">
                        <div class="planet planet-3"></div>
                    </div>
                </div>
            </div>

            <div class="col-lg-5 right-panel">
                <div class="auth-card">

                    <?php if ($message != ""): ?>
                        <div class="alert alert-<?php echo $messageType; ?> text-center mb-4" role="alert">
                            <?php echo $message; ?>
                        </div>
                    <?php endif; ?>

                    <div id="login-form">
                        <h3 class="text-center form-title">Command Login</h3>
                        <p class="text-center text-white-50 mb-4 small">Secure Terminal Access</p>
                        <form method="POST">
                            <input type="hidden" name="action" value="login">
                            <div class="mb-3 input-group">
                                <span class="input-group-text bg-transparent border-secondary text-white-50"><i
                                        class="fas fa-envelope"></i></span>
                                <input type="email" name="email" class="form-control" placeholder="Email Address"
                                    required>
                            </div>
                            <div class="mb-4 input-group">
                                <span class="input-group-text bg-transparent border-secondary text-white-50"><i
                                        class="fas fa-lock"></i></span>
                                <input type="password" name="password" class="form-control" placeholder="Access Code"
                                    required>
                            </div>
                            <button type="submit" class="btn btn-primary w-100 mb-3">INITIALIZE</button>
                        </form>
                        <p class="text-center text-white-50 mt-3 small">New Personnel? <span class="toggle-link"
                                onclick="toggleForms()">Register ID</span></p>
                    </div>

                    <div id="register-form" class="hidden">
                        <h3 class="text-center form-title">New Registration</h3>
                        <p class="text-center text-white-50 mb-4 small">Create Personnel ID</p>
                        <form method="POST">
                            <input type="hidden" name="action" value="register">
                            <div class="mb-3 input-group">
                                <span class="input-group-text bg-transparent border-secondary text-white-50"><i
                                        class="fas fa-user"></i></span>
                                <input type="text" name="name" class="form-control" placeholder="Full Name" required>
                            </div>
                            <div class="mb-3 input-group">
                                <span class="input-group-text bg-transparent border-secondary text-white-50"><i
                                        class="fas fa-envelope"></i></span>
                                <input type="email" name="email" class="form-control" placeholder="Email Address"
                                    required>
                            </div>
                            <div class="mb-4 input-group">
                                <span class="input-group-text bg-transparent border-secondary text-white-50"><i
                                        class="fas fa-key"></i></span>
                                <input type="password" name="password" class="form-control"
                                    placeholder="Create Password" required>
                            </div>
                            <button type="submit" class="btn btn-primary w-100 mb-3">REGISTER</button>
                        </form>
                        <p class="text-center text-white-50 mt-3 small">Active ID? <span class="toggle-link"
                                onclick="toggleForms()">Return to Login</span></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function toggleForms() {
            var loginForm = document.getElementById('login-form');
            var registerForm = document.getElementById('register-form');
            loginForm.style.opacity = '0'; registerForm.style.opacity = '0';
            setTimeout(() => {
                if (loginForm.classList.contains('hidden')) {
                    loginForm.classList.remove('hidden'); registerForm.classList.add('hidden'); loginForm.style.opacity = '1';
                } else {
                    loginForm.classList.add('hidden'); registerForm.classList.remove('hidden'); registerForm.style.opacity = '1';
                }
            }, 200);
        }
        document.getElementById('login-form').style.transition = "opacity 0.2s";
        document.getElementById('register-form').style.transition = "opacity 0.2s";

        // --- WARP SPEED JS ENGINE ---
        const canvas = document.getElementById('warpCanvas');
        const ctx = canvas.getContext('2d');
        let w, h;
        const stars = [];
        const numStars = 400; // Number of warp stars
        const speed = 0.1; // Base speed

        function resize() {
            w = canvas.width = canvas.parentElement.offsetWidth;
            h = canvas.height = canvas.parentElement.offsetHeight;
        }

        class Star {
            constructor() {
                this.x = Math.random() * w - w / 2;
                this.y = Math.random() * h - h / 2;
                this.z = Math.random() * w; // Depth
                this.size = Math.random() * 3 + 1; // Large base size
            }
            update() {
                this.z -= speed * 50; // Move closer fast
                if (this.z <= 0) {
                    this.z = w;
                    this.x = Math.random() * w - w / 2;
                    this.y = Math.random() * h - h / 2;
                }
            }
            draw() {
                // Perspective projection
                let x = (this.x / this.z) * w + w / 2;
                let y = (this.y / this.z) * h + h / 2;
                // Size increases as it gets closer
                let r = (this.size * (w / this.z)) * 0.5;

                ctx.beginPath();
                ctx.fillStyle = "rgba(255, 255, 255, " + (1 - this.z / w) + ")";
                ctx.arc(x, y, r, 0, Math.PI * 2);
                ctx.fill();
            }
        }

        function initWarp() {
            resize();
            for (let i = 0; i < numStars; i++) stars.push(new Star());
            animateWarp();
        }

        function animateWarp() {
            ctx.fillStyle = 'rgba(0,0,0,0.3)'; // Trails
            ctx.fillRect(0, 0, w, h);
            stars.forEach(star => { star.update(); star.draw(); });
            requestAnimationFrame(animateWarp);
        }

        window.addEventListener('resize', resize);
        // Start warp animation after bloom
        setTimeout(initWarp, 2000); 
    </script>

</body>

</html>