<?php
session_start();
include 'db.php';

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Check if the user is logged in
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(["status" => "error", "message" => "User not logged in"]);
        exit();
    }

    $userId = $_SESSION['user_id']; // Get the logged-in user ID
    $elementName = $_POST['name'];

    // Insert the element into the saved_elements table with user ID
    $sql = "INSERT INTO saved_elements (name, users_id) VALUES (?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $elementName, $userId);

    if ($stmt->execute()) {
        echo json_encode(["status" => "success", "message" => "Element saved successfully!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to save element."]);
    }

    $stmt->close();
    $conn->close();
} else {
    echo json_encode(["status" => "error", "message" => "Invalid request method."]);
}
?>
