<?php

namespace GriffinForms\Frontend\Ajax;

class Terms extends \GriffinForms\Frontend\Format
{
    public function __construct()
    {
        $this->setAll();
        add_action('wp_ajax_griffinformsFetchTerms', array($this, 'fetchTerms'));
        add_action('wp_ajax_nopriv_griffinformsFetchTerms', array($this, 'fetchTerms'));
    }

    public function fetchTerms()
    {
        $response = array(
            'success' => false,
            'content' => '',
            'message' => __('Unable to load terms content.', 'griffinforms-form-builder'),
        );

        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';

        if (!wp_verify_nonce($nonce, 'griffinforms_fetch_terms')) {
            $this->log->add('warning', 'field', 0, get_current_user_id(), 'Terms fetch failed nonce validation.', 'terms');
            wp_send_json($response);
        }

        $field_id = isset($_POST['field_id']) ? absint(wp_unslash($_POST['field_id'])) : 0;
        $source_type = isset($_POST['source_type']) ? sanitize_key(wp_unslash($_POST['source_type'])) : '';
        $source_id = isset($_POST['source_id']) ? absint(wp_unslash($_POST['source_id'])) : 0;

        if ($field_id === 0 || $source_id === 0 || !in_array($source_type, array('page', 'post'), true)) {
            $this->log->add('error', 'field', $field_id, get_current_user_id(), 'Invalid parameters supplied to Terms fetch.', 'terms');
            wp_send_json($response);
        }

        $sql = \GriffinForms\Frontend\Sql\Field::getInstance();

        if (!$sql->itemExists('field', $field_id)) {
            $this->log->add('error', 'field', $field_id, get_current_user_id(), 'Terms fetch attempted for non-existent field.', 'terms');
            wp_send_json($response);
        }

        $field = new \GriffinForms\Items\Field();
        $field->loadItem($field_id);

        if ($field->getProp('field_type') !== 'termsconditions') {
            $this->log->add('error', 'field', $field_id, get_current_user_id(), 'Terms fetch attempted on non-terms field.', 'terms');
            wp_send_json($response);
        }

        $settings = $field->getProp('field_settings');
        $expected_id = 0;

        if (is_array($settings)) {
            $stored_type = isset($settings['link_type']) ? sanitize_key($settings['link_type']) : 'page';
            if ($stored_type === 'post') {
                $expected_id = isset($settings['post_id']) ? absint($settings['post_id']) : 0;
            } else {
                $expected_id = isset($settings['page_id']) ? absint($settings['page_id']) : 0;
            }
        }

        if ($expected_id !== $source_id) {
            $this->log->add('warning', 'field', $field_id, get_current_user_id(), 'Terms fetch source mismatch detected.', 'terms');
            wp_send_json($response);
        }

        $post = get_post($source_id);

        if (!$post || $post->post_status !== 'publish') {
            $this->log->add('error', 'field', $field_id, get_current_user_id(), 'Terms fetch failed due to missing or unpublished content.', 'terms');
            wp_send_json($response);
        }

        $content = apply_filters('the_content', $post->post_content);
        $content = wp_kses_post($content);

        if (!preg_match('/<\s*(p|br|div|section|article|ul|ol|li|table|blockquote|figure|h[1-6])\b/i', $content)) {
            $content = wpautop($content, false);
        }

        $content = preg_replace('/\s*<p>\s*<\/p>\s*/i', '', $content);
        $content = preg_replace('/(?:<br\\s*\\/?>\\s*){2,}/i', '<br />', $content);

        $response['success'] = true;
        $response['content'] = $content;
        $response['message'] = '';

        wp_send_json($response);
    }
}
