<?php
// notes_save.php
// Save anonymous Bible study notes to server

header('Content-Type: application/json');

$notesDir = __DIR__ . '/notes/';
if (!is_dir($notesDir)) {
    mkdir($notesDir, 0755, true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content = isset($_POST['content']) ? trim($_POST['content']) : '';

    if (empty($content)) {
        echo json_encode(['success' => false, 'error' => 'Note content is empty']);
        exit;
    }

    // Generate unique ID using timestamp and random string
    $noteId = time() . '_' . bin2hex(random_bytes(8));
    $noteFile = $notesDir . $noteId . '.txt';

    // Save note content
    if (file_put_contents($noteFile, $content) !== false) {
        // Create metadata file
        $metadata = [
            'id' => $noteId,
            'created' => time(),
            'ip' => getVisitorIP(),
            'lines' => substr_count($content, "\n") + 1,
            'size' => strlen($content)
        ];
        file_put_contents($notesDir . $noteId . '.meta', json_encode($metadata));

        // Return success with link to view note
        $viewUrl = 'notes_view.php?id=' . $noteId;
        echo json_encode([
            'success' => true,
            'noteId' => $noteId,
            'viewUrl' => $viewUrl
        ]);
    } else {
        echo json_encode(['success' => false, 'error' => 'Failed to save note']);
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}

function getVisitorIP() {
    $ipKeys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED',
               'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
    foreach ($ipKeys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }
    return 'unknown';
}
?>
