<?php

declare(strict_types=1);

namespace App\Modules\Messaging;

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

/**
 * MessageController — HTTP Handler for messaging templates and guest previews.
 *
 * Scoped only to request parsing, sessions, and rendering views.
 * Thin controller design with no SQL queries.
 *
 * @package Inveetaire
 * @ref     PILOT-006
 */
class MessageController extends BaseController
{
    protected string $layout = 'couple';
    private MessageModel $model;
    private MessageTemplateService $templateService;
    private MessageDeliveryService $deliveryService;
    private PublicInvitationService $publicInvitationService;

    public function __construct()
    {
        parent::__construct();
        $this->model = new MessageModel();
        $this->templateService = new MessageTemplateService();
        $this->deliveryService = new MessageDeliveryService();
        $this->publicInvitationService = new PublicInvitationService();
    }

    /**
     * Show the message template editor view.
     * Route: GET /app/couple/messaging/template
     *
     * @param Request $request
     * @return void
     */
    public function editTemplate(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');

        $template = $this->model->getTemplate($workspaceId, 'invitation');
        $defaultText = "Dear {{guest_name}},\n\nWe joyfully invite you to celebrate our wedding.\n\nPlease find your personal digital invitation pass below:\n{{invitation_url}}\n\n{{holy_information}}\n\n{{reception_information}}\n\nThank you,\n{{couple_name}}";
        $bodyText = $template ? $template['body_text'] : $defaultText;

        $this->render('message/template', [
            'title'    => 'Edit Message Template',
            'body_text'=> $bodyText,
            'errors'   => Session::get('errors') ?? [],
            'success'  => Session::get('success') ?? null
        ]);

        Session::set('errors', null);
        Session::set('success', null);
    }

    /**
     * Handle template form saving.
     * Route: POST /app/couple/messaging/template
     *
     * @param Request $request
     * @return void
     */
    public function saveTemplate(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        $bodyText = trim((string) $request->post('body_text'));


        if ($bodyText === '') {
            Session::set('errors', ['body_text' => 'Template message content cannot be empty.']);
            $this->redirect('/app/couple/messaging/template');
            return;
        }

        try {
            $this->model->saveTemplate($workspaceId, 'invitation', $bodyText);
            Session::set('success', 'Message template updated successfully!');
        } catch (\Throwable $e) {
            Session::set('errors', ['system' => 'Failed to save template: ' . $e->getMessage()]);
        }

        $this->redirect('/app/couple/messaging/template');
    }

    /**
     * List all guests with their compiled message previews, links, and deep links.
     * Route: GET /app/couple/messaging/preview
     *
     * @param Request $request
     * @return void
     */
    public function previewList(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');

        $workspace = $this->model->getWorkspace($workspaceId);
        if ($workspace === null) {
            $this->flash('error', 'Active workspace not found.');
            $this->redirect('/app/couple/dashboard');
            return;
        }

        $invitation = $this->model->getInvitation($workspaceId);

        // Fetch current template or fall back to default wording
        $template = $this->model->getTemplate($workspaceId, 'invitation');
        $defaultText = "Dear {{guest_name}},\n\nWe joyfully invite you to celebrate our wedding.\n\nPlease find your personal digital invitation pass below:\n{{invitation_url}}\n\n{{holy_information}}\n\n{{reception_information}}\n\nThank you,\n{{couple_name}}";
        $templateText = $template ? $template['body_text'] : $defaultText;

        // Load DB collections
        $guests = $this->model->getGuests($workspaceId);
        $allEvents = $this->model->getWeddingEvents($workspaceId);

        $compiledGuests = [];

        foreach ($guests as $guest) {
            $assignedEventIds = $this->model->getAssignedEventIds($workspaceId, (int) $guest['id']);
            
            // Generate guest personalized url using PublicInvitationService
            $personalUrl = $this->publicInvitationService->generatePersonalUrl($workspace['slug'], $guest['guest_code']);

            // Compile the message placeholders
            $compiledMessage = $this->templateService->compileMessage(
                $templateText,
                $guest,
                $workspace,
                $invitation,
                $allEvents,
                $assignedEventIds,
                $personalUrl
            );

            // Generate WhatsApp Deep Link
            $whatsAppUrl = '';
            if (!empty($guest['phone_number'])) {
                $whatsAppUrl = $this->deliveryService->generateWhatsAppUrl($guest['phone_number'], $compiledMessage);
            }

            $compiledGuests[] = [
                'id'           => $guest['id'],
                'full_name'    => $guest['full_name'],
                'phone_number' => $guest['phone_number'],
                'invited_pax'  => $guest['invited_pax'],
                'guest_group'  => $guest['guest_group'],
                'personal_url' => $personalUrl,
                'message'      => $compiledMessage,
                'whatsapp_url' => $whatsAppUrl
            ];
        }

        $this->render('message/preview', [
            'title'  => 'Invitation Distribution',
            'guests' => $compiledGuests
        ]);
    }
}
