<?php
require 'db.php';

$shortUrl = '';
$shortCode = '';
$clicks = 0;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $originalUrl = trim($_POST['url']);
    if (filter_var($originalUrl, FILTER_VALIDATE_URL)) {
        $result = createShortUrl($pdo, $originalUrl);
        $shortCode = $result['short_code'];
        $shortUrl = "https://1134a.store/" . $shortCode;
        $clicks = $result['clicks'];
    } else {
        $error = "Please enter a valid URL";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Simple URL Shortener</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f4f4f4; text-align: center; padding-top: 50px; }
        input[type=text] { padding: 10px; width: 300px; }
        input[type=submit] { padding: 10px 20px; }
        .result { margin-top: 20px; font-size: 18px; }
        .error { color: red; margin-top: 20px; }
    </style>
</head>
<body>

<h1>URL Shortener</h1>

<form method="POST">
    <input type="text" name="url" placeholder="Enter your URL" required>
    <input type="submit" value="Generate Short URL">
</form>

<?php if ($shortUrl) : ?>
    <div class="result">
        Short URL: <a href="<?= htmlspecialchars($shortUrl) ?>" target="_blank"><?= htmlspecialchars($shortUrl) ?></a><br>
        Clicks: <span id="click-count"><?= $clicks ?></span>
    </div>
    <script>
        const shortCode = "<?= $shortCode ?>";
        const countEl = document.getElementById('click-count');

        // 每5秒刷新点击数
        setInterval(() => {
            fetch('get_clicks.php?code=' + shortCode)
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        countEl.textContent = data.clicks;
                    }
                });
        }, 5000);
    </script>
<?php elseif ($error) : ?>
    <div class="error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

</body>
</html>
