<?php
function visitorQrColumnExists($conn, $column) {
    $column = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM visitors LIKE '$column'");
    return $res && $res->num_rows > 0;
}

function visitorQrPublicBaseUrl() {
    $https = (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off");
    $scheme = $https ? "https" : "http";
    $host = $_SERVER["HTTP_HOST"] ?? "gramadhikar.com";
    $scriptDir = str_replace("\\", "/", dirname($_SERVER["SCRIPT_NAME"] ?? "/"));
    $base = preg_replace("#/(sub-admin|village-admin|api/visitor)$#", "", $scriptDir);
    return rtrim($scheme . "://" . $host . $base, "/");
}

function visitorQrEnsureToken($conn, $visitorId) {
    if (!visitorQrColumnExists($conn, "qr_token")) {
        return "";
    }

    $visitorId = intval($visitorId);
    $res = $conn->query("SELECT qr_token FROM visitors WHERE id='$visitorId' LIMIT 1");
    $row = $res ? $res->fetch_assoc() : null;

    if (!empty($row["qr_token"])) {
        return $row["qr_token"];
    }

    do {
        $token = bin2hex(random_bytes(24));
        $safeToken = $conn->real_escape_string($token);
        $exists = $conn->query("SELECT id FROM visitors WHERE qr_token='$safeToken' LIMIT 1");
    } while ($exists && $exists->num_rows > 0);

    $conn->query("UPDATE visitors SET qr_token='$safeToken' WHERE id='$visitorId' LIMIT 1");
    return $token;
}

function visitorQrScanUrl($token) {
    return visitorQrPublicBaseUrl() . "/scan-visitor.php?t=" . urlencode($token);
}

function visitorQrImageUrl($token, $size = 360) {
    $scanUrl = visitorQrScanUrl($token);
    return "https://api.qrserver.com/v1/create-qr-code/?size=" . intval($size) . "x" . intval($size) . "&data=" . urlencode($scanUrl);
}

function visitorQrWhatsappShareUrl($mobile, $visitorName, $token) {
    $digits = preg_replace("/\D/", "", (string) $mobile);
    if (strlen($digits) === 10) {
        $digits = "91" . $digits;
    }

    $scanUrl = visitorQrScanUrl($token);
    $qrUrl = visitorQrImageUrl($token, 360);
    $message = "Gram Rakshak visitor QR for " . $visitorName . "\n\nScan link: " . $scanUrl . "\nQR image: " . $qrUrl;

    return "https://wa.me/" . $digits . "?text=" . urlencode($message);
}
