<?php
// Set the content type to JSON
header('Content-Type: application/json');

// Define the file path to save the pages
$pagesFilePath = __DIR__ . '/../database/pages.json';

// Read the raw JSON input
$rawInput = file_get_contents('php://input');

// Decode it as an array
$pages = json_decode($rawInput, true);

// Validate that we received an array
if (!is_array($pages)) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid input format. Expected JSON array.'
    ]);
    exit;
}

// Optional: Remove empty strings and trim page names
$pages = array_filter(array_map('trim', $pages), function($page) {
    return $page !== '';
});

// Save the cleaned array to the file
if (file_put_contents($pagesFilePath, json_encode(array_values($pages), JSON_PRETTY_PRINT))) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save pages to file.'
    ]);
}
?>
