<?php
/**
 * Session keep-alive + CSRF token refresh.
 *
 * Pages that stay open for long-running flows (cpanel imports, WordPress
 * installs, backup runs) would previously fall off the edge of PHP's
 * session.gc_maxlifetime. The page's <?php echo get_csrf_token() ?> snapshot
 * went stale relative to a freshly-rebuilt session, and the next AJAX call
 * got rejected with a CSRF mismatch. That bit a real import 2026-06-01.
 *
 * This endpoint:
 *   1. Loads auto-prepend (which restores the session via cookie/persist
 *      token if necessary), preventing GC of a session that's actively in use.
 *   2. Returns the CURRENT session csrf_token so the page can refresh its
 *      cached `nonce` JS variable without a full page reload.
 *
 * Frontend usage: ping every 5 minutes from any page that runs panel work.
 * (Implemented in web-files/js/whp-keepalive.js.)
 */

require_once('../auto-prepend.php');

header('Content-Type: application/json');
header('Cache-Control: no-store');

if (!defined('AUTH_USER')) {
    // Don't extend an unauth'd session. Return a clean 401 so the frontend
    // can prompt for re-login instead of pretending things are fine.
    http_response_code(401);
    echo json_encode([
        'ok'    => false,
        'error' => 'Not authenticated — please log in again.',
        'code'  => 'unauth',
    ]);
    exit;
}

// auto-prepend.php already validated nonce and (re)issued the session cookie
// with the panel-default lifetime, which is what prevents GC of the file.
// All we need to return is the current token.
echo json_encode([
    'ok'         => true,
    'csrf_token' => get_csrf_token(),
    'user'       => AUTH_USER,
    'ts'         => time(),
]);
