<?php
declare(strict_types=1);

namespace Celena\Plugin\Leads\Controllers;

use Celena\Core\Database\Connection;
use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Mail\Mailer;
use Celena\Core\Template\Engine;
use Celena\Module\Settings\Options;
use Celena\Plugin\Leads\Repositories\FormRepository;
use Celena\Plugin\Leads\Support\FormRenderer;

/**
 * Публичные эндпоинты конструктора форм:
 *   POST /api/forms/{slug}/submit — приём заявки конкретной формы
 *   GET  /form/{slug}             — отдельная страница с формой (для встраивания ссылкой)
 */
final class FormsPublicController
{
    public function __construct(
        private readonly Connection $conn,
        private readonly Mailer $mailer,
        private readonly Options $options,
        private readonly Engine $engine,
    ) {
    }

    public function submit(Request $req, array $params): Response
    {
        $slug = (string) ($params['slug'] ?? '');
        return (new FormSubmitService($this->conn, $this->mailer, $this->options))->handle($req, $slug);
    }

    public function show(Request $req, array $params): Response
    {
        $slug = (string) ($params['slug'] ?? '');
        $form = (new FormRepository($this->conn))->findBySlug($slug);
        if ($form === null || (string) ($form['status'] ?? 'active') !== 'active') {
            return Response::notFound();
        }
        $siteUrl = (string) $this->options->get('site_url', '');
        $vars = [
            'site'               => ['name' => (string) $this->options->get('site_name', 'Celena'), 'url' => $siteUrl],
            'page'               => ['og_image' => ''],
            'form_html'          => FormRenderer::render($form),
            'form_title'         => (string) ($form['title'] ?? ''),
            'seo_title_override' => (string) ($form['title'] ?? 'Form'),
            'seo_desc_override'  => '',
            'canonical_url'      => $siteUrl . '/form/' . $slug,
            'no_hreflang'        => '1',
        ];
        $this->engine->setTheme((string) $this->options->get('theme', 'celena-agency'));
        return Response::html($this->engine->render('plugins/leads/form_page', $vars));
    }
}
