<?php

declare(strict_types=1);

namespace App\Modules\Theme;

/**
 * ThemeRenderer -- Resolves and renders the invitation entry view for a theme.
 *
 * Responsibilities:
 *   - Receive workspace, guest, invitation, and theme data.
 *   - Resolve the correct theme entry file path.
 *   - Render the theme entry file with data extracted into scope.
 *   - Controllers must not know theme-specific paths.
 *
 * No SQL. No theme-path logic in controllers.
 *
 * @package Inveetaire
 * @ref     RC-009
 */
class ThemeRenderer
{
    /**
     * Render a theme entry file with the provided invitation data.
     *
     * The theme entry file receives these variables in its scope:
     *   $workspace    -- array  -- Workspace details.
     *   $guest        -- array  -- Guest details.
     *   $invitation   -- array  -- Invitation configuration.
     *   $events       -- array  -- Assigned wedding events.
     *   $sections     -- array  -- Compiled visible sections.
     *   $theme        -- array  -- Theme manifest data.
     *   $themePath    -- string -- Absolute path to the theme folder (for assets).
     *   $url          -- string -- Personal invitation URL.
     *   $qr_code      -- string -- Base64 QR code payload.
     *   $rsvp         -- array|null -- Previous RSVP data.
     *   $wish         -- array|null -- Previous wish data.
     *
     * @param string $entryFile Absolute path to the theme entry PHP file.
     * @param array  $data      Invitation render payload.
     * @return void
     */
    public function render(string $entryFile, array $data): void
    {
        if (!file_exists($entryFile)) {
            http_response_code(503);
            echo '<p style="font-family:sans-serif;text-align:center;padding:2rem;">'
               . 'Invitation theme is currently unavailable. Please try again later.'
               . '</p>';
            return;
        }

        // Expose $themePath so themes can reference their own assets
        $data['themePath'] = dirname($entryFile);

        // Isolate theme rendering in a closure to prevent variable leakage
        $renderTheme = static function (string $__entry, array $__data): void {
            extract($__data, EXTR_SKIP);
            require $__entry;
        };

        $renderTheme($entryFile, $data);
    }
}