<?php
// Including Database configuration file.
include "databaseconnect.php";

// Function to sanitize and validate the search term.
function cleanInput($input) {
    // Remove whitespace from the beginning and end of the input.
    $input = trim($input);
    // Sanitize the input to prevent SQL injection and other attacks.
    $input = filter_var($input, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    // Validate the input to ensure it meets the required criteria (optional).
    if (strlen($input) < 2 || strlen($input) > 50) {
        // Invalid input, return an empty string or handle the error accordingly.
        return "";
    }
    // Return the sanitized and validated input.
    return $input;
}

// Getting value of "search" variable from "script.js".
if (isset($_POST['search'])) {
    // Clean and validate the search term.
    $searchTerm = cleanInput($_POST['search']);

    // If the cleaned search term is not empty, proceed with the search.
    if (!empty($searchTerm)) {
        // Search query with prepared statement.
        $query = "SELECT title FROM posts WHERE title LIKE ? LIMIT 10";

        // Prepare the statement.
        $stmt = mysqli_prepare($con, $query);

        if ($stmt) {
            // Bind the parameter and execute the statement.
            mysqli_stmt_bind_param($stmt, "s", $searchPattern);
            $searchPattern = '%' . $searchTerm . '%';
            mysqli_stmt_execute($stmt);

            // Get the result set.
            $result = mysqli_stmt_get_result($stmt);

            // Creating unordered list to display result.
            echo '<br><span>';

            // Fetching result from database.
            while ($row = mysqli_fetch_array($result)) {
                // Generating safe HTML output.
                $title = htmlspecialchars($row['title']);

                // Truncate the title to 20 characters.
                $truncatedTitle = substr($title, 0, 20);

                // Output the result.
                echo '<div class="liveresults1" onclick="location.href=\'/search.php?search=' . urlencode($truncatedTitle) . '\'">';
                echo $truncatedTitle . '<span style="font-size: 10px">&#128269;</span><br>';
                echo '</div>';
            }

            // Close the prepared statement.
            mysqli_stmt_close($stmt);
            echo '</span>';
        } else {
            // Handle statement preparation failure.
            echo "Error: " . mysqli_error($con);
        }
    } else {
        // Handle empty or invalid search term.
        echo "Invalid search term.";
    }

    // Close the database connection.
    mysqli_close($con);
}

