<?php

namespace PWH_DCFH\App\Frontend\DiviContactForm\Features;

use DOMException;
use PWH_DCFH\App\Controllers\PWH_DCFH_DOM;
use DOMXPath;
use PWH_DCFH\App\Frontend\Request\PWH_DCFH_Post_Repository;

if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('PWH_DCFH_Modify_Form')) {
    class PWH_DCFH_Modify_Form
    {
        public $render_slug;

        public $output;

        public $props = [];

        public $contact_form_order_class;

        public $contact_form_index;

        /**
         * Class Constructor
         */
        public function __construct($render_slug, $output, $props)
        {
            $this->render_slug = $render_slug;
            $this->output = $output;
            $this->props = $props;
        }

        /**
         * Update Form Conatiner DOM
         * @throws DOMException
         * @return false|string
         */
        public function filter_form_container_dom()
        {
            $dom = PWH_DCFH_DOM::dom($this->output);
            $dom_xpath = new DOMXPath($dom);
            $form_container = $dom_xpath->query('//div[contains(@class,"'.$this->contact_form_order_class.'")]');
            $post_repository = PWH_DCFH_Post_Repository::instance();
            if (isset($form_container->length) && 0 !== $form_container->length) {
                $form_container_item = $form_container->item(0);
                /*
                * Add form_unique_id attribute to a contact form div
                *
                * If divi is older than 4.13.1
                *
                * @since 1.0.0
                * */
                if (!pwh_dcfh_wp_helpers()::is_divi_4131_or_above()) {
                    $form_container_item->setAttribute('data-form_unique_id', $this->props['_unique_id']);
                    $this->output = $dom->saveHTML();
                }
                // Add Loading Icon Div
                if (isset($this->props['show_loading_icon']) && 'on' === $this->props['show_loading_icon'] && !$post_repository->is_threshold_reached) {
                    $overlay_div = $dom->createElement('div');
                    $overlay_div->setAttribute('class', 'et_pb_contact_form_overlay');
                    $form_container_item->appendChild($overlay_div);
                    $spinner_div = $dom->createElement('div');
                    $spinner_div->setAttribute('class', 'et_pb_contact_form_loader_spinner');
                    $overlay_div->appendChild($spinner_div);
                    $this->output = $dom->saveHTML();
                }
                // Spinner
                $et_pb_contact_message = $dom_xpath->query('//div[contains(@class,"et-pb-contact-message")]');
                if ($et_pb_contact_message->length > 0 && !$post_repository->is_threshold_reached) {
                    $spinner_ele = $dom->createElement('span');
                    $spinner_ele->setAttribute('class', 'et_pb_contact_spinner');
                    $target_div = $et_pb_contact_message->item(0);
                    $target_div->parentNode->insertBefore($spinner_ele, $target_div);
                    $this->output = $dom->saveHTML();
                }
                // Form Threshold Handle
                if ($post_repository->is_threshold_reached) {
                    $threshold_message = !empty($this->props['entries_threshold_message']) ? $this->props['entries_threshold_message'] : '';
                    $et_pb_contact = $dom_xpath->query('//div[contains(@class,"'.$this->contact_form_order_class.'")]//div[@class="et_pb_contact"]');
                    if ($et_pb_contact->length > 0) {
                        $et_pb_contact_heading = $dom_xpath->query('//div[contains(@class,"'.$this->contact_form_order_class.'")]//h1[@class="et_pb_contact_main_title"]');
                        if (isset($et_pb_contact_heading->length) && $et_pb_contact_heading->length > 0) {
                            $et_pb_contact_heading->item(0)->remove();
                        }
                        $et_pb_contact_item = $et_pb_contact->item(0);
                        $et_pb_contact_item->parentNode->removeChild($et_pb_contact_item);
                        $this->output = $dom->saveHTML();
                    }
                    if (!empty($threshold_message)) {
                        $threshold_div = $dom->createElement('div');
                        $threshold_div->setAttribute('class', 'et_pb_contact_threshold_message');
                        $form_container_item->appendChild($threshold_div);
                        $threshold_div->appendChild($dom->createCDATASection($threshold_message));
                        $this->output = $dom->saveHTML();
                    }
                }
            }

            return $this->output;
        }

        /**
         * Update Form DOM
         * @throws DOMException
         * @return false|string
         */
        public function filter_form_dom()
        {
            $post_repository = PWH_DCFH_Post_Repository::instance();
            $dom = PWH_DCFH_DOM::dom($this->output);
            $form = $dom->getElementsByTagName('form');
            if ($form->length) {
                $form_item = $form->item(0);
                // Add Cookie Attr
                if (isset($this->props['save_entries_to_db'])
                    && 'on' === $this->props['save_entries_to_db']
                    && isset($this->props['unique_views_cookie'])
                    && 'on' === $this->props['unique_views_cookie']) {
                    $form_item->setAttribute('data-unique-views-cookies', 'on');
                    $this->output = $dom->saveHTML();
                }
                // Add Redirect Data Attrs
                if (isset($this->props['custom_use_redirect']) && 'on' === $this->props['custom_use_redirect']) {
                    $redirect_url = '';
                    $custom_redirect_to = isset($this->props['custom_redirect_to']) ? $this->props['custom_redirect_to'] : 'url';
                    $custom_redirect_url = isset($this->props['custom_redirect_url']) ? $this->props['custom_redirect_url'] : null;
                    $custom_redirect_page = isset($this->props['custom_redirect_page']) ? $this->props['custom_redirect_page'] : null;
                    $custom_redirect_delay = isset($this->props['custom_redirect_delay']) ? $this->props['custom_redirect_delay'] : '3000';
                    if ('url' === $custom_redirect_to && !empty($custom_redirect_url)) {
                        $redirect_url = $custom_redirect_url;
                    }
                    if ('page' === $custom_redirect_to && !empty($custom_redirect_page)) {
                        $redirect_url = get_the_permalink(intval($custom_redirect_page));
                    }
                    if (!empty($redirect_url)) {
                        $form_item->setAttribute('data-redirect-url', $redirect_url);
                        $form_item->setAttribute('data-redirect-delay', $custom_redirect_delay);
                        $this->output = $dom->saveHTML();
                    }
                }
                // Add Honeypot Hidden Input
                if (isset($this->props['use_honeypot']) && 'on' === $this->props['use_honeypot']) {
                    $hp_label = $dom->createElement('label');
                    $hp_label->setAttribute('aria-hidden', 'true');
                    $hp_input = $dom->createElement('input');
                    $hp_input->setAttribute('type', 'radio');
                    $hp_input->setAttribute('name', 'et_pb_contact_hp_field_'.$this->contact_form_index);
                    $hp_input->setAttribute('id', 'et_pb_contact_hp_field_'.$this->contact_form_index);
                    $hp_input->setAttribute('tabindex', -1);
                    $hp_input->setAttribute('value', 'on');
                    $hp_label->appendChild($hp_input);
                    $form_item->appendChild($hp_label);
                    $this->output = $dom->saveHTML();
                }
                // Referrer URL
                $referer_url = isset($_SERVER['HTTP_REFERER']) ? sanitize_text_field($_SERVER['HTTP_REFERER']) : '';
                $ru_input = $dom->createElement('input');
                $ru_input->setAttribute('type', 'hidden');
                $ru_input->setAttribute('name', 'et_pb_contact_field_referer_url');
                $ru_input->setAttribute('value', $referer_url);
                $form_item->appendChild($ru_input);
                $this->output = $dom->saveHTML();
            }
            // Google reCAPTCHA V2
            $googlerecaptcha_enabled = $post_repository->is_googlerecaptcha_v2_enabled;
            $googlerecaptcha_sitekey = et_get_option('pwh_dcfh_googlerecaptcha_v2_sitekey');
            $googlerecaptcha_secretkey = et_get_option('pwh_dcfh_googlerecaptcha_v2_secretkey');
            if ($googlerecaptcha_enabled && !empty($googlerecaptcha_sitekey) && !empty($googlerecaptcha_secretkey)) {
                $this->add_captcha($dom, $googlerecaptcha_sitekey, 'g-recaptcha et_pb_g_recaptcha', 'et_pb_contact_g_recaptcha_token');
            }
            // Cloudflare Turnstile
            $turnstile_enabled = $post_repository->is_cloudflare_turnstile_enabled;
            $turnstile_sitekey = et_get_option('pwh_dcfh_turnstile_sitekey');
            $turnstile_secretkey = et_get_option('pwh_dcfh_turnstile_secretkey');
            if ($turnstile_enabled && !empty($turnstile_sitekey) && !empty($turnstile_secretkey)) {
                $this->add_captcha($dom, $turnstile_sitekey, 'et_pb_cf_turnstile', 'et_pb_contact_ct_token');
            }

            return $this->output;
        }

        /**
         * Add Captcha DOM
         *
         * @param $dom
         * @param $sitekey
         * @param $captcha_class
         * @param $token_name
         *
         * @return void
         */
        private function add_captcha($dom, $sitekey, $captcha_class, $token_name)
        {
            $dom_xpath = new DOMXPath($dom);
            $bottom_container = $dom_xpath->query("//div[contains(@class,'et_contact_bottom_container')]");
            if ($bottom_container->length > 0) {
                $bottom_container_item = $bottom_container->item(0);
                $captcha_container = $dom->createElement('div');
                $captcha_container->setAttribute('id', "{$captcha_class}_$this->contact_form_index");
                $captcha_container->setAttribute('class', $captcha_class);
                $captcha_container->setAttribute('data-sitekey', $sitekey);
                $bottom_container_item->parentNode->insertBefore($captcha_container, $bottom_container_item);
                $captcha_input = $dom->createElement('input');
                $captcha_input->setAttribute('type', 'hidden');
                $captcha_input->setAttribute('name', "{$token_name}_$this->contact_form_index");
                $captcha_input->setAttribute('value', '');
                $bottom_container_item->parentNode->insertBefore($captcha_input, $bottom_container_item);
                $this->output = $dom->saveHTML();
            }
        }
    }
}