<?php
// Session refresh endpoint

// Start output buffering to prevent any stray output
ob_start();

// Suppress PHP errors/warnings that might generate HTML output
error_reporting(E_ERROR | E_PARSE);

try {
    require_once 'includes/functions.php';
    require_once 'config/config.php';
    require_once 'includes/session_manager.php';
} catch (Exception $e) {
    // Clean any output and send error
    ob_clean();
    header('Content-Type: application/json');
    http_response_code(500);
    // Minimal language loading for early error
    $lang_alerts_early_error = loadLanguageFile('lang_alerts.php');
    echo json_encode(['success' => false, 'error' => $lang_alerts_early_error['API_ERROR_CONFIGURATION'] ?? 'Configuration error']);
    ob_end_flush();
    exit;
}

// Language loading using helper function
$lang_alerts = loadLanguageFile('lang_alerts.php');

// Clean any output buffer content and set JSON header
ob_clean();
header('Content-Type: application/json');



// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    ob_clean();
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => $lang_alerts['API_ERROR_METHOD_NOT_ALLOWED'] ?? 'Method not allowed']);
    ob_end_flush();
    exit;
}

// Check if user is logged in and session is valid
if (!validateAjaxSession()) {
    exit;
}

// Validate CSRF token
if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
    ob_clean();
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => $lang_alerts['API_ERROR_CSRF_INVALID'] ?? 'Invalid CSRF token']);
    ob_end_flush();
    exit;
}

try {
    // Regenerate session ID for security (suppress any warnings)
    @session_regenerate_id(true);
    
    // Use SessionManager to refresh the session
    if (SessionManager::refresh()) {
        // Get the updated expiry time
        if (isset($_SESSION['expires_at'])) {
            try {
                $expiryDateTime = new DateTime($_SESSION['expires_at']);
                $expiryTimestamp = $expiryDateTime->getTimestamp() * 1000; // JavaScript expects milliseconds
                

                
                // Ensure clean output
                ob_clean();
                echo json_encode([
                    'success' => true,
                    'expires_at' => $expiryTimestamp,
                    'message' => $lang_alerts['API_SUCCESS_SESSION_EXTENDED'] ?? 'Session extended successfully'
                ]);
            } catch (Exception $e) {
                throw new Exception(($lang_alerts['API_ERROR_SESSION_EXPIRY_PARSE_FAILED'] ?? "Failed to parse session expiry time: ") . $e->getMessage());
            }
        } else {
            throw new Exception($lang_alerts['API_ERROR_SESSION_EXPIRY_NOT_SET'] ?? "Session expiry time not set after refresh");
        }
    } else {
        throw new Exception($lang_alerts['API_ERROR_SESSION_REFRESH_FAILED'] ?? "SessionManager::refresh() returned false");
    }
    
} catch (Exception $e) {
    error_log("Session refresh error: " . $e->getMessage());
    
    // Ensure clean output
    ob_clean();
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $lang_alerts['API_ERROR_INTERNAL_SERVER'] ?? 'Internal server error']);
}

// End output buffering and send
ob_end_flush();
?> 