<?php
header('Content-Type: application/json');
$base_dir = 'linkspaces/';
$data = json_decode(file_get_contents('php://input'), true);
$suffix = preg_replace('/[^a-zA-Z0-9]/', '', $data['suffix'] ?? '');
$password = $data['password'] ?? '';

if (strlen($suffix) < 1 || strlen($suffix) > 10) {
    echo json_encode(['success' => false, 'message' => 'Suffix must be 1-10 alphanumeric characters.']);
    exit;
}

$space_dir = $base_dir . $suffix;
$file = $space_dir . '/links.json';

if (file_exists($file)) {
    echo json_encode(['success' => false, 'message' => 'Link space already exists.']);
    exit;
}

if (!file_exists($space_dir)) {
    mkdir($space_dir, 0777, true);
}

$links = [
    'password_hash' => password_hash($password, PASSWORD_DEFAULT),
    'links' => []
];

file_put_contents($file, json_encode($links, JSON_PRETTY_PRINT));
echo json_encode(['success' => true, 'redirect' => "?$suffix"]);
?>
