<?php
// Database configuration
$servername = "localhost"; 
$username = "root";  // Default MySQL username in XAMPP
$password = "";  // Default MySQL password in XAMPP (leave empty)
$dbname = "sureshadmin";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Debug: Check if connected successfully
// echo "Connected successfully";

// Function to filter data
if (!function_exists('filteration')) { // Prevent function redeclaration
    function filteration($data)
    {
        foreach ($data as $key => $value) {
            $data[$key] = trim($value);
            $data[$key] = stripslashes($value);
            $data[$key] = htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); // Secure encoding
            $data[$key] = strip_tags($value);
        }
        return $data;
    }
}

// Function to execute select queries
if (!function_exists('select')) { // Prevent function redeclaration
    function select($sql, $values, $datatypes)
    {
        $con = $GLOBALS['conn'];

        // Debug: Check database connection
        if (!$con || !$con->ping()) {
            die("Database connection is not available.");
        }

        // Debug: Check if SQL query is correctly passed
        error_log("Executing Query: " . $sql);

        if ($stmt = mysqli_prepare($con, $sql)) {
            mysqli_stmt_bind_param($stmt, $datatypes, ...$values);

            if (mysqli_stmt_execute($stmt)) {
                $res = mysqli_stmt_get_result($stmt);
                mysqli_stmt_close($stmt);
                return $res;
            } else {
                error_log("Query execution failed: " . mysqli_stmt_error($stmt));
                mysqli_stmt_close($stmt);
                die("Query execution failed: " . mysqli_stmt_error($stmt));
            }
        } else {
            error_log("Statement preparation failed: " . mysqli_error($con));
            die("Query preparation failed: " . mysqli_error($con));
        }
    }
}

// Debug: Check if functions are loaded
// echo "Functions loaded successfully.";
?>
