<?php

namespace GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls;

class TermsConditions extends \GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormControls\Format
{
    public function getHtml()
    {
        $this->renderFieldStyles(array('checkbox_radio'));
        $color = $this->form_theme->getLabelColor();

        $settings = $this->item->getProp('field_settings');
        $lang = \GriffinForms\Admin\Language\Field::getInstance();

        if (!is_array($settings)) {
            $settings = array();
        }

        $checkbox_label = isset($settings['checkbox_label']) && $settings['checkbox_label'] !== ''
            ? $settings['checkbox_label']
            : $lang->getText('terms_checkbox_label', 'default');

        $anchor_text = isset($settings['anchor_text']) && $settings['anchor_text'] !== ''
            ? $settings['anchor_text']
            : $lang->getText('terms_anchor_text', 'default');

        $subtext = isset($settings['subtext']) ? $settings['subtext'] : '';

        $link_type = isset($settings['link_type']) && in_array($settings['link_type'], array('page', 'post'), true)
            ? $settings['link_type']
            : 'page';

        $page_id = isset($settings['page_id']) ? absint($settings['page_id']) : 0;
        $post_id = isset($settings['post_id']) ? absint($settings['post_id']) : 0;
        $target_id = $link_type === 'post' ? $post_id : $page_id;
        $target_url = $target_id ? get_permalink($target_id) : '';
        $open_modal = !empty($settings['open_in_modal']);

        echo '<div class="my-2 d-flex align-items-center">';
        $attributes = $this->getFieldStyleAttributes('checkbox_radio');
        echo '<input class="me-2 gf-checkbox-radio-input" type="checkbox"' . $attributes . '>';
        echo '<label class="" style="color:' . esc_attr($color) . ';">' . esc_html($checkbox_label) . '</label>';
        echo '</div>';

        if ($anchor_text !== '') {
            echo '<div class="mb-2 text-start">';
            if ($open_modal) {
                // Render modal trigger preview without actual modal markup.
                echo '<a href="#" class="griffinforms-terms-trigger-link" role="button">';
                echo esc_html($anchor_text);
                echo '</a>';
            } elseif ($target_url) {
                echo '<a class="griffinforms-terms-link" href="' . esc_url($target_url) . '" target="_blank" rel="noopener noreferrer">';
                echo esc_html($anchor_text);
                echo '</a>';
            } else {
                echo '<span class="griffinforms-terms-link text-muted">' . esc_html($anchor_text) . '</span>';
            }
            echo '</div>';
        }

        if ($subtext !== '') {
            echo '<div class="d-flex mb-2 text-start">';
            echo '<div class="text-muted small">' . esc_html($subtext) . '</div>';
            echo '</div>';
        }
    }

}
