<?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'] ?? '');
$action = $data['action'] ?? '';
$file = $base_dir . $suffix . '/links.json';

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

$links_data = json_decode(file_get_contents($file), true);

switch ($action) {
    case 'verify':
        $password = $data['password'] ?? '';
        if (password_verify($password, $links_data['password_hash'])) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Incorrect password.']);
        }
        break;

    case 'add':
        $url = filter_var($data['url'] ?? '', FILTER_VALIDATE_URL);
        if (!$url) {
            echo json_encode(['success' => false, 'message' => 'Invalid URL.']);
            exit;
        }
        $links_data['links'][] = ['url' => $url, 'created_at' => time()];
        file_put_contents($file, json_encode($links_data, JSON_PRETTY_PRINT));
        echo json_encode(['success' => true]);
        break;

    case 'edit':
        $index = (int)($data['index'] ?? -1);
        $url = filter_var($data['url'] ?? '', FILTER_VALIDATE_URL);
        if ($index < 0 || $index >= count($links_data['links']) || !$url) {
            echo json_encode(['success' => false, 'message' => 'Invalid input.']);
            exit;
        }
        $links_data['links'][$index]['url'] = $url;
        file_put_contents($file, json_encode($links_data, JSON_PRETTY_PRINT));
        echo json_encode(['success' => true]);
        break;

    case 'delete':
        $index = (int)($data['index'] ?? -1);
        if ($index < 0 || $index >= count($links_data['links'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid index.']);
            exit;
        }
        array_splice($links_data['links'], $index, 1);
        file_put_contents($file, json_encode($links_data, JSON_PRETTY_PRINT));
        echo json_encode(['success' => true]);
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action.']);
}
?>