<?php
// Include the database connection file
require_once 'connection.php';

// Function to sanitize input data
function sanitize($conn, $data) {
    return mysqli_real_escape_string($conn, trim($data));
}


// Check if POST data is set
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['image']) && isset($_POST['fcm'])) {
    // Prepare data for insertion (sanitize inputs)
    $name = sanitize($conn, $_POST['name']);
    $email = sanitize($conn, $_POST['email']);
    $image = sanitize($conn, $_POST['image']);
    $fcm = sanitize($conn, $_POST['fcm']);

    // Check if the email already exists
    $check_query = "SELECT * FROM user WHERE email = '$email'";
    $result = $conn->query($check_query);

    if ($result->num_rows > 0) {
        // User with this email already exists
        $response = array(
            "status" => "error",
            "message" => "User with this email already exists"
        );
    } else {
        // Insert the new user
        $sql = "INSERT INTO user (name, email, image, fcm) VALUES ('$name', '$email', '$image', '$fcm')";

        if ($conn->query($sql) === TRUE) {
            // Success message
            $response = array(
                "status" => "success",
                "message" => "User inserted successfully"
            );
        } else {
            // Error message
            $response = array(
                "status" => "error",
                "message" => "Error: " . $sql . "<br>" . $conn->error
            );
        }
    }
} else {
    // In case of missing parameters
    $response = array(
        "status" => "error",
        "message" => "Missing required parameters"
    );
}

header('Content-Type: application/json');
echo json_encode($response);

$conn->close();
?>
