<?php

namespace GriffinForms\Admin\Html\Elements\Submission;

class Field extends \GriffinForms\Admin\Html\Format
{
    protected $field_id;
    protected $field_value;
    protected $field;
    protected $submission_id;
    protected $decrypt_nonce;
    protected $context = [];


    protected function setField()
    {
        $this->field = new \GriffinForms\Items\Field();
        $this->field->loadItem($this->field_id);
    }

    public function getHtml()
    {
        $field_classes = array('gf-submission-field', 'mb-4', 'text-break');

        if ($this->isAccountEmailSourceField()) {
            $field_classes[] = 'gf-submission-field-account-email-source';
        }

        echo '<div class="' . esc_attr(implode(' ', $field_classes)) . '" data-gf-fieldid="' . esc_attr($this->field_id) . '">';
        echo '<div class="gf-submission-field-header mb-2">';
        $this->fieldLabelHtml();
        echo '</div>';
        echo '<div class="gf-submission-field-body">';
        $this->formControlHtml();
        echo '</div>';
        $this->fieldDescriptionHtml();
        echo '</div>';
    }

    protected function fieldLabelHtml()
    {
        echo '<div class="gf-submission-field-heading">';
        echo '<div class="gf-submission-field-label text-uppercase text-muted small fw-semibold letter-spacing-sm">';
        echo esc_html($this->field->getProp('heading'));
        echo '</div>';
        $this->fieldHeaderMarkerHtml();
        echo '</div>';
    }

    protected function fieldHeaderMarkerHtml()
    {
        if (!$this->isAccountEmailSourceField()) {
            return;
        }

        echo '<div class="gf-submission-field-source-note" title="' . esc_attr__('Used for account registration', 'griffinforms-form-builder') . '" aria-label="' . esc_attr__('Used for account registration', 'griffinforms-form-builder') . '">';
        echo '<span class="gf-submission-field-source-mark-icon" aria-hidden="true"></span>';
        echo '<span class="gf-submission-field-source-mark-text">' . esc_html__('Used for account registration', 'griffinforms-form-builder') . '</span>';
        echo '</div>';
    }

    protected function fieldDescriptionHtml()
    {
        $desc = $this->field->getProp('description');
        if ($desc !== '') {
            echo '<div class="gf-submission-field-help text-muted small mt-2">';
            echo esc_html($desc);
            echo '</div>';
        }
    }

    protected function formControlHtml()
    {
        $field_type = $this->field->getProp('field_type');

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

        $field_class = $this->config->getSubmissionFieldClass((string) $field_type);
        if ($field_class === '' || !class_exists($field_class)) {
            $this->renderUnavailableFieldHtml((string) $field_type);
            return;
        }

        $this->renderFieldValuesWithClass($field_class);
    }

    protected function renderFieldValuesWithClass(string $field_class)
    {
        if ($field_class === \GriffinForms\Admin\Html\Elements\Submission\Payment::class) {
            $context = array(
                'submission_id' => $this->submission_id,
                'payment_status' => $this->context['payment_status'] ?? '',
                'payment_meta' => $this->context['payment_meta'] ?? [],
                'cart' => $this->context['cart'] ?? [],
                'form_id' => $this->context['form_id'] ?? 0,
            );

            $field = new $field_class($this->field, $this->field_value, $context);
            $field->getHtml();
            return;
        }

        if ($field_class === \GriffinForms\Admin\Html\Elements\Submission\InputPassword::class) {
            if (!is_array($this->field_value)) {
                echo '<div class="' . esc_attr($this->input_class) . '">' . wp_kses_post($this->field_value) . '</div>';
                return;
            }

            foreach ($this->field_value as $index => $field_value) {
                $context = array(
                    'submission_id' => $this->submission_id,
                    'field_id' => $this->field_id,
                    'iteration' => $index,
                    'decrypt_nonce' => $this->decrypt_nonce,
                );

                $field = new $field_class($this->field, $field_value, $context);
                $field->getHtml();
            }

            return;
        }

        foreach ($this->field_value as $field_value) {
            $field = new $field_class($this->field, $field_value);
            $field->getHtml();
        }
    }

    protected function renderUnavailableFieldHtml(string $field_type): void
    {
        $this->log->add(
            'warning',
            'field',
            $this->field_id,
            get_current_user_id(),
            sprintf('Unavailable submission renderer for field type "%s".', $field_type),
            'package_provider'
        );

        echo '<div class="gf-notice gf-notice-warning">';
        echo esc_html__('This submission value cannot be rendered because the field renderer is not currently available.', 'griffinforms-form-builder');
        echo '</div>';
    }

    public function __construct($field_id = 0, $field_value = [], $context = [])
    {
        $this->field_id = absint($field_id);
        $this->field_value = is_array($field_value) ? $field_value : [];
        $context = is_array($context) ? $context : [];
        $this->submission_id = isset($context['submission_id']) ? absint($context['submission_id']) : 0;
        $this->decrypt_nonce = isset($context['decrypt_nonce']) ? sanitize_text_field($context['decrypt_nonce']) : '';
        $this->context = $context;
        $this->setAll();
    }

    protected function isAccountEmailSourceField(): bool
    {
        $field_ids = $this->context['accounts_email_field_ids'] ?? array();

        if (!is_array($field_ids) || empty($field_ids)) {
            return false;
        }

        return in_array($this->field_id, array_map('absint', $field_ids), true);
    }
}
