<?php

// Establish database connection
$conn = mysqli_connect("localhost", "dzvisual_admin", "Farhan@123456", "dzvisual_homestay");

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Check if code parameter is present in the URL
if (isset($_GET['code'])) {
    // Sanitize input to prevent SQL injection
    $code = mysqli_real_escape_string($conn, $_GET['code']);

    // Prepare SQL statement
    $sql = "SELECT * FROM wifi_redirections WHERE code = '$code'";

    // Execute SQL query
    $result = mysqli_query($conn, $sql);

    // Check if query was successful
    if ($result) {
        // If a matching record is found, fetch and output it
        if (mysqli_num_rows($result) > 0) {
            $row = mysqli_fetch_assoc($result);
            $url = $row["url"];
            $tgChatId = $row["tg_chat_id"];
            $room = $row["room"];

            // Telegram Alert
            sendMessage("Guest $room scanned WiFi",$tgChatId);
            
            // Redirect to the URL
            echo "Redirecting...";
            header("Location: $url");
            
            exit();
        } else {
            // If no matching record is found, display an error message
            echo "Code not found";
        }
    } else {
        // Handle SQL query error
        echo "Error: " . mysqli_error($conn);
    }

    // Free result set
    mysqli_free_result($result);
}

// Close database connection
mysqli_close($conn);

function sendMessage($messaggio,$chatID = 26236173){
	$token = "1206454586:AAHP37-65ffVZdTJr6zGZj11MBtz3WcytbM";

	$url = "https://api.telegram.org/bot" . $token . "/sendMessage?chat_id=" . $chatID;
	$url = $url . "&text=" . urlencode($messaggio);
	file_get_contents($url);
}

?>
