<?php

namespace CreoCode\ContaoFormSubmissions\Classes;

use Contao\Frontend;
use Contao\FormFieldModel;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsModel;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsSetModel;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsDataModel;

/**
 * Class FormSubmissions
 */
class FormSubmissions extends Frontend
{
    /**
     * Save form submission
     */
    public function saveSubmission(array $arrSubmitted, array $arrLabels, array $arrFields): void
    {
        // Check if option is activated
        if (empty($arrLabels['cc_save_submissions'])) {
            return;
        }

        // Create new set if none found
        $set = FormSubmissionsSetModel::findOneBy('form_id', $arrLabels['id']);

        if ($set === null) {
            $set            = new FormSubmissionsSetModel();
            $set->form_id   = $arrLabels['id'];
            $set->form_alias = $arrLabels['alias'];
            $set->form_title = $arrLabels['title'];
            $set->tstamp    = time();
            $set->save();
        }

        // Save submission header
        $item            = new FormSubmissionsModel();
        $item->pid       = $set->id;
        $item->tstamp    = time();
        $item->recipient = $arrLabels['recipient'];
        $item->save();

        // Build allowed field name list
        $objFormFields = FormFieldModel::findBy('pid', $arrLabels['id']);
        $arrFormFields = $objFormFields !== null ? $objFormFields->fetchEach('name') : [];

        // Build legacy HTML representation for e-mail compatibility
        $strData = '<ul>';
        foreach ($arrSubmitted as $key => $value) {
            // Use in_array with strict=true to avoid falsy match on index 0
            if (!in_array($key, $arrFormFields, true)) {
                continue;
            }
            if (empty($value)) {
                $value = '-';
            }
            if (is_array($value)) {
                $value = implode(', ', $value);
            }
            $strData .= '<li><strong>' . htmlspecialchars($key) . '</strong>: ' . htmlspecialchars((string) $value) . '</li>';
        }
        $strData .= '</ul>';

        // Save form data
        $itemData              = new FormSubmissionsDataModel();
        $itemData->pid         = $item->id;
        $itemData->form_id     = $arrLabels['id'];
        $itemData->tstamp      = time();
        $itemData->subject     = $arrLabels['subject'];
        $itemData->data        = $strData;
        $itemData->arrSubmitted = serialize($arrSubmitted);
        $itemData->arrLabels   = serialize($arrLabels);
        $itemData->arrFields   = serialize($arrFields);
        $itemData->save();
    }
}
