<?php

namespace GriffinForms\Admin\Html\Elements\Submission;

class TermsConditions extends \GriffinForms\Admin\Html\Elements\Submission\Format
{
    protected $accepted = false;

    protected function setFieldValue()
    {
        $value = $this->field_value;

        if (is_array($value)) {
            $value = reset($value);
        }

        if (is_string($value)) {
            $value = trim($value);
        }

        $this->accepted = $value === '1' || $value === 1 || $value === 'accepted';
    }

    public function getHtml()
    {
        $status_text = $this->accepted
            ? $this->lang->getText('terms_status_accepted')
            : $this->lang->getText('terms_status_declined');
        $link = $this->getTermsSourceLink();

        echo '<span>' . esc_html($status_text) . '</span>';

        if ($link['url'] !== '') {
            $link_text = sprintf(
                /* translators: %s refers to the linked content title */
                __('View %s', 'griffinforms-form-builder'),
                esc_html($link['label'])
            );
            echo ' &mdash; <a class="text-primary small" href="' . esc_url($link['url']) . '" target="_blank" rel="noopener noreferrer">' . esc_html($link_text) . '</a>';
        }
    }

    private function getTermsSourceLink()
    {
        $settings = $this->field->getProp('field_settings');
        if (!is_array($settings)) {
            return array('url' => '', 'label' => '');
        }

        $link_type = isset($settings['link_type']) ? sanitize_key((string) $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;

        if ($target_id <= 0) {
            return array('url' => '', 'label' => '');
        }

        $url = get_permalink($target_id);
        if (!$url) {
            return array('url' => '', 'label' => '');
        }

        $title = get_the_title($target_id);
        if ($title === '') {
            $title = __('Terms content', 'griffinforms-form-builder');
        }

        return array(
            'url'   => $url,
            'label' => $title,
        );
    }
}
