<?php
/**
 * @var \App\View\AppView $this
 * @var string $message
 * @var string|null $url
 */
use Cake\Core\Configure;
use Cake\Routing\Router;

// CSRF / FormProtection recovery is handled earlier in the middleware stack
// (see src/Middleware/TokenRecoveryMiddleware.php) — by the time we get here,
// it's a genuine 4xx. In debug mode show CakePHP's dev overlay.
if (Configure::read('debug')) {
    $this->setLayout('dev_error');
    $this->assign('title', $message ?? 'Not found');
    $this->assign('templateName', 'error400.php');

    $this->start('file');
    echo $this->element('auto_table_warning');
    $this->end();
    ?>
    <h2><?= h($message ?? 'Not found') ?></h2>
    <p class="error">
        <strong><?= __d('cake', 'Error') ?>: </strong>
        <?= __d('cake', 'The requested address {0} was not found on this server.', "<strong>'{$url}'</strong>") ?>
    </p>
    <?php
    return;
}

/*
 * Production: redirect to the on-brand /route-help page so visitors land on
 * something useful instead of a stock "Not found" screen. We can't issue a
 * real HTTP redirect from inside a view, so we emit a minimal HTML document
 * that does it three ways (header, meta refresh, JS) — whichever the UA
 * honours first wins. It degrades to a readable page.
 */
$requested = (string)($url ?? $this->getRequest()->getRequestTarget());
$redirectUrl = Router::url([
    '_name' => 'route_help',
    '?' => ['from' => $requested],
]);
// Single, explicit Location header. This works because error renderers run
// before any buffered output is flushed.
if (!headers_sent()) {
    header('Location: ' . $redirectUrl, true, 302);
}
$escaped = h($redirectUrl);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="refresh" content="0;url=<?= $escaped ?>">
    <title>Redirecting… · CandleCraft Academy</title>
    <link rel="icon" type="image/svg+xml" href="/favicon.svg">
    <style>
        body { margin: 0; min-height: 100vh; background: #FAF8F5; color: #1C1917;
               font-family: 'Plus Jakarta Sans', system-ui, sans-serif; display: grid; place-items: center; padding: 32px; }
        a { color: #B45C3D; }
    </style>
</head>
<body>
    <p>Sending you somewhere useful… <a href="<?= $escaped ?>">Continue →</a></p>
    <script>window.location.replace(<?= json_encode($escaped, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>);</script>
</body>
</html>
