<?php

namespace App\Http\Controllers;

use App\Models\Form;
use App\Services\FormEmbedBuilder;

/**
 * Public endpoints backing the generated embed code: the popup runtime
 * widget script, and a lightweight view-counter ping fired by both the
 * inline snippet and the popup script (see FormEmbedBuilder).
 */
class FormEmbedController extends Controller
{
    public function script(string $uuid)
    {
        $form = Form::where('uuid', $uuid)->where('type', 'popup')->first();

        if (!$form) {
            return $this->warningScript('CRMfic popup form not found for uuid "' . $uuid . '".');
        }

        if ($form->status !== 'active') {
            return $this->warningScript('CRMfic popup form "' . $form->name . '" is not published yet - set it to Active in the builder to make it appear on your site.');
        }

        return response(FormEmbedBuilder::popupScript($form), 200)
            ->header('Content-Type', 'text/javascript; charset=utf-8')
            ->header('Cache-Control', 'no-cache');
    }

    public function inlineScript(string $uuid)
    {
        $form = Form::where('uuid', $uuid)->where('type', 'inline')->first();

        if (!$form) {
            return $this->warningScript('CRMfic form not found for uuid "' . $uuid . '".');
        }

        if ($form->status !== 'active') {
            return $this->warningScript('CRMfic form "' . $form->name . '" is not published yet - set it to Active in the builder to make it appear on your site.');
        }

        return response(FormEmbedBuilder::inlineScript($form), 200)
            ->header('Content-Type', 'text/javascript; charset=utf-8')
            ->header('Cache-Control', 'no-cache');
    }

    private function warningScript(string $message)
    {
        $js = 'console.warn(' . json_encode($message) . ');';

        return response($js, 200)
            ->header('Content-Type', 'text/javascript; charset=utf-8')
            ->header('Cache-Control', 'no-cache');
    }

    public function view(string $uuid)
    {
        Form::where('uuid', $uuid)->where('status', 'active')->increment('total_views');

        return response()->noContent();
    }
}
