<?php
/**
 * InflatableOffice Action for Elementor Forms
 * 
 * Custom action that creates an InflatableOffice entity when an Elementor form is submitted.
 * This appears in the "Actions After Submit" dropdown in the Elementor form editor.
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Class IO_Entity_Action
 * 
 * Extends Elementor's Form_Action_Base to create a custom form action
 * that sends form data to InflatableOffice to create an entity.
 */
class IO_Entity_Action extends \ElementorPro\Modules\Forms\Classes\Action_Base {
    private string $brand = "InflatableOffice";
    function __construct(){
        switch(get_option('io_brand')) {
            case "EO":
                $this->brand = "EventOffice";
                break;
            case "PW":
                $this->brand = "PowerWashOffice";
                break;
            case "GCO":
                $this->brand = "GolfCartOffice";
                break;
        }

        add_action('elementor/editor/after_enqueue_styles', array($this, 'enqueue_editor_styles'));
    }
    
    /**
     * Enqueue styles for Elementor editor
     */
    public function enqueue_editor_styles() {
        wp_enqueue_style(
            'io-elementor-actions',
            plugin_dir_url(__FILE__) . 'io-elementor-actions.css',
            array(),
            '1.0.0'
        );
    }

    /**
     * Get the action name
     * 
     * @return string
     */
    public function get_name() {
        return 'io_lead';
    }

    /**
     * Get the action label (appears in the dropdown)
     * 
     * @return string
     */
    public function get_label() {
        return __($this->brand, 'inflatableoffice');
    }

    /**
     * Register action settings
     * 
     * Adds settings fields specific to this action in the Elementor editor
     * 
     * @param \Elementor\Widget_Base $widget
     */
    public function register_settings_section($widget) {
        /* TODO: have option be entity and they are Lead, Customer, Worker, and Contact. Contact is default. Uses current implementation (new_record)
                 SHow what from fields they need and give required names.
        */
        $widget->start_controls_section(
            'section_io_entity',
            [
                'label' => __($this->brand, 'inflatableoffice'),
                'condition' => [
                    'submit_actions' => $this->get_name(),
                ],
            ]
        );

        $widget->add_control(
            'io_entity_type',
            [
                'label' => __('Entity Type', 'inflatableoffice'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'contact',
                'options' => [
                    'contact' => __('Contact', 'inflatableoffice'),
                    'lead' => __('Lead', 'inflatableoffice'),
                    'customer' => __('Customer', 'inflatableoffice'),
                    #'worker' => __('Worker', 'inflatableoffice'),
                ],
                'description' => __('Choose the type of Entity you want to be created in your account.', 'inflatableoffice'),
            ]
        );

        $widget->add_control(
            'io_entity_contact_info',
            [
                'type' => \Elementor\Controls_Manager::RAW_HTML,
                'raw' => '<div class="io-entity-info-wrapper">
                            <p>This is the default behavior of the form action. This will create a lead with certain specified fields.</p>
                            <h5>Additional Fields:</h5>
                            <table class="io-entity-fields-table">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>ID</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>Ok To Text</td>
                                        <td><code class="io-code-dark">oktotext<i class="fas fa-paste io-id-paste" data="oktotext"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Start Date</td>
                                        <td><code class="io-code-dark">startdate<i class="fas fa-paste io-id-paste" data="startdate"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Start Time</td>
                                        <td><code class="io-code-dark">starttime<i class="fas fa-paste io-id-paste" data="starttime"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>End Date</td>
                                        <td><code class="io-code-dark">enddate<i class="fas fa-paste io-id-paste" data="enddate"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>End Time</td>
                                        <td><code class="io-code-dark">endtime<i class="fas fa-paste io-id-paste" data="endtime"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event Name</td>
                                        <td><code class="io-code-dark">eventname<i class="fas fa-paste io-id-paste" data="eventname"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event Street</td>
                                        <td><code class="io-code-dark">eventstreet<i class="fas fa-paste io-id-paste" data="eventstreet"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event City</td>
                                        <td><code class="io-code-dark">eventcity<i class="fas fa-paste io-id-paste" data="eventcity"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event State</td>
                                        <td><code class="io-code-dark">eventstate<i class="fas fa-paste io-id-paste" data="eventstate"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event Zip</td>
                                        <td><code class="io-code-dark">eventzip<i class="fas fa-paste io-id-paste" data="eventzip"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Delivery Type</td>
                                        <td><code class="io-code-dark">deliverytype<i class="fas fa-paste io-id-paste" data="deliverytype"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Contact Street</td>
                                        <td><code class="io-code-dark">street<i class="fas fa-paste io-id-paste" data="street"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Contact City</td>
                                        <td><code class="io-code-dark">city<i class="fas fa-paste io-id-paste" data="city"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Contact State</td>
                                        <td><code class="io-code-dark">state<i class="fas fa-paste io-id-paste" data="state"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Contact Zip</td>
                                        <td><code class="io-code-dark">zip<i class="fas fa-paste io-id-paste" data="zip"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>First Name</td>
                                        <td><code class="io-code-dark">firstname<i class="fas fa-paste io-id-paste" data="firstname"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Last Name</td>
                                        <td><code class="io-code-dark">lastname<i class="fas fa-paste io-id-paste" data="lastname"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Full Name</td>
                                        <td><code class="io-code-dark">firstandlastname<i class="fas fa-paste io-id-paste" data="firstandlastname"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Attachments</td>
                                        <td><code class="io-code-dark">attachment<i class="fas fa-paste io-id-paste" data="attachment"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Surface</td>
                                        <td><code class="io-code-dark">surface<i class="fas fa-paste io-id-paste" data="surface"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Notes</td>
                                        <td><code class="io-code-dark">notes<i class="fas fa-paste io-id-paste" data="notes"></i></code></td>
                                    </tr>
                                </tbody>
                            </table>
                          </div>',
                'condition' => [
                    'io_entity_type' => 'contact',
                ]
            ]
        );

        $widget->add_control(
            'io_entity_lead_info',
            [
                'type' => \Elementor\Controls_Manager::RAW_HTML,
                'raw' => '<div class="io-entity-info-wrapper">
                            <p>This option creates a Lead entity in your account. Note you can use eventduration instead of both eventenddate_text and eventendtime_text</p>
                            
                            <h5>Required Fields:</h5>
                            <table class="io-entity-fields-table">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>ID</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>Event Start Date</td>
                                        <td><code class="io-code-dark">eventstartdate_text<i class="fas fa-paste io-id-paste" data="eventstartdate_text"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event Start Time</td>
                                        <td><code class="io-code-dark">eventstarttime_text<i class="fas fa-paste io-id-paste" data="eventstarttime_text"></i></code></td>
                                    </tr>
                                    <tr style="border-width: 3px 3px 1px 3px; border-style: solid; border-color: #e9ecef;">
                                        <td style="border-width: 3px 1px 1px 3px; border-style: solid; border-color: #e9ecef;">Event End Date</td>
                                        <td style="border-width: 3px 3px 1px 1px; border-style: solid; border-color: #e9ecef;"><code class="io-code-dark">eventenddate_text<i class="fas fa-paste io-id-paste" data="eventenddate_text"></i></code></td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 1px 3px; border-style: solid solid dashed solid; border-color: #e9ecef;">
                                        <td style="border-width: 1px 1px 1px 3px; border-style: solid solid dashed solid; border-color: #e9ecef;">Event End Time</td>
                                        <td style="border-width: 1px 3px 1px 1px; border-style: solid solid dashed solid; border-color: #e9ecef;"><code class="io-code-dark">eventendtime_text<i class="fas fa-paste io-id-paste" data="eventendtime_text"></i></code></td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 1px 3px; border-style: dashed solid dashed solid; border-color: #e9ecef;">
                                        <td colspan="2" style="text-align: center; font-weight: bold; font-style: italic; padding: 8px; border-width: 1px 3px 1px 3px; border-style: dashed solid dashed solid; border-color: #e9ecef;">— OR —</td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 3px 3px; border-style: dashed solid solid solid; border-color: #e9ecef;">
                                        <td style="border-width: 1px 1px 3px 3px; border-style: dashed solid solid solid; border-color: #e9ecef;">Event Duration</td>
                                        <td style="border-width: 1px 3px 3px 1px; border-style: dashed solid solid solid; border-color: #e9ecef;"><code class="io-code-dark">eventduration<i class="fas fa-paste io-id-paste" data="eventduration"></i></code></td>
                                    </tr>
                                    <tr style="border-width: 3px 3px 1px 3px; border-style: solid; border-color: #e9ecef;">
                                        <td style="border-width: 3px 1px 1px 3px; border-style: solid; border-color: #e9ecef;">Contact First Name</td>
                                        <td style="border-width: 3px 3px 1px 1px; border-style: solid; border-color: #e9ecef;"><code class="io-code-dark">firstname<i class="fas fa-paste io-id-paste" data="firstname"></i></code></td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 1px 3px; border-style: solid solid dashed solid; border-color: #e9ecef;">
                                        <td style="border-width: 1px 1px 1px 3px; border-style: solid solid dashed solid; border-color: #e9ecef;">Contact Last Name</td>
                                        <td style="border-width: 1px 3px 1px 1px; border-style: solid solid dashed solid; border-color: #e9ecef;"><code class="io-code-dark">lastname<i class="fas fa-paste io-id-paste" data="lastname"></i></code></td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 1px 3px; border-style: dashed solid dashed solid; border-color: #e9ecef;">
                                        <td colspan="2" style="text-align: center; font-weight: bold; font-style: italic; padding: 8px; border-width: 1px 3px 1px 3px; border-style: dashed solid dashed solid; border-color: #e9ecef;">— OR —</td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 3px 3px; border-style: dashed solid solid solid; border-color: #e9ecef;">
                                        <td style="border-width: 1px 1px 3px 3px; border-style: dashed solid solid solid; border-color: #e9ecef;">Contact Full Name</td>
                                        <td style="border-width: 1px 3px 3px 1px; border-style: dashed solid solid solid; border-color: #e9ecef;"><code class="io-code-dark">name<i class="fas fa-paste io-id-paste" data="name"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Cell Phone</td>
                                        <td><code class="io-code-dark">cellphone<i class="fas fa-paste io-id-paste" data="cellphone"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Email</td>
                                        <td><code class="io-code-dark">email<i class="fas fa-paste io-id-paste" data="email"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event Street</td>
                                        <td><code class="io-code-dark">eventstreet<i class="fas fa-paste io-id-paste" data="eventstreet"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event City</td>
                                        <td><code class="io-code-dark">eventcity<i class="fas fa-paste io-id-paste" data="eventcity"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event State</td>
                                        <td><code class="io-code-dark">eventstate<i class="fas fa-paste io-id-paste" data="eventstate"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event Zip</td>
                                        <td><code class="io-code-dark">eventzip<i class="fas fa-paste io-id-paste" data="eventzip"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Delivery Type</td>
                                        <td><code class="io-code-dark">deliverytype<i class="fas fa-paste io-id-paste" data="deliverytype"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Surface</td>
                                        <td><code class="io-code-dark">surface<i class="fas fa-paste io-id-paste" data="surface"></i></code></td>
                                    </tr>
                                </tbody>
                            </table>
                            
                            <h5>Additional Fields:</h5>
                            <table class="io-entity-fields-table">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>ID</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>Event Name</td>
                                        <td><code class="io-code-dark">eventname<i class="fas fa-paste io-id-paste" data="eventname"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Lead Status</td>
                                        <td><code class="io-code-dark">status<i class="fas fa-paste io-id-paste" data="status"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Event Notes</td>
                                        <td><code class="io-code-dark">notes<i class="fas fa-paste io-id-paste" data="notes"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Venue Notes</td>
                                        <td><code class="io-code-dark">venuenotes<i class="fas fa-paste io-id-paste" data="venuenotes"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Venue Name</td>
                                        <td><code class="io-code-dark">venuename<i class="fas fa-paste io-id-paste" data="venuename"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Venue Contact</td>
                                        <td><code class="io-code-dark">venuecontact<i class="fas fa-paste io-id-paste" data="venuecontact"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Tax Exempt</td>
                                        <td><code class="io-code-dark">taxexempt<i class="fas fa-paste io-id-paste" data="taxexempt"></i></code></td>
                                    </tr>
                                </tbody>
                            </table>
                          </div>',
                'condition' => [
                    'io_entity_type' => 'lead',
                ]
            ]
        );

        $widget->add_control(
            'io_entity_customer_info',
            [
                'type' => \Elementor\Controls_Manager::RAW_HTML,
                'raw' => '<div class="io-entity-info-wrapper">
                            <p>This option creates a Customer entity in your account. For the customer name, you may provide either both First Name and Last Name — or a single Full Name.</p>
                            <h5>Required Fields:</h5>
                            <table class="io-entity-fields-table">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>ID</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr style="border-width: 3px 3px 1px 3px; border-style: solid; border-color: #e9ecef;">
                                        <td style="border-width: 3px 1px 1px 3px; border-style: solid; border-color: #e9ecef;">First Name</td>
                                        <td style="border-width: 3px 3px 1px 1px; border-style: solid; border-color: #e9ecef;"><code class="io-code-dark">firstname<i class="fas fa-paste io-id-paste" data="firstname"></i></code></td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 1px 3px; border-style: solid solid dashed solid; border-color: #e9ecef;">
                                        <td style="border-width: 1px 1px 1px 3px; border-style: solid solid dashed solid; border-color: #e9ecef;">Last Name</td>
                                        <td style="border-width: 1px 3px 1px 1px; border-style: solid solid dashed solid; border-color: #e9ecef;"><code class="io-code-dark">lastname<i class="fas fa-paste io-id-paste" data="lastname"></i></code></td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 1px 3px; border-style: dashed solid dashed solid; border-color: #e9ecef;">
                                        <td colspan="2" style="text-align: center; font-weight: bold; font-style: italic; padding: 8px; border-width: 1px 3px 1px 3px; border-style: dashed solid dashed solid; border-color: #e9ecef;">— OR —</td>
                                    </tr>
                                    <tr style="border-width: 1px 3px 3px 3px; border-style: dashed solid solid solid; border-color: #e9ecef;">
                                        <td style="border-width: 1px 1px 3px 3px; border-style: dashed solid solid solid; border-color: #e9ecef;">Full Name</td>
                                        <td style="border-width: 1px 3px 3px 1px; border-style: dashed solid solid solid; border-color: #e9ecef;"><code class="io-code-dark">name<i class="fas fa-paste io-id-paste" data="name"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Cell Phone</td>
                                        <td><code class="io-code-dark">cellphone<i class="fas fa-paste io-id-paste" data="cellphone"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Email</td>
                                        <td><code class="io-code-dark">email<i class="fas fa-paste io-id-paste" data="email"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Customer Type</td>
                                        <td><code class="io-code-dark">customertype<i class="fas fa-paste io-id-paste" data="customertype"></i></code></td>
                                    </tr>
                                </tbody>
                            </table>
                            <h5>Additional Fields</h5>
                            <table class="io-entity-fields-table">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>ID</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>Home Phone</td>
                                        <td><code class="io-code-dark">homephone<i class="fas fa-paste io-id-paste" data="homephone"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Office Phone</td>
                                        <td><code class="io-code-dark">officephone<i class="fas fa-paste io-id-paste" data="officephone"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Fax</td>
                                        <td><code class="io-code-dark">fax<i class="fas fa-paste io-id-paste" data="fax"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Street</td>
                                        <td><code class="io-code-dark">street<i class="fas fa-paste io-id-paste" data="street"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>City</td>
                                        <td><code class="io-code-dark">city<i class="fas fa-paste io-id-paste" data="city"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>State</td>
                                        <td><code class="io-code-dark">state<i class="fas fa-paste io-id-paste" data="state"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Zip</td>
                                        <td><code class="io-code-dark">zip<i class="fas fa-paste io-id-paste" data="zip"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Country</td>
                                        <td><code class="io-code-dark">country<i class="fas fa-paste io-id-paste" data="country"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Customer Tags</td>
                                        <td><code class="io-code-dark">custtags<i class="fas fa-paste io-id-paste" data="custtags"></i></code></td>
                                    </tr>
                                    <tr>
                                        <td>Clear Tags</td>
                                        <td><code class="io-code-dark">cleartags<i class="fas fa-paste io-id-paste" data="cleartags"></i></code></td>
                                    </tr>
                                </tbody>
                            </table>
                          </div>',
                'condition' => [
                    'io_entity_type' => 'customer',
                ]
            ]
        );

        $widget->add_control(
            'io_entity_worker_info',
            [
                'type' => \Elementor\Controls_Manager::RAW_HTML,
                'raw' => '<div class="io-entity-info-wrapper">
                            <p>This option creates a Worker entity in your account.</p>
                            <h5>Optional Fields</h5>
                            <table class="io-entity-fields-table">
                                <thead>
                                    <tr>
                                        <th>Name</th>
                                        <th>ID</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>Ok To Text</td>
                                        <td><code>okToTextPresent<i class="fas fa-paste io-id-paste" data="okToTextPresent"></i></code></td>
                                    </tr>
                                </tbody>
                            </table>
                          </div>',
                'condition' => [
                    'io_entity_type' => 'worker',
                ]
            ]
        );

        $widget->add_control(
            'io_entity_copy_script',
            [
                'type' => \Elementor\Controls_Manager::RAW_HTML,
                'raw' => '<script>
                            jQuery(document).ready(function (){
                                jQuery(".io-id-paste").click(function(){
                                    navigator.clipboard.writeText(jQuery(this).attr("data"));
                                    switch_paste_class(this);
                                    setTimeout(switch_paste_class,1500,this);
                                });
                            });
                            function switch_paste_class(icon){
                                if(jQuery(icon).hasClass("fa-paste")){
                                    jQuery(icon).toggleClass("fa-paste");
                                    jQuery(icon).toggleClass("fa-clipboard-check")
                                    jQuery(icon).css("color", "green")
                                }else if(jQuery(icon).hasClass("fa-clipboard-check")){
                                   jQuery(icon).toggleClass("fa-paste");
                                    jQuery(icon).toggleClass("fa-clipboard-check")
                                    jQuery(icon).css("color", "inherit")
                                }
                            }
                          </script>'
            ]
        );

        $widget->end_controls_section();
    }

    /**
     * Run the action after form submission
     * 
     * @param \ElementorPro\Modules\Forms\Classes\Form_Record $record
     * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $ajax_handler
     */
    public function run($record, $ajax_handler) {
        /* TODO: Depending on entity, make sure required fields are filled. Contact uses current implemtion with new_record.
                 Contact uses contactme.php and others use API Calls.
        */
        $settings = $record->get('form_settings');
        switch($settings["io_entity_type"]) {
            case "lead":
                $result = $this->handle_lead($record);
                break;
            case "customer":
                $result = $this->handle_customer($record);
                break;
            case "worker":
                #$result = $this->handle_worker($record);
                return;
            default:
                $result = $this->handle_contact($record);
                break;
        }

        
        // Handle response
        if (is_wp_error($result)) {
            $ajax_handler->add_error_message(__('Failed to create lead. Please try again.', 'inflatableoffice'));
            return;
        }
        
        $result_body = json_decode($result['body']);
        
        // Handle redirect if provided and no redirect is already set
        if (isset($result_body->redirect_url) && empty($record->get_form_settings('redirect_to'))) {
            $ajax_handler->add_response_data('redirect_url', $result_body->redirect_url);
        }
    }

    private function handle_contact($record){
        $form_name = $record->get_form_settings('form_name');

        $io_pagename = get_option('io_pagename');
        $page_name = urlencode($io_pagename);
        $page_name = '&name=' . $page_name;
        $link_params = '&elemCTA=1&io_action=io_lead';

        // IO-28339 add additional URL parameters from cookies
        $io_url_params = get_option('io_url_params');
        if ($io_url_params) {
            $io_url_params = json_decode($io_url_params);
            foreach ($io_url_params as $io_url_param) {
                if (isset($_COOKIE[$io_url_param->urlparam_cookiename])) {
                    $cookie_value = $_COOKIE[$io_url_param->urlparam_cookiename];
                    // Protect against XSS by only allowing alphanumeric characters and basic punctuation
                    if (preg_match('/^[a-zA-Z0-9\s\-_.,;:!?\'"\(\)]+$/', $cookie_value)) {
                        $link_params .= '&' . $io_url_param->urlparam_paramname . '=' . $cookie_value;
                    }
                }
            }
        }

        $cust_ip = $_SERVER['REMOTE_ADDR'];
        if (!empty($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)) {
            $cust_ip = $_SERVER['HTTP_CLIENT_IP'];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
            $cust_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        if (!empty($_SERVER['HTTP_X_SUCURI_CLIENTIP']) && filter_var($_SERVER['HTTP_X_SUCURI_CLIENTIP'], FILTER_VALIDATE_IP)) {
            $cust_ip = $_SERVER['HTTP_X_SUCURI_CLIENTIP'];
        }
        $ips = explode(',', $cust_ip, 2);
        $cust_ip = urlencode(trim($ips[0]));
        $link_params .= '&io_custip=' . $cust_ip;

        if (isset($_COOKIE['guid'])) {
            $link_params .= '&io_custguid=' . urlencode($_COOKIE['guid']);
        }

        $link = 'https://rental.software/quotes/contactme.php?nowrap=1' . $page_name . $link_params;

        $fields = array();
        $raw_fields = $record->get('fields');

        foreach ($raw_fields as $k => $v) {
            if ($k == 'name') $k = 'firstandlastname';
            if ($k == 'message') $k = 'notes';

            if ($v['type'] == 'html') continue;

            if (strpos($k, 'customfield_') !== FALSE) {
                $k = str_replace('customfield_', 'customfield-', $k);
            }

            $v = trim($v["value"]);

            $standard_fields = array(
                'okToTextPresent', 'oktotext', 'startdate', 'starttime', 'enddate', 'endtime', 'taxexempt',
                'eventname', 'salesrep', 'eventstreet', 'eventzip', 'eventcity', 'eventstate', 'deliverytype',
                'street', 'zip', 'state', 'city', 'officephone', 'custtags', 'firstandlastname', 'cellphone',
                'email', 'firstname', 'lastname', 'eventorganization', 'notes', 'title', 'attachment',
                'surface', 'elementor_statusid'
            );

            if (!in_array($k, $standard_fields) && strpos($k, 'customfield-') === FALSE) {
                if (!isset($fields['notes'])) {
                    $fields['notes'] = '';
                }
                $fields['notes'] .= "\n" . $k . ': ' . $v;
            }

            $fields[$k] = $v;
        }
        // Add form name to notes
        if (!isset($fields['notes'])) {
            $fields['notes'] = '';
        }
        $fields['notes'] = trim($fields['notes']);
        if (!empty($form_name)) {
            $fields['notes'] .= "\n\nForm: " . $form_name;
        }

        $fields['from_wp'] = 1;

        return wp_safe_remote_post($link, [
            'body' => $fields,
            'timeout' => 20
        ]);
    }

    private function handle_lead($record) {
        $raw_fields = $record->get('fields');

        // Helper to extract a trimmed value from Elementor field shape
        $getVal = function($key) use ($raw_fields) {
            if (!isset($raw_fields[$key])) {
                return '';
            }
            $field = $raw_fields[$key];
            if (is_array($field) && array_key_exists('value', $field)) {
                return trim((string)$field['value']);
            }
            if (is_string($field)) {
                return trim($field);
            }
            return '';
        };
        $starttime = $getVal("eventstarttime_text");
        $endtime = $getVal("eventendtime_text");
        $startdate = $getVal("eventstartdate_text");
        $enddate = $getVal("eventenddate_text");
        $duration = $getVal("eventduration");
        $firstname = $getVal('firstname');
        $lastname = $getVal('lastname');
        $cellphone = $getVal('cellphone');
        $email = $getVal('email');
        $fullname = $getVal('name');
        $street = $getVal('eventstreet');
        $city = $getVal('eventcity');
        $zip = $getVal('eventzip');
        $state = $getVal('eventstate');
        $deliverytype = $getVal('deliverytype');
        $surface = $getVal('surface');

        $missing = [];

        $hasFirstLast = ($firstname !== '' && $lastname !== '');
        $hasFull = ($fullname !== '');
        if (!$hasFirstLast && !$hasFull) {
            // Use a grouped message to be clearer for the user
            $missing[] = __('First Name and Last Name, or Full Name', 'inflatableoffice');
        }

        $hasEndDateTime = ($endtime !== '' && $enddate !== '');
        $hasDuration = ($duration !== '');
        if (!$hasEndDateTime && !$hasDuration) {
            // Use a grouped message to be clearer for the user
            $missing[] = __('End Date and Time or Duration', 'inflatableoffice');
        }

        if ($starttime === '') {
            $missing[] = 'Start Time';
        }
        if ($startdate === '') {
            $missing[] = 'Start Date';
        }
        if ($cellphone === '') {
            $missing[] = 'Cell Phone';
        }
        if ($email === '') {
            $missing[] = 'Email';
        }
        if ($street === '') {
            $missing[] = 'Street';
        }
        if ($city === '') {
            $missing[] = 'City';
        }
        if ($zip === '') {
            $missing[] = 'Zip';
        }
        if ($state === '') {
            $missing[] = 'State';
        }
        if($deliverytype === ''){
            $missing[] = 'Delivery Type';
        }
        if($surface === ''){
            $missing[] = 'Surface';
        }

        if (!empty($missing)) {
            $msg = sprintf(
            /* translators: %s is a comma-separated list of missing field labels */
                __('Please complete the following required field(s): %s', 'inflatableoffice'),
                implode(', ', $missing)
            );
            return new \WP_Error('io_required_fields_missing', $msg);
        }

        $body = [];
        if ($firstname !== '') { $body['firstname'] = $firstname; }
        if ($lastname !== '') { $body['lastname'] = $lastname; }
        if ($fullname !== '') { $body['name'] = $fullname; }
        if ($endtime !== '') { $body['eventendtime_text'] = $endtime; }
        if ($enddate !== '') { $body['eventenddate_text'] = $enddate; }
        if ($duration !== '') { $body['eventduration'] = $duration; }
        $body['eventstarttime_text'] = $starttime;
        $body['eventstartdate_text'] = $startdate;
        $body['cellphone'] = $cellphone;
        $body['email'] = $email;
        $body['eventstreet'] = $street;
        $body['eventcity'] = $city;
        $body['eventzip'] = $zip;
        $body['eventstate'] = $state;
        $body['deliverytype'] = $deliverytype;
        $body['surface'] = $surface;

        // Optional fields
        $body['venue_name'] = $getVal('venue_name');
        $body['status'] = $getVal('status');
        $body['notes'] =  $getVal('notes');
        $body['venuenotes'] = $getVal('venuenotes');
        $body['venuename'] = $getVal('venuename');
        $body['venuecontact'] = $getVal('venuecontact');
        $body['taxexempt'] = $getVal('taxexempt');
        $body['rentals'] = $getVal('rentals');

        $api_key = get_option('io_lead_apikey');
        $url = "https://rental.software/api6/leads/?apiKey=$api_key";

        return wp_safe_remote_post($url, [
            'body' => $body,
            'timeout' => 20
        ]);
    }

    private function handle_worker($record){
        
    }

    private function handle_customer($record){
        // Validate required customer fields from the Elementor form record
        // Name fields are OR: (firstname AND lastname) OR (name)
        // Other required fields: cellphone, email, customertype
        $raw_fields = $record->get('fields');

        // Helper to extract a trimmed value from Elementor field shape
        $getVal = function($key) use ($raw_fields) {
            if (!isset($raw_fields[$key])) {
                return '';
            }
            $field = $raw_fields[$key];
            if (is_array($field) && array_key_exists('value', $field)) {
                return trim((string)$field['value']);
            }
            if (is_string($field)) {
                return trim($field);
            }
            return '';
        };

        $firstname = $getVal('firstname');
        $lastname = $getVal('lastname');
        $fullname = $getVal('name');
        $cellphone = $getVal('cellphone');
        $email = $getVal('email');
        $customertype = $getVal('customertype');

        $missing = [];

        // Validate name group: require either both first+last OR full name
        $hasFirstLast = ($firstname !== '' && $lastname !== '');
        $hasFull = ($fullname !== '');
        if (!$hasFirstLast && !$hasFull) {
            // Use a grouped message to be clearer for the user
            $missing[] = __('First Name and Last Name, or Full Name', 'inflatableoffice');
        }

        if ($cellphone === '') {
            $missing[] = 'Cell Phone';
        }
        if ($email === '') {
            $missing[] = 'Email';
        }
        if ($customertype === '') {
            $missing[] = 'Customer Type';
        }

        if (!empty($missing)) {
            $msg = sprintf(
                /* translators: %s is a comma-separated list of missing field labels */
                __('Please complete the following required field(s): %s', 'inflatableoffice'),
                implode(', ', $missing)
            );
            return new \WP_Error('io_required_fields_missing', $msg);
        }

        // Build request body (include provided fields only). If only full name was provided,
        // we still pass it through as 'name'. If first/last provided, send them individually,
        // and include full name as given as well if present.
        $body = [];
        if ($firstname !== '') { $body['firstname'] = $firstname; }
        if ($lastname !== '') { $body['lastname'] = $lastname; }
        if ($fullname !== '') { $body['name'] = $fullname; }
        $body['cellphone'] = $cellphone;
        $body['email'] = $email;
        $body['customertype'] = $customertype;

        // Optional fields (pass through when provided)
        $homephone   = $getVal('homephone');
        $officephone = $getVal('officephone');
        $fax         = $getVal('fax');
        $street      = $getVal('street');
        $city        = $getVal('city');
        $state       = $getVal('state');
        $zip         = $getVal('zip');
        $country     = $getVal('country');
        $custtags    = $getVal('custtags');
        $cleartags   = $getVal('cleartags');

        if ($homephone   !== '') { $body['homephone']   = $homephone; }
        if ($officephone !== '') { $body['officephone'] = $officephone; }
        if ($fax         !== '') { $body['fax']         = $fax; }
        if ($street      !== '') { $body['street']      = $street; }
        if ($city        !== '') { $body['city']        = $city; }
        if ($state       !== '') { $body['state']       = $state; }
        if ($zip         !== '') { $body['zip']         = $zip; }
        if ($country     !== '') { $body['country']     = $country; }
        if ($custtags    !== '') { $body['custtags']    = $custtags; }
        if ($cleartags   !== '') { $body['cleartags']   = $cleartags; }

        $api_key = get_option('io_lead_apikey');
        $url = "https://rental.software/api6/customers/?apiKey=$api_key";


        return wp_safe_remote_post($url, [
            'body' => $body,
            'timeout' => 20
        ]);
    }


    /**
     * Register the action on form submit
     * 
     * @param \ElementorPro\Modules\Forms\Registrars\Form_Actions_Registrar $form_actions_registrar
     */
    public function on_export($element) {
        // Nothing to export for this action
    }
}
