<?php

declare(strict_types=1);

namespace App\Modules\Invitation;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Session;
use App\Modules\PublicInvitation\PublicInvitationService;
use App\Modules\Theme\ThemeService;

/**
 * InvitationController — HTTP Handler for Couple Portal Invitation management.
 *
 * Coordinates rendering the invitation builder form, executing updates via
 * the service layer, and serving the invitation page preview using the couple layout.
 *
 * @package Inveetaire
 * @ref     PILOT-001
 */
class InvitationController extends BaseController
{
    protected string $layout = 'couple';
    private InvitationService $service;

    public function __construct()
    {
        parent::__construct();
        $this->service = new InvitationService();
    }

    /**
     * Display the invitation configuration builder.
     *
     * @param Request $request
     * @return void
     */
    public function edit(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');

        try {
            $invitation = $this->service->getInvitationDetails($workspaceId);
            $themes     = $this->service->getThemeOptions();

            // Resolve workspace slug for the Live Preview button URL
            $workspace = $this->service->getWorkspaceDetails($workspaceId);
            $workspaceSlug = (string) ($workspace['slug'] ?? '');

            $this->render('invitation/edit', [
                'title'          => 'Edit Invitation',
                'invitation'     => $invitation,
                'themes'         => $themes,
                'workspace_slug' => $workspaceSlug,
                'old'            => Session::get('old_input') ?? [],
                'errors'         => Session::get('errors') ?? []
            ]);

        } catch (\Throwable $e) {
            $this->flash('error', $e->getMessage());
            $this->redirect('/app/couple/dashboard');
        }

        // Clear temporary form values from session
        Session::set('old_input', null);
        Session::set('errors', null);
    }

    /**
     * Handle configuration save and publish state submissions.
     *
     * @param Request $request
     * @return void
     */
    public function update(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        $postData = $request->allPost();

        // Separate validation check to return precise errors list in view
        $validator = new InvitationValidator();
        $errors = $validator->validate($postData, $workspaceId);

        if (!empty($errors)) {
            Session::set('errors', $errors);
            Session::set('old_input', $postData);
            $this->flash('error', 'Please correct the errors in the form.');
            $this->redirect('/app/couple/invitation/edit');
            return;
        }

        try {
            $this->service->updateInvitationDetails($workspaceId, $postData);
            
            $status = trim((string) ($postData['invitation_status'] ?? 'draft'));
            $successMsg = ($status === 'published')
                ? 'Your wedding invitation is now PUBLISHED and live!'
                : 'Invitation draft saved successfully.';
                
            $this->flash('success', $successMsg);
            $this->redirect('/app/couple/invitation/edit');

        } catch (\Throwable $e) {
            $this->flash('error', 'Failed to save changes: ' . $e->getMessage());
            Session::set('old_input', $postData);
            $this->redirect('/app/couple/invitation/edit');
        }
    }

    /**
     * Display the invitation theme layout preview screen inside the device simulator.
     *
     * Delegates rendering to PublicInvitationService and ThemeService to guarantee
     * 100% renderer parity with Live Preview and Public Invitation pages.
     *
     * @param Request $request
     * @return void
     */
    public function preview(Request $request): void
    {
        $this->layout = 'ajax';
        $workspaceId  = (int) Session::get('active_workspace_id');

        try {
            $invitation = $this->service->getInvitationDetails($workspaceId);
            $themes     = $this->service->getThemeOptions();

            $themeName = 'Klasik Putih';
            foreach ($themes as $theme) {
                if ((int) $theme['id'] === (int) ($invitation['theme_version_id'] ?? 1)) {
                    $themeName = "{$theme['theme_name']} v{$theme['version_number']}";
                    break;
                }
            }

            // Obtain compiled production render payload
            $publicService = new PublicInvitationService();
            $payload = $publicService->getRenderedPayloadForPreview($workspaceId);

            $themeHtml = '';
            if ($payload !== null) {
                $brideName = $payload['workspace']['bride_name'] ?? 'Bride';
                $groomName = $payload['workspace']['groom_name'] ?? 'Groom';

                $renderPayload = [
                    'title'        => "{$brideName} & {$groomName}",
                    'workspace'    => $payload['workspace'],
                    'guest'        => $payload['guest'],
                    'invitation'   => $payload['invitation'],
                    'events'       => $payload['events'],
                    'theme'        => $payload['theme'],
                    'sections'     => $payload['sections'],
                    'url'          => $payload['personal_url'],
                    'qr_code'      => $payload['qr_code'],
                    'rsvp'         => $payload['rsvp'] ?? null,
                    'wish'         => $payload['wish'] ?? null,
                    'live_preview' => true,
                ];

                ob_start();
                $themeService = new ThemeService();
                $themeService->renderInvitation($renderPayload);
                $themeHtml = (string) ob_get_clean();
            }

            $this->render('invitation/preview', [
                'title'                => 'Invitation Preview — ' . $themeName,
                'invitation'           => $invitation,
                'theme_name'           => $themeName,
                'invitationScreenHtml' => $themeHtml,
            ]);

        } catch (\Throwable $e) {
            $this->layout = 'couple';
            $this->flash('error', 'Preview failed: ' . $e->getMessage());
            $this->redirect('/app/couple/invitation/edit');
        }
    }

    /**
     * Display the invitation theme design overview workspace.
     *
     * @param Request $request
     * @return void
     */
    public function design(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');

        try {
            $invitation = $this->service->getInvitationDetails($workspaceId);
            $themes = $this->service->getThemeOptions();

            // Find selected theme version display details
            $themeName = 'Klasik Putih';
            $themeObj = null;
            foreach ($themes as $theme) {
                if ((int) $theme['id'] === (int) $invitation['theme_version_id']) {
                    $themeName = "{$theme['theme_name']} v{$theme['version_number']}";
                    $themeObj = $theme;
                    break;
                }
            }

            $this->render('invitation/design', [
                'title'      => 'Design Workspace',
                'invitation' => $invitation,
                'theme_name' => $themeName,
                'theme'      => $themeObj,
                'themes'     => $themes
            ]);

        } catch (\Throwable $e) {
            $this->flash('error', 'Failed to load design workspace: ' . $e->getMessage());
            $this->redirect('/app/couple/dashboard');
        }
    }
}
