<?php

namespace Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\ActionsAfterSubmit;

use ElementorPro\Modules\Forms\Classes\Action_Base;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\CrmFields;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\Helper;
use Itgalaxy\Elementor\Form\Infusionsoft\Integration\Includes\RenderFields;

class ContactActionAfterSubmit extends Action_Base
{
    public function get_name()
    {
        return 'infusionsoft_contact';
    }

    public function get_tabs_name()
    {
        return $this->get_name() . '_tabs';
    }

    public function get_label()
    {
        return esc_html__('Infusionsoft (Contact)', 'el-pro-form-infusionsoft-integration');
    }

    public function run($record, $ajax_handler)
    {
        $recordSettings = $record->get('form_settings');
        $sendFields = [];
        $crmFields = [];

        Helper::log('(' . $this->get_name() . ') send event form start - ' . $recordSettings['id']);

        $fields = new CrmFields();

        $crmFields['contact'] = $fields->contact;
        $sendFields['contact'] = Helper::resolveFieldValues($crmFields['contact'], $record, 'contact_');

        if (empty($sendFields['contact'])) {
            Helper::log('empty contact data', $sendFields);

            return;
        }

        $sendFields['send_type'] = 'create_update';

        if (isset($recordSettings['el_pro_infusionsoft_contact_send_type'])) {
            $sendFields['send_type'] = $recordSettings['el_pro_infusionsoft_contact_send_type'];
        }

        if (!empty($recordSettings['el_pro_infusionsoft_contact_tags'])) {
            $tags = $record->replace_setting_shortcodes(trim($recordSettings['el_pro_infusionsoft_contact_tags']));
            $tags = Helper::replaceAdditionalTags($tags, $recordSettings);

            if ($tags) {
                $sendFields['tags'] = $tags;
            }
        }

        if (!empty($recordSettings['el_pro_infusionsoft_contact_opt_in_reason'])) {
            $reason = $record->replace_setting_shortcodes(trim($recordSettings['el_pro_infusionsoft_contact_opt_in_reason']));
            $reason = Helper::replaceAdditionalTags($reason, $recordSettings);

            if (!empty($reason)) {
                $sendFields['contact']['opt_in_reason'] = $reason;
            }
        }

        if (!empty($recordSettings['el_pro_infusionsoft_contact_note_contact'])) {
            $note = $record->replace_setting_shortcodes(trim($recordSettings['el_pro_infusionsoft_contact_note_contact']));
            $note = Helper::allFieldsShortcode($note, $record);
            $note = Helper::replaceAdditionalTags($note, $recordSettings);

            if ($note) {
                $sendFields['note'] = $note;
            }
        }

        if (
            isset($recordSettings['el_pro_infusionsoft_contact_send_files'])
            && $recordSettings['el_pro_infusionsoft_contact_send_files'] === 'yes'
            && !empty($record->get('files'))
        ) {
            $sendFields['uploads'] = Helper::resolveFilesList($record);
        }

        $contactResult = Helper::sendProcess($sendFields, $recordSettings, 'contact', $recordSettings['id']);

        Helper::log('(' . $this->get_name() . ') send event form end - ' . $recordSettings['id']);

        /**
         * The action allows to organize custom behavior after data delivery to Keep.
         *
         * If is used send_type=wp_cron, then variable $contactResult will be empty, since the send is delayed.
         *
         * @since 1.4.0
         *
         * @param \ElementorPro\Modules\Forms\Classes\Form_Record  $record
         * @param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $ajax_handler
         * @param array                                            $contactResult
         */
        do_action('itglx/elpro/keap/after-contact-action', $record, $ajax_handler, $contactResult);
    }

    public function register_settings_section($widget)
    {
        $widget->start_controls_section(
            'section_' . $this->get_name(),
            [
                'label' => $this->get_label(),
                'condition' => [
                    'submit_actions' => $this->get_name(),
                ],
            ]
        );

        $widget->start_controls_tabs($this->get_tabs_name());

        $widget->start_controls_tab(
            $this->get_tabs_name() . '_main_fields',
            [
                'label' => esc_html__('Main', 'el-pro-form-infusionsoft-integration'),
            ]
        );

        $renderFields = new RenderFields('contact_');

        $renderFields->inputCheckboxField(
            $widget,
            'send_files',
            esc_html__('Send uploaded files', 'el-pro-form-infusionsoft-integration'),
            ['isRequired' => false]
        );

        $renderFields->selectField(
            $widget,
            [
                'create' => esc_html__('Create', 'el-pro-form-infusionsoft-integration'),
                'create_update' => esc_html__('Create or Update (if found by email)', 'el-pro-form-infusionsoft-integration'),
            ],
            'send_type',
            esc_html__('Send method', 'el-pro-form-infusionsoft-integration')
        );

        $renderFields->inputTextField(
            $widget,
            'tags',
            esc_html__('Tags', 'el-pro-form-infusionsoft-integration'),
            [
                'isRequired' => false,
            ]
        );

        $renderFields->inputTextField(
            $widget,
            'opt_in_reason',
            esc_html__('Opt-in Reason', 'el-pro-form-infusionsoft-integration'),
            [
                'isRequired' => false,
                'description' => esc_html__('Keap API info: You can use this for opt-in or mark a Contact as Marketable. The reason you provide here will help with compliance. Example reasons: "Customer opted-in through webform", "Contact gave explicit permission."', 'el-pro-form-infusionsoft-integration'),
            ]
        );

        $crmFields = new CrmFields();

        $fields = $crmFields->contact;

        foreach ($fields as $key => $field) {
            $renderFields->inputTextField(
                $widget,
                $key,
                $field['label'],
                $field
            );
        }

        $widget->end_controls_tab();

        $widget->start_controls_tab(
            $this->get_tabs_name() . '_custom_fields',
            [
                'label' => esc_html__('Custom', 'el-pro-form-infusionsoft-integration'),
            ]
        );

        $renderFields->showCustomFields($widget, $renderFields);

        $widget->end_controls_tab();

        $widget->start_controls_tab(
            $this->get_tabs_name() . '_note_fields',
            [
                'label' => esc_html__('Note', 'el-pro-form-infusionsoft-integration'),
            ]
        );

        $renderFields->textareaField(
            $widget,
            'note_contact',
            esc_html__('Note text', 'el-pro-form-infusionsoft-integration'),
            [
                'isRequired' => false,
                'label_block' => true,
            ]
        );

        $widget->end_controls_tab();

        $widget->end_controls_tabs();

        $widget->end_controls_section();
    }

    public function on_export($element)
    {
        // Nothing
    }
}
