<?php include("db.php"); ?>
<?php include 'backend/core/unavailableBrands.php'; ?>

<!DOCTYPE html><html>
<?php 

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);


$url_id = '';
$url = '';
$ip = '';
$city = '';
$state = '';
$country = '';
$visits = 0;

//$code = isset($_GET['code']) ? $_GET['code'] : null;




// Get the full request URI, e.g., "/swiggy?source=test"
$requestUri = $_SERVER['REQUEST_URI'];

// Parse the URL to separate path and query components
$parsedUrl = parse_url($requestUri);

// Extract the route parameter from the path
$path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
$code = strtolower(trim($path, '/')); // "swiggy"

// Extract the 'source' query parameter
$source = isset($_GET['source']) ? $_GET['source'] : 'Primary';




$og_source = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'NA';

function mapRefererToEvent(string $referer): string
{
    if ($referer === 'NA') {
        return 'Unavailable';
    }

    $urlParts = parse_url($referer);
    $scheme   = $urlParts['scheme']   ?? '';
    $host     = $urlParts['host']     ?? '';

    // android-app scheme for LinkedIn
    if ($scheme === 'android-app' && strpos($referer, 'com.linkedin.android') !== false) {
        return 'LinkedIn';
    }

    switch ($host) {
        case 'm.facebook.com':
        case 'l.facebook.com':
        case 'lm.facebook.com':
            return 'Facebook';
        case 'l.instagram.com':
            return 'Instagram';
        case 't.co':
            return 'X (Twitter)';
        case 'www.linkedin.com':
            return 'LinkedIn';
        case '360qr.in':
            return '360qr.in';
        default:
            return 'Other';
    }
}

$og_source_filtered = mapRefererToEvent($og_source);




$userAgent = $_SERVER['HTTP_USER_AGENT'];
$isBot = preg_match('/facebookexternalhit|twitterbot|linkedinbot|whatsapp|slackbot|discordbot|TelegramBot|SkypeUriPreview/i', $userAgent);

$appName = "Get-Our.APP | Simplify App Download with Just One QR Code ";
$appLogo = "https://get-our.app/assets/custom/images/ogImage.jpg";
$mimeType = "image/png";
$appDescription = "No need for multiple QRs or links for each app store. With just one Get-Our.App QR code, your app can be accessed across all  app stores seamlessly.";

if ($code && !in_array(strtolower($code), array_map('strtolower', $unAvailableBrands))) {

    $sqlurlSEO = "SELECT * FROM url WHERE url = '$code' LIMIT 1";
    $resulturlSEO = $con->query($sqlurlSEO);
    if ($resulturlSEO->num_rows > 0) {                               
    while($rowurlSEO = $resulturlSEO->fetch_assoc()) { 
        
        if($rowurlSEO["appName"] != "") {
            $appName = $rowurlSEO["appName"];
        }

        if($rowurlSEO["logo"] != "") {
            $appLogo = "https://get-our.app/getAppLogo.php/".$code;
        } else if($appName != "") {
            $appLogo = "https://get-our.app/getOurAppQRLogoAutoGenerated.php?code=".$code;
        } else {
            $appLogo = "https://get-our.app/assets/custom/images/ogImage.jpg";
        }
        

        if($rowurlSEO["appDescription"] != "") {
            $appDescription = $rowurlSEO["appDescription"];
        }
        
    } } else { }
    
    echo "<head>
            <title>'$appName'</title>
            <meta charset='UTF-8'>
            <meta name='description' content='" . htmlspecialchars(strip_tags($appDescription, ENT_QUOTES)) . "' />
            <meta property='og:type' content='$appName' />
            <meta property='og:site_name' content='get-our.app' />
            <meta property='og:title' content='" . htmlspecialchars($appName, ENT_QUOTES) . "' />
            <meta property='og:description' content='" . htmlspecialchars(strip_tags($appDescription, ENT_QUOTES)) . "' />
            <meta property='og:image' content='$appLogo' />
            <meta property='og:url' content='https://get-our.app/$code' />
            <meta property='og:locale' content='https://get-our.app/$code' />
            <meta property='og:logo' content='$appLogo' />
            <meta name='twitter:card' content='summary_large_image' />
        </head>";
    

    $url_id = 0;
    $url = "";
    $serialNumber = 0;
    $redirectURLs = [];
    
    $sqlurl = "SELECT * FROM url WHERE url = '$code' LIMIT 1";
    $resulturl = $con->query($sqlurl);
    if ($resulturl->num_rows > 0) {                               
        while($rowurl = $resulturl->fetch_assoc()) { 
            $serialNumber = $rowurl["serial_number"];
            $validityStatus = $rowurl["validityStatus"];
            $validity = $rowurl["validDate"];
            $validity = new DateTime($validity); 
            $status = $rowurl["status"];
            $url_id = $rowurl["id"];
            $userId = $rowurl["u_id"];
            $now = new DateTime();
            
            $directLander = $rowurl["directLander"];
        
            if(($validity > $now)) { 
                $sql = "UPDATE url SET validityStatus = 'Active' WHERE serial_number = '$serialNumber'";
                $con->query($sql);
            }
        
            if(($now > $validity)) { 
                $sql = "UPDATE url SET validityStatus = 'Expired' WHERE serial_number = '$serialNumber'";
                $con->query($sql);
                $url = "expired"; 
            } else if($status == "Pause") { 
                $url = "paused";
            } else { 
                
                $userPlanRedirectionsConsumed = 0;
                $userPlanMonthlyRedirects = 0;
                
                $sqlPlanDetails = "SELECT * FROM userPlans WHERE userId = '$userId' ORDER BY id DESC LIMIT 1";
                $resultPlanDetails = $con->query($sqlPlanDetails);
                if ($resultPlanDetails->num_rows > 0) {                               
                while($rowPlanDetails = $resultPlanDetails->fetch_assoc()) { 
                    $userPlanMonthlyRedirects = $rowPlanDetails["monthlyRedirections"];
                } } else { }
                
                $sqlurl_userPlan = "SELECT * FROM userPlans WHERE userId = '$userId' ORDER BY id DESC LIMIT 1";
                $resulturl_userPlan = $con->query($sqlurl_userPlan);
                if ($resulturl_userPlan->num_rows > 0) {                               
                while($rowurl_userPlan = $resulturl_userPlan->fetch_assoc()) { 
                    $userPlanRedirectionsConsumed = $rowurl_userPlan["monthlyRedirections"];
                    $userPlanLifeTime = $rowurl_userPlan["lifeTime"];
                    $userPlanDate = $rowurl_userPlan["dateTime"];
                    
                    $userPlanRedirections = $rowurl_userPlan["monthlyRedirections"];

                    $userPlanStatus = $rowurl_userPlan["status"];
                    
                    $userPlanValidity = new DateTime($userPlanDate);
                    $userPlanValidity->modify("+{$userPlanLifeTime} days");
                } } else { }
                
                
                if ($now > $userPlanValidity || $userPlanStatus == "Cancelled" || $userPlanStatus == "Halted" || $userPlanStatus == "Paused") { 
                    $url = "expired";
                    
                    $sqlUpdateUserPlansStatus = "UPDATE userPlans set status = '$userPlanStatus' WHERE userId = '$userId' ORDER BY id DESC LIMIT 1";
                    if ($conn->query($sqlUpdateUserPlansStatus) === TRUE) { } else {
                        echo "ERROR" . $sqlUpdateUserPlansStatus . "<br>" . $conn->error;
                    }
                } else {
            
                    if($userPlanRedirectionsConsumed != 0) {
                        
                        $userPlanRedirectionsConsumed = $userPlanRedirectionsConsumed - 1;
                        
                        $sqlUpdateUserPlansRedirects = "UPDATE userPlans set monthlyRedirections = '$userPlanRedirectionsConsumed' WHERE userId = '$userId' ORDER BY id DESC LIMIT 1";
                        if ($conn->query($sqlUpdateUserPlansRedirects) === TRUE) { } else {
                            echo "ERROR" . $sqlUpdateUserPlansRedirects . "<br>" . $conn->error;
                        }
                        
                        $sqlurlFields = "SELECT * FROM urlfields WHERE serial_number = '$serialNumber'";
                        $resulturlFields = $con->query($sqlurlFields);
                        if ($resulturlFields->num_rows > 0) {                               
                            while($rowurlFields = $resulturlFields->fetch_assoc()) { 
                                $redirectURLs[] = [
                                    "name"  => $rowurlFields["name"],
                                    "value" => $rowurlFields["value"]
                                ];
                            } 
                        }
                        $url = $redirectURLs;
                        
                    } else {
                        
                        $url = "expired";
                    }
                    
                }

            }
        }
    } else { 
        $sqlurl_deleted = "SELECT * FROM url_deleted WHERE id = '$url_id'";
        $resulturl_deleted = $con->query($sqlurl_deleted);
        if ($resulturl_deleted->num_rows > 0) {                               
            while($rowurl_deleted = $resulturl_deleted->fetch_assoc()) { 
                $url = "deleted";
            } 
        } else { 
            $url = "neverexisted";   
        }
    }
    
    $sqlurlBrand = "SELECT * FROM brandNames WHERE name = '$code' AND (status != 'Active' AND status != 'Pending')";
    $resulturlBrand = $con->query($sqlurlBrand);
    if ($resulturlBrand->num_rows > 0) {                               
    while($rowurlBrand = $resulturlBrand->fetch_assoc()) { 
        $url = "expired";
    } } else { }
    
    // Function to get the client's IP address
    function get_client_ip() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            return $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            return $_SERVER['REMOTE_ADDR'];
        }
    }
    
    $ip = get_client_ip();
    
    // Get location data using ipinfo.io API
    $locationData = @file_get_contents("http://ipinfo.io/{$ip}/json");
    if ($locationData) {
        $locationData = json_decode($locationData);
        $city = $locationData->city ?? 'N/A';
        $state = $locationData->region ?? 'N/A';
        $country = $locationData->country ?? 'N/A';
        $countryFullName = $country !== 'N/A'
            ? Locale::getDisplayRegion('-' . $country, 'en')
            : 'N/A';
    }
?>

<body style="margin: 0;">
    
    <div style="width: 100%;
                height: 100vh;
                background: black;
                display: grid;
                justify-content: center;
                align-items: center;">
        <img src="assets/custom/images/loader.gif" alt="" style="width: 400px;" />
    </div>
    
<script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.6/platform.min.js"></script>
    
<script>
// For debugging status messages
function statUpdate(stat) {
    $(".statusNote").html(stat);
    console.log(stat);
}

// If the URL already has "redirected=1", skip redirection logic.
if (window.location.search.indexOf("redirected=1") !== -1) {
    console.log("Already redirected. Halting further redirection logic.");
} else {

    let latitude = '';
    let longitude = '';
    let deviceLanguage = navigator.language || (navigator.languages ? navigator.languages[0] : 'en');
    let hasRedirected = false; // guard to prevent duplicate redirections


    // Device detection and details
    let browserName = "Unknown";
    let os = "Unknown OS";
    let osVersion = "Unknown Version";
    let deviceType = "Unknown";
    let deviceModel = "Unknown";

    // Helper: Append a "redirected" flag to target URL and perform the redirection.
    function redirectTo(url) {
        if (url.indexOf('?') !== -1) {
            url += "&redirected=1";
        } else {
            url += "?redirected=1";
        }
        window.location.replace(url);
    }

    // Modified geolocation with fallback timer.
    function getLocation() {
        if (navigator.geolocation) {
            let fallbackTriggered = false;
            // Start a fallback timer (1 second)
            const fallbackTimer = setTimeout(() => {
                fallbackTriggered = true;
                console.log("Fallback timer triggered");
                errorCallback({code: 0, message: "Fallback timeout"});
            }, 1000);
            
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    if (!fallbackTriggered) {
                        clearTimeout(fallbackTimer);
                        successCallback(position);
                    }
                },
                (error) => {
                    if (!fallbackTriggered) {
                        clearTimeout(fallbackTimer);
                        errorCallback(error);
                    }
                },
                {timeout: 5000, maximumAge: 300000} // 5 sec timeout, cache for 5 minutes
            );
        } else {
            redirect();
        }
        statUpdate("level 1");
        statUpdate("level 1.1");
    }
    
    function successCallback(position) {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        redirect();
    }
    
    function errorCallback(error) {
        // Even on error (or permission denied), continue to redirect.
        console.log("Geolocation error/fallback:", error);
        redirect();
    }
    
    
    statUpdate("level 1.2");
    
    statUpdate("level 1.3");
    
    async function fetchDeviceDetailsEnhanced() {
        statUpdate("level 2.5");
        
        const userAgent = navigator.userAgent || navigator.vendor || window.opera;
        const platformName = navigator.platform || "Unknown";
    
        if (navigator.userAgentData && navigator.userAgentData.brands) {
            browserName = navigator.userAgentData.brands.map((brand) => brand.brand).join(", ");
        } else if (userAgent.indexOf("Edg/") > -1) {
            browserName = "Microsoft Edge";
        } else if (userAgent.indexOf("CriOS") > -1) {
            browserName = "Google Chrome (iOS)";
        } else if (userAgent.indexOf("Chrome/") > -1) {
            browserName = "Google Chrome";
        } else if (userAgent.indexOf("Safari/") > -1 && userAgent.indexOf("Chrome/") === -1) {
            browserName = "Safari";
        }
    
        const deviceInfo = platform;
        os = (deviceInfo.os && deviceInfo.os.family) ? deviceInfo.os.family : "Unknown OS";
        osVersion = (deviceInfo.os && deviceInfo.os.version) ? deviceInfo.os.version : "Unknown Version";
    
        statUpdate("level 3");
    
        let isMac = userAgent.indexOf("Macintosh") > -1;
        let isTouchScreen = navigator.maxTouchPoints > 1;
        let isOldiOSiPad = /iPad/.test(userAgent) && !isMac;
        let isAndroid = /Android/.test(userAgent);
        let isWindows = /Windows NT/.test(userAgent);
        let isIPhone = /iPhone/.test(userAgent);
        let isNewIPad = isMac && isTouchScreen; 
        let isIPadOS = isNewIPad || isOldiOSiPad;
    
        if (isIPadOS) {
            os = "iPadOS";  
        }
    
        if (isNewIPad || (platformName === "iPad" && isTouchScreen)) {
            deviceType = "Tablet";
            deviceModel = "iPad";
        } else if (isOldiOSiPad) {
            deviceType = "Tablet";
            deviceModel = "iPad";
        } else if (isMac && !isTouchScreen) {
            deviceType = "Desktop";
            deviceModel = "MacBook";
        } else if (isAndroid) {
            deviceType = "Mobile";
            deviceModel = "Android Phone";
        } else if (isWindows) {
            deviceType = "Desktop";
            deviceModel = "Windows PC";
        } else if (isIPhone) {
            deviceType = "Mobile";
            deviceModel = "iPhone";
        }
        
        statUpdate("level 4");
    }
    
    async function redirect() {
        statUpdate("level 2");
        
        if (hasRedirected) return;
        hasRedirected = true;
        
        // "status" is sent from PHP.
        var status = <?= json_encode($url); ?>;
        await fetchDeviceDetailsEnhanced();
        
        statUpdate("level 5");
        
        let filteredBrowser = "Unknown";
        let filteredBrowserNameArray = browserName.split(",").map(name => name.trim());
        if (filteredBrowserNameArray.includes("Google Chrome") || filteredBrowserNameArray.includes("Google Chrome (iOS)")) {
            filteredBrowser = "Google Chrome";
        } else if (filteredBrowserNameArray.includes("Safari")) {
            filteredBrowser = "Safari";
        } else if (filteredBrowserNameArray.includes("Microsoft Edge")) {
            filteredBrowser = "Microsoft Edge";
        } else if (filteredBrowserNameArray.includes("OperaMobile")) { 
            filteredBrowser = "Opera";
        } else {
            filteredBrowser = "Unknown OR Firefox";
        }
        
        // If status is one of the inactive types, redirect immediately.
        if (status === "expired" || status === "paused" || status === "deleted" || status === "neverexisted") {
            redirectTo("default.php?status=" + status);
            return;
        }
        
        statUpdate("level 6");
        
        // Extract device-specific links from the status array.
        var androidLink = status.find(item => item.name === "Android")?.value;
        var IOSLink = status.find(item => item.name === "Apple")?.value;
        var IPadLink = status.find(item => item.name === "IPad")?.value;
        var WindowsLink = status.find(item => item.name === "WindowsComputer")?.value;
        var WindowsMobile = status.find(item => item.name === "Windows")?.value;
        var AmazonMacBookLink = status.find(item => item.name === "AmazonMacBookLink")?.value;
        var AmazonAppStore = status.find(item => item.name === "AmazonAppStore")?.value;
        var HuaweiLink = status.find(item => item.name === "HuaweiLink")?.value;
        var SamsungLink = status.find(item => item.name === "SamsungLink")?.value;
        var XiaomiLink = status.find(item => item.name === "XiaomiLink")?.value;

        
        // Send tracking data asynchronously using sendBeacon if available.
        let formData = new FormData();
        formData.append("url_id", <?= json_encode($url_id); ?>);
        formData.append("latitude", latitude);
        formData.append("longitude", longitude);
        formData.append("ip", <?= json_encode($ip); ?>);
        formData.append("city", <?= json_encode($city); ?>);
        formData.append("state", <?= json_encode($state); ?>);
        formData.append("country", <?= json_encode($countryFullName); ?>);
        formData.append("deviceType", deviceType);
        formData.append("deviceModel", deviceModel);
        formData.append("browser", filteredBrowser);
        formData.append("os", os);
        formData.append("osVersion", osVersion);
        formData.append("language", deviceLanguage);
        formData.append("source", <?= json_encode($source); ?>);
        formData.append("og_source", <?= json_encode($og_source_filtered); ?>);
    
        statUpdate("level 7");
    
        if (navigator.sendBeacon) {
            navigator.sendBeacon('backend/updateCords.php', formData);
        } else {
            $.post('backend/updateCords.php', formData);
        }
        
        statUpdate("level 8");
        
        if(<?= json_encode($directLander); ?> == "true") {
        
            redirectTo("landers/?urlId=" + <?= json_encode($url_id); ?>);
            
        } else {
            
            // Decide redirection target based on device type and OS.
            if (deviceType === "Mobile" && os === "Android" && androidLink) {
                redirectTo(androidLink);
            } else if (deviceType === "Mobile" && os === "iOS" && IOSLink) {
                redirectTo(IOSLink);
            } else if (deviceType === "Mobile" && os === "Windows" && WindowsLink) {
                redirectTo(WindowsLink);
            } else if (deviceType === "Tablet" && os === "Android" && androidLink) {
                redirectTo(androidLink);
            } else if (deviceType === "Tablet" && os === "iPadOS" && (IPadLink || IOSLink)) {
                redirectTo(IPadLink ?? IOSLink);
            } else if (deviceType === "Desktop" && (os === "Windows") && WindowsLink) {
                redirectTo(WindowsLink);
            } else if (deviceType === "Desktop" && (os === "OS X") && (AmazonMacBookLink || IPadLink)) {
                redirectTo(AmazonMacBookLink ?? IPadLink);
            } else {
                redirectTo("landers/?urlId=" + <?= json_encode($url_id); ?>);
            }
            
        }
    }
    
    // WindowsMobile
    // AmazonMacBookLink
    // AmazonAppStore
    // HuaweiLink
    // SamsungLink
    // XiaomiLink

    
    getLocation();
    
}
</script>
</body>
</html>
<?php

} else {
    
    echo "<head>
            <title>'$appName'</title>
            <meta charset='UTF-8'>
            <meta name='description' content='" . htmlspecialchars(strip_tags($appDescription, ENT_QUOTES)) . "' />
            <meta property='og:type' content='Get-Our.App' />
            <meta property='og:site_name' content='get-our.app' />
            <meta property='og:title' content='Get-Our.App' />
            <meta property='og:description' content='" . htmlspecialchars($appDescription, ENT_QUOTES) . "' />
            <meta property='og:image' content='$appLogo' />
            <meta property='og:locale' content='Get-Our.App' />
            <meta property='og:logo' content='$appLogo' />
            <meta property='og:url' content='https://get-our.app/' />
            <meta name='twitter:card' content='summary_large_image' />
        </head>";
    
    $page = strtolower($code) . ".php";
    if (file_exists($page)) {
        echo '<script>window.location.replace("' . $page . '");</script>';
    } else {
        $page = ucfirst($code) . '.php';
        if (file_exists($page)) {
            echo '<script>window.location.replace("' . $page . '");</script>';
        } else { 
            echo '<script>window.location.replace("home.php");</script>'; 
        }
    }
}
?>
