<?php

namespace CreoCode\ContaoFormSubmissions\Classes;

use Contao\BackendModule;
use Contao\Input;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsModel;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsSetModel;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsDataModel;

/**
 * Class FormSubmissionsDataShow
 */
class FormSubmissionsDataShow extends BackendModule
{
	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = 'form_submissions_data_show';

	/**
	 * Generate the module
	 */
	protected function compile(): void
	{
		$showFormId = (int) Input::get('showForm');

		if ($showFormId <= 0) {
			return;
		}

		$submission = FormSubmissionsModel::findById($showFormId);

		if ($submission === null) {
			return;
		}

		$submissionSet  = FormSubmissionsSetModel::findById($submission->pid);
		$submissionData = FormSubmissionsDataModel::findOneBy('pid', $submission->id);

		$submissionRow     = $submission->row();
		$submissionSetRow  = $submissionSet?->row() ?? [];
		$submissionDataRow = $submissionData?->row() ?? [];

		// Unserialize arrSubmitted for table + JSON display
		if (!empty($submissionDataRow['arrSubmitted'])) {
			$arrSubmitted = unserialize($submissionDataRow['arrSubmitted'], ['allowed_classes' => false]);
			$arrLabels    = !empty($submissionDataRow['arrLabels'])
				? unserialize($submissionDataRow['arrLabels'], ['allowed_classes' => false])
				: [];

			$systemKeys = ['REQUEST_TOKEN', 'FORM_SUBMIT', 'MAX_FILE_SIZE', 'formatted_html', 'cc_save_submissions'];
			$tableRows  = [];
			$jsonData   = [];

			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;

					if (is_array($value)) {
						$displayValue = implode(', ', $value);
					} elseif ($value === '' || $value === null) {
						$displayValue = '-';
					} else {
						$displayValue = (string) $value;
					}

					$tableRows[]      = ['label' => $label, 'name' => $name, 'value' => $displayValue];
					$jsonData[$label] = $displayValue;
				}
			}

			$submissionDataRow['tableRows']        = $tableRows;
			$submissionDataRow['arrSubmittedJson'] = json_encode(
				$jsonData,
				JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
			);
		}

		$this->Template->submission     = $submissionRow;
		$this->Template->submissionSet  = $submissionSetRow;
		$this->Template->submissionData = $submissionDataRow;
	}
}
