<?php
/**
 * InflatableOffice Contact Action for Elementor Forms
 * 
 * Custom action that creates a contact/quote request in InflatableOffice 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_Contact_Action
 * 
 * Extends Elementor's Form_Action_Base to create a custom form action
 * that sends form data to InflatableOffice to create a contact/quote request.
 */
class IO_Contact_Action extends \ElementorPro\Modules\Forms\Classes\Form_Action_Base {

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

    /**
     * Get the action label (appears in the dropdown)
     * 
     * @return string
     */
    public function get_label() {
        return __('InflatableOffice Contact', '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) {
        $widget->start_controls_section(
            'section_io_contact',
            [
                'label' => __('InflatableOffice Contact', 'inflatableoffice'),
                'condition' => [
                    'submit_actions' => $this->get_name(),
                ],
            ]
        );

        $widget->add_control(
            'io_contact_notes_prefix',
            [
                'label' => __('Notes Prefix', 'inflatableoffice'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => '',
                'placeholder' => __('Optional prefix for notes', 'inflatableoffice'),
                'description' => __('Add a prefix to the notes field (optional).', 'inflatableoffice'),
            ]
        );

        $widget->add_control(
            'io_contact_create_event',
            [
                'label' => __('Create Event', 'inflatableoffice'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'inflatableoffice'),
                'label_off' => __('No', 'inflatableoffice'),
                'return_value' => 'yes',
                'default' => 'no',
                'description' => __('Automatically create an event/quote if event details are provided.', 'inflatableoffice'),
            ]
        );

        $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) {
        $settings = $record->get('form_settings');
        
        // Get form name for logging
        $form_name = $record->get_form_settings('form_name');
        
        // Get action settings
        $notes_prefix = isset($settings['io_contact_notes_prefix']) ? $settings['io_contact_notes_prefix'] : '';
        $create_event = isset($settings['io_contact_create_event']) && $settings['io_contact_create_event'] === 'yes';
        
        // Get global IO settings
        $io_pagename = get_option('io_pagename');
        $page_name = urlencode($io_pagename);
        $page_name = '&name=' . $page_name;
        $link_params = '&elemCTA=1&io_action=io_contact';
        
        // 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;
                    }
                }
            }
        }
        
        // Get customer IP address
        $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']);
        }
        
        // Build the API endpoint URL
        $link = 'https://rental.software/quotes/contactme.php?nowrap=1' . $page_name . $link_params;
        
        // Process form fields
        $fields = array();
        $raw_fields = $record->get('fields');
        
        foreach ($raw_fields as $k => $v) {
            // Map common field names
            if ($k == 'name') $k = 'firstandlastname';
            if ($k == 'message') $k = 'notes';
            
            // Skip HTML fields
            if ($v['type'] == 'html') continue;
            
            // Handle custom fields
            if (strpos($k, 'customfield_') !== FALSE) {
                $k = str_replace('customfield_', 'customfield-', $k);
            }
            
            $v = trim($v["value"]);
            
            // Non-standard fields get appended to notes
            $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 notes prefix if configured
        if (!empty($notes_prefix)) {
            if (!isset($fields['notes'])) {
                $fields['notes'] = '';
            }
            $fields['notes'] = $notes_prefix . "\n" . $fields['notes'];
        }
        
        // 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;
        
        // Send data to InflatableOffice
        $result = wp_safe_remote_post($link, [
            'body' => $fields,
            'timeout' => 20
        ]);
        
        // Handle response
        if (is_wp_error($result)) {
            $ajax_handler->add_error_message(__('Failed to submit contact form. 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);
        }
    }

    /**
     * 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
    }
}
