<?php
// Database connection details
$dbHost = '127.0.0.1';
$dbPort = 3306;
$dbName = 'links';
$dbUser = 'links';
$dbPassword = 'lJ8jEjjlh)PBZ)D4';

try {
    // Create a new PDO connection
    $pdo = new PDO("mysql:host=$dbHost;port=$dbPort;dbname=$dbName", $dbUser, $dbPassword);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Get the 'link' parameter from the query string
$link = $_GET['link'] ?? '';

// If the link parameter is empty, show the welcome page
if ($link === '' || $link === 'index.php') {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Sterling Public Schools | URL Shortener</title>
        <link rel="stylesheet" href="assets/style.css">
        <meta property="og:image" content="https://assets.sterlingpsct.gov/favicon/android-chrome-512x512.png" />
        <link rel="icon" type="image/x-icon" href="https://assets.sterlingpsct.gov/favicon/favicon.ico">
        <META NAME="robots" CONTENT="noindex,nofollow">
        <meta name="color-scheme" content="light dark">
        <style>
            body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
            .welcome-container { padding: 20px; border: 1px solid #ccc; border-radius: 5px; display: inline-block; max-width: 600px; background-color: var(--container-bg); }
            h1 { color: #cc0000; }
            h2 { font-size: 12px; color: #cc0000; }
            .footerLink, .headerLink { color: #cc0000; text-decoration: none; }
            p { font-size: 18px; }
        </style>
    </head>
    <body>
        <div class="welcome-container">
            <a href="https://www.sterlingschool.org/" class="headerLink"><img src="https://assets.sterlingpsct.gov/logos/2024logo.png" height="30%" width="30%"></a>
            <h1>Sterling Public Schools</h1>
            <p>This domain (<a href="https://strk12.link/">strk12.link</a>) is used by Sterling Public Schools to provide shortened URLs. If you are a parent or community member, please note the link you are trying to access may be invalid.</p>
            <button onclick="window.location.href='https://sterlingschool.org'">Sterling Community School</button>
            <button onclick="window.location.href='https://sterlingct.us'">Town of Sterling</button>
            <br><br><hr>
            <h2>Copyright © <a href="https://www.sterlingschool.org/" class="footerLink">Sterling Public Schools</a> <script>document.write(new Date().getFullYear())</script>
        </div>
    </body>
    </html>
    <?php
    exit();
}

// Query the database for the provided short link
try {
    $stmt = $pdo->prepare("SELECT redirect_url FROM links WHERE short_link = :short_link AND deleted_at IS NULL");
    $stmt->execute(['short_link' => $link]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        // Redirect to the corresponding URL if a valid link is found
        header("Location: " . $row['redirect_url']);
        exit();
    }
} catch (PDOException $e) {
    die("Error fetching link: " . $e->getMessage());
}

// If no valid link is found, show the "Page Not Found" content
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Not Found</title>
    <link rel="stylesheet" href="style.css">
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
        .error-container { padding: 20px; border: 1px solid #ccc; border-radius: 5px; display: inline-block; max-width: 400px; background-color: #f9f9f9; }
        h1 { color: #d9534f; }
        p { font-size: 18px; }
        #countdown { font-weight: bold; color: #007bff; }
    </style>
    <script>
        let countdown = 5;
        const redirectUrl = 'https://www.sterlingschool.org/';

        function startCountdown() {
            const countdownElement = document.getElementById('countdown');
            if (countdown <= 0) {
                window.location.href = redirectUrl;
            } else {
                countdownElement.innerText = countdown;
                countdown--;
                setTimeout(startCountdown, 1000);
            }
        }

        window.onload = function() {
            startCountdown();
        };
    </script>
</head>
<body>
    <div class="error-container">
        <h1>404 - Page Not Found</h1>
        <p>We're sorry, but the short link you entered does not exist.</p>
        <p>Redirecting to Sterling Public Schools | Home in <span id="countdown">5</span> seconds.</p>
    </div>
</body>
</html>
