<?php
declare(strict_types=1);
@ini_set('display_errors', '1');
@error_reporting(E_ALL);

require_once 'db/config.php';

if (isset($_GET['token'])) {
    $token = $_GET['token'];

    try {
        $pdo = db();
        $stmt = $pdo->prepare("SELECT `id`, `expires_at` FROM `published_pages` WHERE `management_token` = ?");
        $stmt->execute([$token]);
        $page = $stmt->fetch();

        if ($page) {
            $new_expires_at = date('Y-m-d H:i:s', strtotime('+60 days'));
            $update_stmt = $pdo->prepare("UPDATE `published_pages` SET `expires_at` = ? WHERE `id` = ?");
            $update_stmt->execute([$new_expires_at, $page['id']]);

            echo "<div style='text-align:center; padding: 50px;'>";
            echo "<h2>Success!</h2>";
            echo "<p>Your page's lifetime has been extended by 60 days.</p>";
            echo "<p>New expiration date: " . $new_expires_at . "</p>";
            echo "</div>";
        } else {
            echo "<div style='text-align:center; padding: 50px;'>";
            echo "<h2>Error!</h2>";
            echo "<p>Invalid management token.</p>";
            echo "</div>";
        }
    } catch (PDOException $e) {
        error_log("DB Error: " . $e->getMessage());
        echo "<div style='text-align:center; padding: 50px;'>";
        echo "<h2>Error!</h2>";
        echo "<p>An error occurred while processing your request.</p>";
        echo "</div>";
    }
} else {
    header('Location: index.php');
    exit;
}

