<?php
session_start();
$base_dir = 'linkspaces/';
if (!file_exists($base_dir)) {
    mkdir($base_dir, 0777, true);
}

// Get query parameters
$query = $_GET;

// Check for 1-10 character suffix in query
$suffix = null;
foreach ($query as $key => $value) {
    if (preg_match('/^[a-zA-Z0-9]{1,10}$/', $key)) {
        $suffix = $key;
        break;
    }
}

if ($suffix) {
    $file = $base_dir . $suffix . '/links.json';
    
    if (file_exists($file)) {
        ob_start();
        header("Location: space.php?suffix=$suffix");
        ob_end_flush();
        exit;
    } else {
        header('HTTP/1.0 404 Not Found');
        die('Link space not found.');
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LinkGram</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <main class="container mx-auto p-4">
        <h1 class="text-3xl font-bold mb-4 text-center">Welcome to LinkGram</h1>
        <p class="text-center mb-6">Create your own link space to share and manage links.</p>
        <div class="flex justify-center">
            <button onclick="createLinkSpace()" class="px-4 py-2">Create Link Space</button>
        </div>
    </main>
    <footer>
        <p>
            LinkGram by <a href="https://amfile.org" target="_blank">Amfile.org</a>,
            a <a href="https://pagetelegram.com" target="_blank">PageTelegram.com</a> production,
            Copyright 2025 | A better world in the making, one site at a time.
        </p>
    </footer>
    <script>
        function createLinkSpace() {
            const suffix = prompt("Enter a suffix (1-10 alphanumeric characters):");
            if (suffix && /^[a-zA-Z0-9]{1,10}$/.test(suffix)) {
                const password = prompt("Create a password for managing this link space:");
                if (password) {
                    fetch('create_space.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ suffix, password })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            window.location.href = `?${suffix}`;
                        } else {
                            alert(data.message);
                        }
                    })
                    .catch(error => alert('Error creating link space: ' + error));
                } else {
                    alert('Password is required.');
                }
            } else {
                alert('Suffix must be 1-10 alphanumeric characters.');
            }
        }
    </script>
</body>
</html>
