<?php

namespace PWH_DCFH\App\Admin\Controllers;

if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('PWH_DCFH_ET_Ajax_Request')) {
    class PWH_DCFH_ET_Ajax_Request
    {
        /**
         * Initializer Of The Class
         * Add/Remove Necessary Actions/Filters
         */
        public function init()
        {
            add_action('wp_ajax_et_fb_ajax_save', [$this, 'maybe_et_ajax_request'], 10);
        }

        /**
         * ET FB Ajax Request
         * @return void
         */
        public function maybe_et_ajax_request()
        {
            $options = $_POST['options'] ?? []; // phpcs:ignore
            $layout_type = isset($_POST['layout_type']) ? sanitize_text_field($_POST['layout_type']) : ''; // phpcs:ignore
            $shortcode_data = isset($_POST['modules']) ? json_decode(stripslashes($_POST['modules']), true) : []; // phpcs:ignore
            $shortcode = et_fb_process_to_shortcode($shortcode_data, $options, $layout_type, true, false);
            if (preg_match('/\[et_pb_contact_form[^\]]*\]/', $shortcode) && preg_match('/\[et_pb_contact_field[^\]]*\]/', $shortcode)) {
                preg_match('/_unique_id="([^"]+)"/', $shortcode, $form_matches);
                $unique_id = $form_matches[1] ?? '';
                if (!empty($unique_id)) {
                    preg_match_all('/field_id="([^"]+)"[^"]+field_title="([^"]+)"/', $shortcode, $fields_matches, PREG_SET_ORDER);
                    $form_fields = [];
                    if (!empty($fields_matches)) {
                        foreach ($fields_matches as $field) {
                            $form_fields[] = [
                                'id' => $field[1],
                                'name' => $field[2],
                            ];
                        }
                    }
                    $option_key = "_pwh_dcfh_contact_form_settings_$unique_id";
                    $old_options = get_option($option_key);
                    $options = [
                        'unique_id' => $unique_id,
                        'fields' => $form_fields,
                    ];
                    $options = wp_parse_args($options, $old_options);
                    update_option($option_key, $options, 'no');
                }
            }
        }
    }
}