<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Permission;
use App\Models\SmartRecipient;
use App\Models\CommunicationTemplate;
use App\Services\CommunicationTemplateRenderer;

final class SmartCommunicationController extends Controller
{
    public function composer(): void
    {
        Auth::requireLogin();
        Permission::require(
            'communications.recipients.search'
        );

        $this->view(
            'communications/smart_composer',
            [
                'pageTitle'=>
                    'Communication intelligente',
                'templates'=>
                    CommunicationTemplate::all(),
            ]
        );
    }

    public function recipients(): void
    {
        Auth::requireLogin();
        Permission::require(
            'communications.recipients.search'
        );

        header(
            'Content-Type: application/json; charset=utf-8'
        );
        header('Cache-Control: no-store');

        echo json_encode(
            [
                'results'=>SmartRecipient::search(
                    (string)($_GET['q'] ?? '')
                )
            ],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }

    public function addresses(): void
    {
        Auth::requireLogin();
        Permission::require(
            'communications.recipients.search'
        );

        $type=(string)($_GET['source_type'] ?? '');
        $id=(int)($_GET['source_id'] ?? 0);

        header(
            'Content-Type: application/json; charset=utf-8'
        );
        header('Cache-Control: no-store');

        echo json_encode(
            [
                'addresses'=>
                    SmartRecipient::addresses(
                        $type,
                        $id
                    ),
                'context'=>
                    SmartRecipient::context(
                        $type,
                        $id
                    ),
            ],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }

    public function preview(): void
    {
        Auth::requireLogin();
        Permission::require(
            'communications.templates.edit'
        );

        $template=CommunicationTemplate::find(
            (int)($_POST['modele_id'] ?? 0)
        );

        if(!$template){
            http_response_code(404);
            exit('Modèle introuvable.');
        }

        $context=json_decode(
            (string)($_POST['context_json'] ?? '{}'),
            true
        ) ?: [];

        $context['signature']=
            (string)($template['signature_html'] ?? '');
        $context['signature_texte']=
            (string)($template['signature_texte'] ?? '');

        $renderer=new CommunicationTemplateRenderer();

        $object=$renderer->render(
            (string)$template['objet'],
            $context
        );

        $html=$renderer->render(
            (string)$template['corps_html'],
            $context
        );

        $text=$renderer->render(
            (string)($template['corps_texte'] ?? ''),
            $context
        );

        header(
            'Content-Type: application/json; charset=utf-8'
        );

        echo json_encode(
            [
                'object'=>$object,
                'html'=>$html,
                'text'=>$text,
                'unresolved'=>array_values(
                    array_unique(
                        array_merge(
                            $renderer->unresolvedVariables(
                                $object
                            ),
                            $renderer->unresolvedVariables(
                                $html
                            ),
                            $renderer->unresolvedVariables(
                                $text
                            )
                        )
                    )
                )
            ],
            JSON_UNESCAPED_UNICODE
        );
        exit;
    }
}
