<?php
// Include the database connection file
// The path is ../ because this file is inside /ringtones-bgm/
include '../databaseconnect.php';

// Check if the 'id' is sent via POST and is a number
if (isset($_POST['id']) && is_numeric($_POST['id'])) {
    
    // Sanitize the input by casting to an integer to prevent SQL injection
    $ringtoneId = (int)$_POST['id'];

    // Prepare the SQL statement to update the download count
    // Using `download_count = download_count + 1` is an atomic operation,
    // which is safer and more efficient than selecting the count first.
    $sql = "UPDATE posts SET download_count = download_count + 1 WHERE No = ?";
    
    // Prepare the statement
    $stmt = $con->prepare($sql);
    
    if ($stmt) {
        // Bind the integer parameter
        $stmt->bind_param("i", $ringtoneId);
        
        // Execute the statement
        if ($stmt->execute()) {
            // Success
            http_response_code(200);
            echo "Download count updated.";
        } else {
            // Execution failed
            http_response_code(500);
            echo "Error updating record: " . $stmt->error;
        }
        
        // Close the statement
        $stmt->close();
    } else {
        // Preparation failed
        http_response_code(500);
        echo "Error preparing statement: " . $con->error;
    }

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

} else {
    // If 'id' is not provided or invalid
    http_response_code(400); // Bad Request
    echo "Invalid request: Ringtone ID not provided.";
}
?>