<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| One-time activation endpoint
|--------------------------------------------------------------------------
| The main bootstrap must load PDO as $pdo.
|--------------------------------------------------------------------------
*/

$bootstrapPath =
    '/home/thgejabu/public_html/bootstrap.php';

if (!is_file($bootstrapPath)) {
    http_response_code(500);
    exit('Bootstrap website tidak ditemukan.');
}

require_once $bootstrapPath;

if (
    !isset($pdo) ||
    !$pdo instanceof PDO
) {
    http_response_code(500);
    exit('Koneksi PDO website tidak tersedia.');
}

require_once
    '/home/thgejabu/backoffice_app/src/maintenance_common.php';

header(
    'Cache-Control: no-store, no-cache, must-revalidate, max-age=0'
);

header('Pragma: no-cache');
header('X-Robots-Tag: noindex, nofollow');

$rawToken = trim(
    (string) (
        $_GET['token'] ?? ''
    )
);

if (
    preg_match(
        '/^[a-f0-9]{64}$/',
        $rawToken
    ) !== 1
) {
    http_response_code(403);
    exit('Link akses maintenance tidak valid.');
}

try {
    $entry =
        maintenanceActivateToken(
            $pdo,
            $rawToken
        );

    if ($entry === null) {
        http_response_code(403);

        exit(
            'Link akses sudah digunakan, kedaluwarsa, atau tidak valid.'
        );
    }

    $expiresAt = (int) (
        $entry['expires_at'] ?? 0
    );

    setcookie(
        MAINTENANCE_BYPASS_COOKIE,
        $rawToken,
        maintenanceCookieOptions(
            $expiresAt
        )
    );

    header(
        'Location: https://rute-28.xyz/',
        true,
        302
    );

    exit;
} catch (Throwable $exception) {
    error_log(
        'MAINTENANCE ACCESS ERROR: ' .
        $exception->getMessage()
    );

    http_response_code(500);

    exit(
        'Akses maintenance gagal dibuat.'
    );
}
