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

// Check if the request method is POST and required fields are set
if ($_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['email']) &&
    isset($_POST['name'])) {

    // Sanitize inputs
    $email = $_POST['email'];
    $name = $_POST['name'];

    // Escape inputs to prevent SQL injection
    $email = $conn->real_escape_string($email);
    $name = $conn->real_escape_string($name);

    // Check if the user exists in the database based on email
    $check_sql = "SELECT * FROM user WHERE email = '$email'";
    $check_result = $conn->query($check_sql);

    if ($check_result->num_rows > 0) {
        // User exists, update their name
        $update_sql = "UPDATE user SET name = '$name' WHERE email = '$email'";

        if ($conn->query($update_sql) === TRUE) {
            // Update successful
            $response = array(
                "status" => "success",
                "message" => "Name updated successfully"
            );
        } else {
            // Update failed
            $response = array(
                "status" => "error",
                "message" => "Failed to update name: " . $conn->error
            );
        }
    } else {
        // User does not exist
        $response = array(
            "status" => "error",
            "message" => "User with email '$email' does not exist"
        );
    }
} else {
    // Missing required fields
    $response = array(
        "status" => "error",
        "message" => "Missing required fields"
    );
}

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

// Close database connection
$conn->close();
?>
