<?php

declare(strict_types=1);

namespace App\Modules\Interaction;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Session;
use App\Core\ErrorHandler;

/**
 * InteractionController — Handles unauthenticated guest form submissions for RSVP
 * and wishes. Scopes all error mappings and redirects back to the invitation page.
 *
 * @package Inveetaire
 * @ref     PILOT-005
 */
class InteractionController extends BaseController
{
    private InteractionService $service;

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

    /**
     * Handle POST submission for RSVP.
     * Route: POST /{workspace_slug}/i/{guest_token}/rsvp
     *
     * @param Request $request
     * @return void
     */
    public function submitRsvp(Request $request): void
    {
        $slug = (string) $request->param('workspace_slug');
        $token = (string) $request->param('guest_token');

        if ($slug === '' || $token === '') {
            ErrorHandler::renderNotFound();
            return;
        }

        // Gather form post input parameters
        $notes = $request->post('notes') ?? $request->post('message');
        $data = [
            'response'      => $request->post('response'),
            'confirmed_pax' => $request->post('confirmed_pax'),
            'notes'         => $notes
        ];

        try {
            $result = $this->service->saveRsvp($slug, $token, $data);

            if (!$result['success']) {
                // Flash validation errors to session
                Session::set('errors', $result['errors']);
            } else {
                Session::set('success', 'RSVP submitted successfully!');
            }
        } catch (\InvalidArgumentException $e) {
            // Invalid workspace or token
            ErrorHandler::renderNotFound();
            return;
        } catch (\Throwable $e) {
            Session::set('errors', ['system' => 'Unable to submit RSVP: ' . $e->getMessage()]);
        }

        // Redirect back to landing page (prevent form resubmission warning)
        $this->redirect("/{$slug}/i/{$token}");
    }

    /**
     * Handle POST submission for Wishes.
     * Route: POST /{workspace_slug}/i/{guest_token}/wish
     *
     * @param Request $request
     * @return void
     */
    public function submitWish(Request $request): void
    {
        $slug = (string) $request->param('workspace_slug');
        $token = (string) $request->param('guest_token');

        if ($slug === '' || $token === '') {
            ErrorHandler::renderNotFound();
            return;
        }

        // Gather form post input
        $data = [
            'message' => $request->post('message')
        ];

        try {
            $result = $this->service->saveWish($slug, $token, $data);

            if (!$result['success']) {
                Session::set('errors', $result['errors']);
            } else {
                $msg = !empty($result['moderated'])
                    ? 'Wish submitted! It will be displayed after couple approval.'
                    : 'Wish submitted successfully!';
                Session::set('success', $msg);
            }
        } catch (\InvalidArgumentException $e) {
            ErrorHandler::renderNotFound();
            return;
        } catch (\Throwable $e) {
            Session::set('errors', ['system' => 'Unable to submit Wish: ' . $e->getMessage()]);
        }

        $this->redirect("/{$slug}/i/{$token}");
    }
}
