<?php
session_start();
header("Content-Type: application/json");
include 'db.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['user_id'])) {
    echo json_encode(["status" => "error", "message" => "User not logged in"]);
    exit();
}

if (!isset($_POST['name'])) {
    echo json_encode(["status" => "error", "message" => "No element name provided"]);
    exit();
}

$userId = $_SESSION['user_id'];
$name = $_POST['name'];

// Check if already saved
$check = $conn->prepare("SELECT 1 FROM saved_elements WHERE name = ? AND users_id = ?");
$check->bind_param("si", $name, $userId);
$check->execute();
$check->store_result();

if ($check->num_rows > 0) {
    echo json_encode(["status" => "exists"]);
    $check->close();
    exit();
}

$check->close();

// Save element
$save = $conn->prepare("INSERT INTO saved_elements (name, users_id) VALUES (?, ?)");
$save->bind_param("si", $name, $userId);

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

$save->close();
$conn->close();
?>
