<?php

use Contao\Backend;
use Contao\BackendUser;
use Contao\DataContainer;
use Contao\DC_Table;
use Contao\FormFieldModel;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsModel;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsDataModel;

/**
 * Table tl_form_submissions_set
 */
$GLOBALS['TL_DCA']['tl_form_submissions_set'] = array
    (
    // Config
    'config' => array
        (
        'dataContainer' => DC_Table::class,
        'ctable' => array('tl_form_submissions'),
        'closed' => true,
        'sql' => array
            (
            'keys' => array
                (
                'id' => 'primary',
                'form_id' => 'index'
            )
        )
    ),

    // Palettes
    'palettes' => array
        (
        'default' => '{label_legend},label_field;label_field_docs'
    ),

    // List
    'list' => array
        (
        'sorting' => array
            (
            'mode' => 1,
            'fields' => array('form_title'),
            'flag' => 1,
            'panelLayout' => 'search,limit'
        ),
        'label' => array
            (
            'fields' => array('form_title'),
            'format' => '%s'
        ),
        'global_operations' => array
            (

        ),
        'operations' => array
            (
            'settings' => array
                (
                'label' => &$GLOBALS['TL_LANG']['tl_form_submissions_set']['settings'],
                'href' => 'act=edit',
                'icon' => 'header.svg'
            ),
            'edit' => array
                (
                'label' => &$GLOBALS['TL_LANG']['tl_form_submissions_set']['edit'],
                'href' => 'table=tl_form_submissions',
                'icon' => 'edit.gif'
            ),
            'show' => array
                (
                'label' => &$GLOBALS['TL_LANG']['tl_form_submissions_set']['show'],
                'href' => 'act=show',
                'icon' => 'show.gif'
            )
        )
    ),

    // Fields
    'fields' => array
        (
        'id' => array
            (
            'sql' => "int(10) unsigned NOT NULL auto_increment"
        ),
        'form_id' => array
            (
            'label' => &$GLOBALS['TL_LANG']['tl_form_submissions_set']['form_id'],
            'foreignKey' => 'tl_form.id',
            'sql' => "int(10) unsigned NOT NULL default '0'",
            'relation' => array('type' => 'belongsTo')
        ),
        'form_alias' => array
            (
            'label' => &$GLOBALS['TL_LANG']['tl_form_submissions_set']['form_alias'],
            'exclude' => false,
            'search' => true,
            'sql' => "varbinary(128) NOT NULL default ''"
        ),
        'form_title' => array
            (
            'label' => &$GLOBALS['TL_LANG']['tl_form_submissions_set']['form_title'],
            'exclude' => false,
            'search' => true,
            'sorting' => false,
            'flag' => 1,
            'sql' => "varchar(255) NOT NULL default ''"
        ),
        'label_field' => array
            (
            'label' => &$GLOBALS['TL_LANG']['tl_form_submissions_set']['label_field'],
            'exclude' => true,
            'inputType' => 'text',
            'eval' => array(
                'tl_class' => 'w50',
                'maxlength' => 255,
                'decodeEntities' => true,
            ),
            'sql' => "varchar(255) NOT NULL default ''"
        ),
        // Rein visuelle Doku-Box – kein SQL, kein Input
        'label_field_docs' => array
            (
            'inputType' => 'text',
            'input_field_callback' => array('tl_form_submissions_set', 'generateDocsHtml'),
        ),
        'tstamp' => array
            (
            'sql' => "int(10) unsigned NOT NULL default '0'"
        )
    )
);

/**
 * Class tl_form_submissions_set
 */
class tl_form_submissions_set extends Backend
{

	/**
	 * Import the back end user object
	 */
	public function __construct()
	{
		parent::__construct();
		$this->import(BackendUser::class, 'User');
	}

    /**
     * Rendert eine Inline-Dokumentationsbox für das Anzeigemuster-Feld.
     * Zeigt die InsertTag-Syntax sowie die im Formular verfügbaren Feldnamen an.
     *
     * @param DataContainer $dc
     * @param string        $xlabel
     * @return string
     */
    public function generateDocsHtml(DataContainer $dc, string $xlabel = ''): string
    {
        \Contao\System::loadLanguageFile('tl_form_submissions_set');
        $lang = $GLOBALS['TL_LANG']['tl_form_submissions_set'];

        // ----------------------------------------------------------------
        // Verfügbare Feldnamen ermitteln
        // 1. Aus der letzten echten Einsendung (arrSubmitted)
        // 2. Fallback: aus der Formular-Konfiguration (tl_form_field)
        // ----------------------------------------------------------------
        $fields     = [];
        $fromLive   = false;
        $systemKeys = ['REQUEST_TOKEN', 'FORM_SUBMIT', 'MAX_FILE_SIZE', 'formatted_html', 'cc_save_submissions'];

        // $dc->activeRecord holds the current set row without an extra DB query
        $formId = (int) ($dc->activeRecord->form_id ?? 0);

        if ($dc->id && $formId) {
            $submission = FormSubmissionsModel::findOneBy('pid', $dc->id, ['order' => 'id DESC']);

            if ($submission !== null) {
                $submissionData = FormSubmissionsDataModel::findOneBy('pid', $submission->id);

                if ($submissionData !== null) {
                    $arrSubmitted = unserialize($submissionData->arrSubmitted, ['allowed_classes' => false]);
                    $arrLabels    = unserialize($submissionData->arrLabels,    ['allowed_classes' => false]);

                    if (is_array($arrSubmitted)) {
                        foreach ($arrSubmitted as $name => $value) {
                            if (in_array($name, $systemKeys, true) || $name === '') {
                                continue;
                            }
                            $label = (is_array($arrLabels) && !empty($arrLabels[$name]))
                                ? $arrLabels[$name]
                                : $name;
                            $fields[$name] = $label;
                        }
                        $fromLive = !empty($fields);
                    }
                }
            }

            // Fallback: Formularfelder aus tl_form_field
            if (empty($fields)) {
                $objFormFields = FormFieldModel::findBy(
                    ['pid=?', "name != ''", "inputType NOT IN ('explanation','html','headline')"],
                    [$formId],
                    ['order' => 'sorting ASC']
                );
                if ($objFormFields !== null) {
                    while ($objFormFields->next()) {
                        $label = $objFormFields->label ?: $objFormFields->name;
                        $fields[$objFormFields->name] = $label;
                    }
                }
            }
        }

        // ----------------------------------------------------------------
        // Feldliste HTML
        // ----------------------------------------------------------------
        $fieldRows = '';
        if (!empty($fields)) {
            foreach ($fields as $name => $label) {
                $tag = htmlspecialchars('{{field_value::' . $name . '}}');
                $fieldRows .= '
                <tr>
                    <td style="padding:0.15em 0.9em 0.15em 0;white-space:nowrap;vertical-align:top">
                        <code style="background:var(--code-bg);padding:0.1em 0.4em;border-radius:2px;font-size:0.85em">' . $tag . '</code>
                    </td>
                    <td style="color:var(--gray);vertical-align:top;font-size:0.9em">' . htmlspecialchars($label) . '</td>
                </tr>';
            }

            $sourceHint = $fromLive
                ? '<span style="color:var(--green);font-size:0.85em">&#10003; ' . htmlspecialchars($lang['docs_source_live'] ?? '') . '</span>'
                : '<span style="color:var(--gray);font-size:0.85em">' . htmlspecialchars($lang['docs_source_config'] ?? '') . '</span>';

            $fieldSection = '
            <div style="margin-bottom:0">
                <strong style="font-size:1em">' . htmlspecialchars($lang['docs_fields_title'] ?? '') . '</strong> &nbsp;' . $sourceHint . '
                <table style="border-collapse:collapse;margin-top:0.4em;width:100%">' . $fieldRows . '</table>
            </div>';
        } else {
            $fieldSection = '<p style="margin-bottom:0;color:var(--gray);font-size:0.9em">' . htmlspecialchars($lang['docs_fields_empty'] ?? '') . '</p>';
        }

        // ----------------------------------------------------------------
        // Gesamte Box
        // ----------------------------------------------------------------
        $codeStyle = 'background:var(--code-bg);padding:0.1em 0.4em;border-radius:2px;font-size:0.85em';

        return '
        <div class="widget clr" style="margin-top:-8px">
            <div style="font-size:1rem;background:var(--info-bg);border:1px solid var(--blue);border-radius:3px;padding:1em 1.2em;line-height:1.3;color:var(--text)">

                <strong style="display:block;font-size:1em;margin-bottom:0.6em">' . htmlspecialchars($lang['docs_title'] ?? '') . '</strong>

                <table style="border-collapse:collapse;width:100%">
                    <tr>
                        <td style="padding:0.15em 0.9em 0.15em 0;white-space:nowrap;vertical-align:top">
                            <code style="' . $codeStyle . '">{{field_value::feldname}}</code>
                        </td>
                        <td style="color:var(--gray);font-size:0.9em;vertical-align:middle">' . htmlspecialchars($lang['docs_desc_single'] ?? '') . '</td>
                    </tr>
                    <tr>
                        <td style="padding:0.15em 0.9em 0.15em 0;white-space:nowrap;vertical-align:top">
                            <code style="' . $codeStyle . '">{{field_value::feld1::feld2}}</code>
                        </td>
                        <td style="color:var(--gray);font-size:0.9em;vertical-align:middle">' . htmlspecialchars($lang['docs_desc_fallback'] ?? '') . '</td>
                    </tr>
                    <tr>
                        <td style="padding:0.15em 0.9em 0.15em 0;white-space:nowrap;vertical-align:top">
                            <code style="' . $codeStyle . '">{{field_value::feld::Fallback-Text}}</code>
                        </td>
                        <td style="color:var(--gray);font-size:0.9em;vertical-align:middle">' . htmlspecialchars($lang['docs_desc_text'] ?? '') . '</td>
                    </tr>
                </table>

                <div style="margin-top:0.75em;padding-top:0.75em;border-top:1px solid var(--content-border);margin-bottom:0.75em">
                    <strong style="font-size:1em">' . htmlspecialchars($lang['docs_examples'] ?? '') . ':</strong>
                    <div style="margin-top:0.4em">
                        <code style="' . $codeStyle . ';display:inline-block;margin-bottom:0.25em">{{field_value::name}}</code><br>
                        <code style="' . $codeStyle . ';display:inline-block;margin-bottom:0.25em">{{field_value::firstname}} {{field_value::lastname}}</code><br>
                        <code style="' . $codeStyle . ';display:inline-block;margin-bottom:0">{{field_value::email::kontakt_email::E-Mail unbekannt}}</code>
                    </div>
                </div>

                ' . $fieldSection . '
            </div>
        </div>';
    }
}
