<?php
require 'config.php'; // Database configuration

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $name = $_POST['name'] ?? '';
        $email = $_POST['email'] ?? '';
        $memory = $_POST['memory'] ?? '';
        $connection = $_POST['connection'] ?? '';

        // Kontrollige, kas kõik vajalikud andmed on esitatud
        if (empty($name) || empty($email) || empty($memory) || empty($connection)) {
            throw new Exception('Kõik väljad on kohustuslikud.');
        }

        // Kontrolli e-posti aadressi formaati
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception('Palun sisesta korrektne e-posti aadress.');
        }

        // Salvestage mälestus andmebaasi
        $stmt = $db->prepare("INSERT INTO memories (name, email, memory, connection) VALUES (:name, :email, :memory, :connection)");
        $stmt->execute([
            ':name' => htmlspecialchars($name),
            ':email' => htmlspecialchars($email),
            ':memory' => htmlspecialchars($memory),
            ':connection' => htmlspecialchars($connection)
        ]);

        // Tagastage edukas vastus
        echo json_encode([
            'success' => true,
            'message' => 'Mälestus edukalt salvestatud.',
            'name' => htmlspecialchars($name),
            'memory' => htmlspecialchars($memory),
            'connection' => htmlspecialchars($connection)
        ]);
    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Ainult POST päringud on lubatud.']);
}
?>
