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

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the input data
    $userEmail = $_POST['userEmail'] ?? null; // User's email
    $status = $_POST['status'] ?? null; // Status (true or false)

    // Validate input
    if (filter_var($userEmail, FILTER_VALIDATE_EMAIL) && is_numeric($status)) {
        // Check if the record already exists
        $checkStmt = $conn->prepare("SELECT statusId FROM `userstatus` WHERE userEmail = ?");
        $checkStmt->bind_param("s", $userEmail);
        $checkStmt->execute();
        $result = $checkStmt->get_result();

        if ($result->num_rows > 0) {
            // If record exists, update the status
            $updateStmt = $conn->prepare("UPDATE `userstatus` SET `status` = ? WHERE `userEmail` = ?");
            $updateStmt->bind_param("is", $status, $userEmail);
            if ($updateStmt->execute()) {
                echo json_encode(["message" => "Status updated successfully."]);
            } else {
                echo json_encode(["error" => "Failed to update status."]);
            }
            $updateStmt->close();
        } else {
            // If record does not exist, insert a new one
            $insertStmt = $conn->prepare("INSERT INTO `userstatus` (`userEmail`, `status`) VALUES (?, ?)");
            $insertStmt->bind_param("si", $userEmail, $status);
            if ($insertStmt->execute()) {
                echo json_encode(["message" => "Status inserted successfully.", "statusId" => $insertStmt->insert_id]);
            } else {
                echo json_encode(["error" => "Failed to insert status."]);
            }
            $insertStmt->close();
        }

        // Close the check statement
        $checkStmt->close();
    } else {
        // Respond with a validation error message
        echo json_encode(["error" => "Invalid input data."]);
    }
} else {
    // Respond with an error if not a POST request
    echo json_encode(["error" => "Invalid request method. Use POST."]);
}

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