<?php
// Include the database connection
include '../databaseconnect.php';

// Check if ID and action are sent
if (isset($_POST['id']) && is_numeric($_POST['id']) && isset($_POST['action'])) {
    
    $ringtoneId = (int)$_POST['id'];
    $action = $_POST['action'];

    // Determine which column to update based on the action
    if ($action === 'like') {
        $column_to_update = 'likes';
    } elseif ($action === 'dislike') {
        $column_to_update = 'dislikes';
    } else {
        // Invalid action
        http_response_code(400);
        echo "Invalid action.";
        exit;
    }

    // Prepare a secure SQL statement to prevent SQL injection
    // The column name is validated above, so it's safe to use in the query string
    $sql = "UPDATE posts SET $column_to_update = $column_to_update + 1 WHERE No = ?";
    
    $stmt = $con->prepare($sql);
    
    if ($stmt) {
        $stmt->bind_param("i", $ringtoneId);
        
        if ($stmt->execute()) {
            http_response_code(200);
            echo "Reaction recorded.";
        } else {
            http_response_code(500);
            echo "Error executing statement: " . $stmt->error;
        }
        
        $stmt->close();
    } else {
        http_response_code(500);
        echo "Error preparing statement: " . $con->error;
    }

    $con->close();

} else {
    // Bad request if parameters are missing
    http_response_code(400);
    echo "Invalid request.";
}
?>