<?php

defined( 'ABSPATH' ) || exit;

use HelpGent\Hidehalo\Nanoid\Client as Nanoid;
use HelpGent\App\Support\Element\Fields\Date;
use HelpGent\App\Support\Element\Fields\FileUpload;
use HelpGent\App\Support\Element\Fields\GDPR;
use HelpGent\App\Support\Element\Fields\OpenEnded;
use HelpGent\App\Support\Element\Fields\LiveChat;
use HelpGent\App\Support\Element\Fields\RatingStar;
use HelpGent\App\Utils\DateTime;
use HelpGent\App\Repositories\OptionRepository;
use HelpGent\App\Repositories\SettingsRepository;
use HelpGent\App\Repositories\SiteVerificationRepository;
use HelpGent\App\Repositories\FormRepository;
use HelpGent\App\Repositories\ResponseRepository;
use HelpGent\App\Support\Element\Element;
use HelpGent\App\Licensing\License;
use HelpGent\WpMVC\Database\Query\Builder;
use HelpGent\App\Support\Element\Fields\PromoterScore;
use HelpGent\App\Support\Element\Fields\SingleSelect;

require_once __DIR__ . '/core.php';
require_once __DIR__ . '/media.php';
require_once __DIR__ . '/user.php';

function helpgent_now() {
    return DateTime::now();
}

function helpgent_is_valid_date( string $date, string $format ) {
    $date_time = \DateTime::createFromFormat( $format, $date );
    return $date_time && $date_time->format( $format ) === $date;
}

function helpgent_generate_token() {
    $time   = microtime( true );
    $random = bin2hex( random_bytes( 5 ) );
    $token  = $random . $time;
    return $token;
}

function helpgent_generate_unique_key( string $prefix = '' ) {
    return $prefix . '_' . uniqid();
}

function helpgent_generate_unique_file_name( string $file_name ) {
    $nanoid = new Nanoid();

    $name = pathinfo( $file_name, PATHINFO_FILENAME ) . '_' . $nanoid->generateId();
    $ext  = pathinfo( $file_name, PATHINFO_EXTENSION );
    $ext  = ! empty( $ext ) ? ".{$ext}" : '';

    return wp_unique_filename( helpgent_upload_dir(), helpgent_trim_file_name( "{$name}{$ext}" ) );
}

function helpgent_trim_file_name( string $file_name, int $max_length = 100 ): string {
    if ( ! strlen( $file_name ) ) {
        return '';
    }

    if ( ! $max_length ) {
        return '';
    }

    preg_match( '/\.[a-zA-Z0-9]+$/', $file_name, $ext_matches );

    $ext = ! empty( $ext_matches ) ? $ext_matches[0] : '';

    $max_name_length = $ext ? $max_length - strlen( $ext ) : $max_length;
    $max_name_length = $max_name_length < 1 ? 1 : $max_name_length;

    $name_length = strlen( $file_name ) - strlen( $ext );

    $name_with_no_extension = substr( $file_name, 0, $name_length );
    $name_with_no_extension = substr( $name_with_no_extension, 0, $max_name_length );

    $new_file_name = "{$name_with_no_extension}{$ext}";

    return $new_file_name;
}

function helpgent_get_setting( string $key, $default = null ) {
    /**
     * @var SettingsRepository $setting_repository
     */
    $setting_repository = helpgent_singleton( SettingsRepository::class );
    return $setting_repository->get_by_key( $key, $default );
}

function helpgent_update_setting( string $key, $value ) {
     /**
     * @var SettingsRepository $setting_repository
     */
    $setting_repository = helpgent_singleton( SettingsRepository::class );
    return $setting_repository->update_setting( $key, $value );
}

function helpgent_get_current_page_id() {
    $page_id = 0;

    // Check if we are on a WooCommerce page
    if ( function_exists( 'is_woocommerce' ) ) {
        if ( is_cart() ) {
            $page_id = wc_get_page_id( 'cart' );
        } elseif ( is_checkout() ) {
            $page_id = wc_get_page_id( 'checkout' );
        } elseif ( is_account_page() ) {
            $page_id = wc_get_page_id( 'myaccount' );
        } elseif ( is_shop() ) {
            $page_id = wc_get_page_id( 'shop' );
        }
    }

    if ( $page_id === 0 ) {
        $page_id = get_queried_object_id();
    }

    return $page_id;
}

function helpgent_get_extension_from_path( string $path ) : string {
    return pathinfo( $path, PATHINFO_EXTENSION );
}

/**
 * Get current user ip address
 *
 * @return string|null
 */
function helpgent_get_user_ip_address() {
    // Check for shared Internet/ISP IP
    if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) && filter_var( $_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP ) ) { //phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        return sanitize_text_field( wp_unslash( $_SERVER['HTTP_CLIENT_IP'] ) );
    }

    // Check for IP addresses passed by proxies
    if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { //phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        // Extract IP addresses
        $ip_addresses = explode(
            ',', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
        );

        // Check each IP address
        foreach ( $ip_addresses as $ip ) {
            $ip = trim( $ip );
            if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) {
                return $ip;
            }
        }
    }

    // Check for the remote IP address
    if ( ! empty( $_SERVER['REMOTE_ADDR'] ) && filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP ) ) { //phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        return sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
    }

    return null;
}

function helpgent_get_server_name() {
    global $is_apache;

    if ( $is_apache ) {
        return 'apache';
    }

    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $server_info = isset( $_SERVER['SERVER_SOFTWARE'] ) ? wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) : '';

    $servers = [
        'nginx',
        'iis',
    ];

    foreach ( $servers as $server ) {
        if ( strpos( strtolower( $server_info ), $server ) !== false ) {
            return $server;
        }
    }

    return '';
}

function helpgent_is_one_level_array( array $array ) {
    foreach ( $array as $value ) {
        if ( is_array( $value ) ) {
            return false; // Contains nested array
        }
    }
    return true; // Valid one-level array
}

/**
 * Get value form nested array
 *
 * @param string $keys Comma separated array keys
 * @param array $values
 * @param mixed $default
 * @return mixed
 */
function helpgent_get_nested_value( string $keys, array $values, $default = null ) {
    $keys = explode( '.', $keys );

    $item = $values;

    foreach ( $keys as $key ) {
        if ( ! isset( $item[ $key ] ) ) {
            return $default;
        }
        $item = $item[$key];
    }
    return $item;
}

function helpgent_allowed_elements_on_submission(): array {
    return apply_filters( 'helpgent_allowed_elements_on_submission', [OpenEnded::get_key(), Date::get_key(), GDPR::get_key(), FileUpload::get_key(), LiveChat::get_key(), RatingStar::get_key(), PromoterScore::get_key(), SingleSelect::get_key()] );
}

function helpgent_get_dashboard_page_url(): ?string {
    $user_dashboard_page_id = absint( helpgent_get_setting( 'user_dashboard_page', 0 ) );
    $dashboard_page_link    = $user_dashboard_page_id ? get_permalink( $user_dashboard_page_id ) : false;

    return ! empty( $dashboard_page_link ) ? $dashboard_page_link : null;
}

function helpgent_option():OptionRepository {
    return helpgent_singleton( OptionRepository::class );
}

function helpgent_date_time_format() {
    return apply_filters( 'helpgent_date_time_format', 'Y-m-d H:i:s' );
}

function helpgent_remove_contacts_csv_cache( int $old_days = 2 ) {
    $temp_dir = helpgent_upload_dir( "contact" );

    if ( ! is_dir( $temp_dir ) ) {
        return;
    }

    $files = array_diff( scandir( $temp_dir ), ['.', '..'] );

    foreach ( $files as $file ) {
        $file_created_time = explode( '-', $file )[1];
        $file_created_time = rtrim( $file_created_time, '.csv' );
        $expired_time      = intval( $file_created_time ) + ( DAY_IN_SECONDS * $old_days );

        if ( $expired_time < time() ) {
            helpgent_filesystem()->delete( "$temp_dir/$file" );
        }
    }
}

function helpgent_is_preview() :bool {
    global $helpgent_is_preview;
    return $helpgent_is_preview ? true : false;
}

function helpgent_get_response_by_token( string $token, int $form_id ) {
    /**
     * @var FormRepository $form_repository
     */
    $form_repository = helpgent_singleton( FormRepository::class );
    $response_id     = $form_repository->get_meta_value( $form_id, $token );

    /**
     * @var ResponseRepository $response_repository
     */
    $response_repository = helpgent_singleton( ResponseRepository::class );
    return $response_repository->get_by_id( $response_id );
}

function helpgent_get_response_token( int $response_id, int $form_id ) {
    /**
     * @var FormRepository $form_repository
     */
    $form_repository = helpgent_singleton( FormRepository::class );
    return $form_repository->get_response_token( $response_id, $form_id );
}

function helpgent_get_site_verification_token(): string {
    /**
     * @var SiteVerificationRepository $repository
     */
    $repository = helpgent_singleton( SiteVerificationRepository::class );

    return $repository->get_token();
}

function helpgent_get_licensing_config(): array {
    /**
     * @var License $license
     */
    $license = helpgent_singleton( License::class );

    return $license->get_config();
}

/**
 * @throws Exception
 * @return bool
 */
function helpgent_verify_site_verification_token( string $token ): bool {
    /**
     * @var SiteVerificationRepository $repository
     */
    $repository = helpgent_singleton( SiteVerificationRepository::class );

    return $repository->verify_token( $token );
}

function helpgent_element_handler( string $field_type ):Element {
    $field_handler_class = helpgent_config( "element-fields-handlers.{$field_type}" );

    if ( ! class_exists( $field_handler_class ) ) {
        throw new Exception( esc_html__( 'Field handler not found.', 'helpgent' ), 500 );
    }

    $element_handler = helpgent_make( $field_handler_class );

    if ( ! $element_handler instanceof Element ) {
        throw new Exception( esc_html__( 'Please use a valid field handler.', 'helpgent' ), 500 );
    }

    return $element_handler;
}

function helpgent_export_contact( Builder $query, string $type = "guest" ) {
    $total_query = clone $query;
    $table_alias = $type === 'lead' ? 'contact' : $type;

    $total_query->groups = null;

    $total = $total_query->distinct()->count( "{$table_alias}.id" );

    if ( 0 === $total ) {
        // translators: %s: contact type
        throw new Exception( sprintf( esc_html__( "There are no %s to export.", 'helpgent' ), esc_attr( $type ) ), 404 );
    }

    $temp_dir = helpgent_upload_dir( "contact" );

    if ( ! is_dir( $temp_dir ) ) {
        helpgent_filesystem()->mkdir( $temp_dir );
    }

    helpgent_remove_contacts_csv_cache();

    $file_name     = $type . '-' . time() . ".csv";
    $csv_file_path = "$temp_dir/{$file_name}";

    $per_page   = 100000;
    $total_page = ceil( $total / $per_page ) + 1;

    // contacts
    $select_query = clone $query;
    $data         = $select_query->pagination( 1, $per_page, 10, $per_page );

    // Write the headers
    $headers = array_keys( ( array ) $data[0] );

    helepgent_fputcsv( $csv_file_path, $headers );

    // Write the data
    helpgent_write_csv( $csv_file_path, $data );

    for ( $page = 2; $page < $total_page; $page++ ) {
        $select_query = clone $query;
        $data         = $select_query->pagination( $page, $per_page, 10, $per_page );

        // Write the data
        helpgent_write_csv( $csv_file_path, $data );
    }

    return [
        'file_name' => $file_name,
        'url'       => helpgent_upload_url( "contact/{$file_name}" )
    ];
}

function helpgent_write_csv( string $file_path, array $data ) {
    foreach ( $data as $row ) {
        helepgent_fputcsv( $file_path, ( array ) $row );
    }
}

function helepgent_fputcsv( string $file_path, array $fields ) {
    $csv_line = implode( ",", array_map( 'helpgent_esc_csv_value', $fields ) ) . "\n";

    return file_put_contents( $file_path, $csv_line, FILE_APPEND );
}

/**
 * Escape values if they contain commas or quotes
 */
function helpgent_esc_csv_value( $value ): string {
    $value = ( string ) $value;

    if ( strpos( $value, ',' ) !== false || strpos( $value, '"' ) !== false ) {
        $value = '"' . str_replace( '"', '""', $value ) . '"';
    }

    return $value;
}

function helpgent_migrate_old_form( $form, bool $content_json = true ) {
    if ( empty( $form->content ) ) {
        return $form;
    }

    $form_content  = json_decode( $form->content, true );
    $form->content = $content_json ? $form->content : $form_content;

    if ( ! isset( $form_content['elements'] ) ) {
        return $form;
    }

    $elements                = [];
    $contact_default_targets = [];
    $has_contact_info        = false;
    $is_elements_already_migrated = false;

    foreach ( $form_content['elements'] as $element ) {
        // Skip elements that are already migrated
        if ( isset( $element['attributes'] ) ) {
            $is_elements_already_migrated = true;
            $elements                     = $form_content['elements'];
            break;
        }

        if ( $element['element_type'] === 'user_validation' ) {
            continue;
        }

        if ( $element['element_type'] === 'contact_info' ) {
            $has_contact_info                          = true;
            $contact_default_targets[ $element['id'] ] = helpgent_get_nested_value( 'controls.elementLogic.default_target', $element );
            continue;
        }

        // Migrate Replay Methods
        $reply_methods = helpgent_get_nested_value( 'controls.general.reply_methods', $element );

        if ( is_array( $reply_methods ) ) {
            foreach ( $reply_methods as $key => $value ) {
                if ( ! is_array( $value ) ) {
                    continue;
                }

                $reply_methods[ $key ] = isset( $value[ 'isActive' ] ) && '1' === $value[ 'isActive' ] ? '1' : '0';
            }
        }

        // Migrate attributes
        $element['attributes'] = [
            'title'                   => $element['title'],
            'description'             => helpgent_get_nested_value( 'controls.general.description.value', $element ),
            'required'                => helpgent_get_nested_value( 'controls.general.required.isActive', $element ),
            'is_max_length'           => helpgent_get_nested_value( 'controls.general.max_length.isActive', $element ),
            'max_length'              => intval( helpgent_get_nested_value( 'controls.general.max_length.value', $element ) ),
            'date'                    => helpgent_get_nested_value( 'fields.date.value', $element ),
            'date_format'             => helpgent_get_nested_value( 'controls.general.date_format.value', $element ),
            'separator'               => helpgent_get_nested_value( 'controls.general.separator.value', $element ),
            'options'                 => helpgent_get_nested_value( 'controls.general.options', $element ),
            'placeholder'             => helpgent_get_nested_value( 'controls.general.placeholder.value', $element ),
            'isSocials'               => helpgent_get_nested_value( 'controls.socials.isActive', $element ),
            'platforms'               => helpgent_get_nested_value( 'controls.socials.platforms', $element ),
            'externalButton'          => helpgent_get_nested_value( 'controls.externalButton.isActive', $element ),
            'upload_btn_text'         => helpgent_get_nested_value( 'controls.general.upload_btn_text.value', $element ),
            'upload_note'             => helpgent_get_nested_value( 'controls.general.upload_note.value', $element ),
            'limit_file_size'         => helpgent_get_nested_value( 'controls.general.file_size.isActive', $element ),
            'file_size'               => intval( helpgent_get_nested_value( 'controls.general.file_size.value', $element ) ),
            'file_size_unit'          => helpgent_get_nested_value( 'controls.general.file_size_unit.value', $element ),
            'limit_files'             => helpgent_get_nested_value( 'controls.general.file_count.isActive', $element ),
            'file_count'              => intval( helpgent_get_nested_value( 'controls.general.file_count.value', $element ) ),
            'learn_more'              => helpgent_get_nested_value( 'controls.general.learn_more.isActive', $element ),
            'learn_more_label'        => helpgent_get_nested_value( 'controls.general.learn_more_label.value', $element ),
            'learn_more_link'         => helpgent_get_nested_value( 'controls.general.learn_more_link.value', $element ),
            'map_api_key'             => helpgent_get_nested_value( 'controls.general.map_api_key.value', $element ),
            'author_location'         => helpgent_get_nested_value( 'controls.general.author_location.coordinates', $element ),
            'is_user_location'        => helpgent_get_nested_value( 'controls.general.user_location.isActive', $element ),
            'user_location'           => helpgent_get_nested_value( 'controls.general.user_location.coordinates', $element ),
            'chat_title'              => helpgent_get_nested_value( 'controls.general.chat_title.value', $element ),
            'footer_message'          => helpgent_get_nested_value( 'controls.general.footer_message.value', $element ),
            'reply_methods'           => $reply_methods,
            'quotation_mark'          => helpgent_get_nested_value( 'controls.general.quotation_mark.isActive', $element ),
            'timeFormat'              => strval( helpgent_get_nested_value( 'controls.general.timeFormat.value', $element ) ),
            'text_fields'             => helpgent_get_nested_value( 'controls.general.text_fields', $element ),
            'defaultTime'             => helpgent_get_nested_value( 'controls.general.defaultTime.value', $element ),
            'minuteStepping'          => strval( helpgent_get_nested_value( 'controls.general.minuteStepping.value', $element ) ),
            'defaultPlaceholder'      => helpgent_get_nested_value( 'controls.general.defaultPlaceholder.value', $element ),
            'is_time_to_complete'     => helpgent_get_nested_value( 'controls.general.time_to_complete.isActive', $element ),
            'low_rating_text'         => helpgent_get_nested_value( 'controls.general.low_rating_text.value', $element ),
            'high_rating_text'        => helpgent_get_nested_value( 'controls.general.high_rating_text.value', $element ),
            'min_value'               => intval( helpgent_get_nested_value( 'controls.general.min_value.value', $element ) ),
            'max_value'               => intval( helpgent_get_nested_value( 'controls.general.max_value.value', $element ) ),
            'start_value'             => intval( helpgent_get_nested_value( 'controls.general.start_value.value', $element ) ),
            'rating_icon'             => helpgent_get_nested_value( 'controls.general.rating_icon.value', $element ),
            'rating_amount'           => intval( helpgent_get_nested_value( 'controls.general.rating_amount.value', $element ) ),
            'fields'                  => helpgent_get_nested_value( 'fields', $element ),
            'is_video_overlay_active' => helpgent_get_nested_value( 'controls.fieldDesign.mediaStyle.video_overlay.isActive', $element ),
            'overlay_color'           => helpgent_get_nested_value( 'controls.fieldDesign.mediaStyle.overlay_color.value', $element ),
            'overlay_opacity'         => strval( helpgent_get_nested_value( 'controls.fieldDesign.mediaStyle.overlay_opacity.value', $element ) ),
            'layout'                  => ( $element['layout'] === 'openEndedDefault' )
                ? 'mediaLeft'
                : ( ( $element['layout'] === 'noMedia' ) ? 'noMedia-lg' : $element['layout'] ),
            'elementLogic'            => helpgent_get_nested_value( 'controls.elementLogic', $element ),
            'media'                   => $element['media'],
        ];

        $elements[] = $element;
    }

    if ( ! $is_elements_already_migrated ) {
        // Update logic target elements if contact_info is present
        if ( $has_contact_info ) {
            foreach ( $elements as &$element ) {
                $logic = &$element['attributes']['elementLogic'];

                if ( ! empty( $logic['logics'] ) ) {
                    foreach ( $logic['logics'] as &$logic_item ) {
                        if ( isset( $contact_default_targets[ $logic_item['target_element'] ] ) ) {
                            $logic_item['target_element'] = $contact_default_targets[ $logic_item['target_element'] ];

                            helpgent_form_enable_collect_contact_details( $element, $form_content['global'] );
                        }
                    }
                }

                if ( isset( $logic['default_target'], $contact_default_targets[ $logic['default_target'] ] ) ) {
                    $logic['default_target'] = $contact_default_targets[ $logic['default_target'] ];

                    helpgent_form_enable_collect_contact_details( $element, $form_content['global'] );
                }
            }
        }

        if ( '1' ===  helpgent_get_nested_value( 'global.anonymous_submission.isActive', $form_content ) ) {
            helpgent_form_enable_collect_contact_details( $elements[0], $form_content['global'] );
        }

        $form_content['elements'] = $elements;

        // Migrate global settings
        if ( isset( $form_content['global'] ) ) {
            $form_content['global']['footer_text_color'] = helpgent_get_nested_value( 'color_style.footer_text_color.value', $form_content['global'] );

            $form_content['global']['background_color']   = '#EDEFF2';
            $form_content['global']['background_overlay'] = helpgent_get_nested_value( 'background_style.background_overlay.isActive', $form_content['global'] );
            $form_content['global']['overlay_color']      = helpgent_get_nested_value( 'background_style.overlay_color.value', $form_content['global'] );
            $form_content['global']['overlay_opacity']    = helpgent_get_nested_value( 'background_style.overlay_opacity.value', $form_content['global'] );

            $form_content['global']['is_active_action_btn']           = helpgent_get_nested_value( 'action_btn.isActive', $form_content['global'] );
            $form_content['global']['is_active_helpgent_branding']    = helpgent_get_nested_value( 'helpgent_branding.isActive', $form_content['global'] );
            $form_content['global']['is_active_save_incomplete_data'] = helpgent_get_nested_value( 'save_incomplete_data.isActive', $form_content['global'] );
            $form_content['global']['is_active_progress_count']       = helpgent_get_nested_value( 'progress_count.isActive', $form_content['global'] );
            $form_content['global']['go_to_next_text']                = helpgent_get_nested_value( 'go_to_next_text.value', $form_content['global'] );
            $form_content['global']['submission_text']                = helpgent_get_nested_value( 'submission_text.value', $form_content['global'] );

            $form_content['global']['bubble_background']       = helpgent_get_nested_value( 'bubble.background_type', $form_content['global'] );
            $form_content['global']['bubble_overlay_text']     = helpgent_get_nested_value( 'bubble.overlay_text', $form_content['global'] );

            $form_content['global']['bubble_media_max_video_duration'] = helpgent_get_nested_value( 'media.max_video_duration.value', $form_content['global'] );
            $form_content['global']['bubble_media_max_voice_duration'] = helpgent_get_nested_value( 'media.max_voice_duration.value', $form_content['global'] );
            $form_content['global']['bubble_media_max_upload_size']    = helpgent_get_nested_value( 'media.max_upload_size.value', $form_content['global'] );
            $form_content['global']['bubble_media_max_upload_unit']    = helpgent_get_nested_value( 'media.max_upload_size.unit', $form_content['global'] );

            $form_content['global']['admin_notification_notify_on_new_response'] = helpgent_get_nested_value( 'email_notification.admin_notification.notify_on_new_response.isActive', $form_content['global'] );
            $form_content['global']['admin_notification_new_response_subject']   = helpgent_get_nested_value( 'email_notification.admin_notification.new_response_subject.value', $form_content['global'] );
            $form_content['global']['admin_notification_new_response_body']      = helpgent_get_nested_value( 'email_notification.admin_notification.new_response_body.value', $form_content['global'] );
            $form_content['global']['admin_notification_notify_on_user_message'] = helpgent_get_nested_value( 'email_notification.admin_notification.notify_on_user_message.isActive', $form_content['global'] );
            $form_content['global']['admin_notification_user_message_subject']   = helpgent_get_nested_value( 'email_notification.admin_notification.user_message_subject.value', $form_content['global'] );
            $form_content['global']['admin_notification_user_message_body']      = helpgent_get_nested_value( 'email_notification.admin_notification.user_message_body.value', $form_content['global'] );

            $form_content['global']['user_notification_notify_on_new_response']  = helpgent_get_nested_value( 'email_notification.user_notification.notify_on_new_response.isActive', $form_content['global'] );
            $form_content['global']['user_notification_new_response_subject']    = helpgent_get_nested_value( 'email_notification.user_notification.new_response_subject.value', $form_content['global'] );
            $form_content['global']['user_notification_new_response_body']       = helpgent_get_nested_value( 'email_notification.user_notification.new_response_body.value', $form_content['global'] );
            $form_content['global']['user_notification_notify_on_admin_message'] = helpgent_get_nested_value( 'email_notification.user_notification.notify_on_admin_message.isActive', $form_content['global'] );
            $form_content['global']['user_notification_admin_message_subject']   = helpgent_get_nested_value( 'email_notification.user_notification.admin_message_subject.value', $form_content['global'] );
            $form_content['global']['user_notification_admin_message_body']      = helpgent_get_nested_value( 'email_notification.user_notification.admin_message_body.value', $form_content['global'] );
        }
    }

    helpgent_migrate_form_themes( $form_content );
    helpgent_migrate_chat_bubble_settings( $form_content );
    helpgent_migrate_collect_contact_details_form( $form_content );
    helpgent_migrate_end_quiz_settings( $form_content );

    // Encode content back to JSON if needed
    $form->content = $content_json ? wp_json_encode( $form_content ) : $form_content;

    return $form;
}

function helpgent_normalize_theme_font_family( $font_family ): array {
    if ( is_array( $font_family ) && ! empty( $font_family['family'] ) ) {
        return $font_family;
    }

    if ( is_string( $font_family ) && '' !== $font_family ) {
        return [
            'family'   => $font_family,
            'category' => 'sans-serif',
        ];
    }

    return [
        'family'   => 'Inter',
        'category' => 'sans-serif',
    ];
}

function helpgent_migrate_form_themes( array &$form_content ): void {
    if ( ! isset( $form_content['global'] ) || ! is_array( $form_content['global'] ) ) {
        $form_content['global'] = [];
    }

    $global = &$form_content['global'];

    if ( ! isset( $global['options_color'] ) && ! empty( $global['option_color'] ) ) {
        $global['options_color'] = $global['option_color'];
    }

    if ( empty( $global['icon_color'] ) ) {
        $global['icon_color'] = '#000000';
    }

    if ( empty( $global['title_color'] ) ) {
        $global['title_color'] = '#101828';
    }

    if ( empty( $global['description_color'] ) ) {
        $global['description_color'] = '#747C89';
    }

    if ( empty( $global['button_color'] ) ) {
        $global['button_color'] = '#6551F2';
    }

    if ( empty( $global['button_text_color'] ) ) {
        $global['button_text_color'] = '#FFFFFF';
    }

    if ( empty( $global['options_color'] ) ) {
        $global['options_color'] = '#3c3c3c';
    }

    if ( empty( $global['promoter_score_active_color'] ) ) {
        $global['promoter_score_active_color'] = '#6551F2';
    }

    if ( empty( $global['info_color'] ) ) {
        $global['info_color'] = '#3c3c3c';
    }

    if ( empty( $global['step_navigation_color'] ) ) {
        $global['step_navigation_color'] = '#4d5761';
    }

    if ( empty( $global['field_background_color'] ) ) {
        $global['field_background_color'] = '#EFEFEF';
    }

    if ( empty( $global['field_icon_color'] ) ) {
        $global['field_icon_color'] = '#4d5761';
    }

    if ( empty( $global['rating_color'] ) ) {
        $global['rating_color'] = '#747C89';
    }

    if ( empty( $global['rating_active_color'] ) ) {
        $global['rating_active_color'] = $global['options_color'];
    }

    if ( empty( $global['range_track_color'] ) ) {
        $global['range_track_color'] = '#D5D5D5';
    }

    if ( empty( $global['range_track_active_color'] ) ) {
        $global['range_track_active_color'] = '#6551F2';
    }

    if ( empty( $global['placeholder_color'] ) ) {
        $global['placeholder_color'] = '#3c3c3c';
    }

    if ( empty( $global['corner'] ) ) {
        $global['corner'] = 'partiallyRound';
    }

    if ( ! array_key_exists( 'background_color', $global ) || '' === $global['background_color'] ) {
        $global['background_color'] = '#FFFFFF';
    }

    if (
        ! array_key_exists( 'background_image', $global ) ||
        (
            ! is_array( $global['background_image'] ) &&
            ! is_string( $global['background_image'] )
        )
    ) {
        $global['background_image'] = [];
    }

    if ( ! array_key_exists( 'background_overlay', $global ) ) {
        $global['background_overlay'] = '0';
    }

    if ( ! array_key_exists( 'overlay_color', $global ) || '' === $global['overlay_color'] ) {
        $global['overlay_color'] = '#000000';
    }

    if ( ! array_key_exists( 'overlay_opacity', $global ) || '' === $global['overlay_opacity'] ) {
        $global['overlay_opacity'] = '50';
    }

    $global['font_family'] = helpgent_normalize_theme_font_family( $global['font_family'] ?? null );

    if ( empty( $global['font_weight_variations'] ) || ! is_array( $global['font_weight_variations'] ) ) {
        $global['font_weight_variations'] = [ 400, 500, 600 ];
    }

    $themes = isset( $global['themes'] ) && is_array( $global['themes'] ) ? $global['themes'] : [];

    if ( empty( $themes ) ) {
        $theme_id = ! empty( $global['activeThemeId'] ) && is_string( $global['activeThemeId'] )
            ? $global['activeThemeId']
            : 'theme_default';

        $global['themes'] = [
            $theme_id => [
                'id'         => $theme_id,
                'attributes' => [
                    'name'                   => 'My new theme',
                    'font_family'            => $global['font_family'],
                    'font_weight_variations' => $global['font_weight_variations'],
                    'icon_color'             => $global['icon_color'],
                    'title_color'            => $global['title_color'],
                    'description_color'      => $global['description_color'],
                    'button_color'           => $global['button_color'],
                    'button_text_color'      => $global['button_text_color'],
                    'options_color'          => $global['options_color'],
                    'promoter_score_active_color' => $global['promoter_score_active_color'],
                    'info_color'             => $global['info_color'],
                    'step_navigation_color'  => $global['step_navigation_color'],
                    'field_background_color' => $global['field_background_color'],
                    'field_icon_color'       => $global['field_icon_color'],
                    'rating_color'           => $global['rating_color'],
                    'rating_active_color'    => $global['rating_active_color'],
                    'range_track_color'      => $global['range_track_color'],
                    'range_track_active_color' => $global['range_track_active_color'],
                    'placeholder_color'      => $global['placeholder_color'],
                    'corner'                 => $global['corner'],
                    'background_color'       => $global['background_color'],
                    'background_image'       => $global['background_image'],
                    'background_overlay'     => strval( $global['background_overlay'] ),
                    'overlay_color'          => $global['overlay_color'],
                    'overlay_opacity'        => strval( $global['overlay_opacity'] ),
                ],
            ],
        ];
        $global['activeThemeId'] = $theme_id;

        return;
    }

    foreach ( $themes as $theme_id => $theme ) {
        $attributes = isset( $theme['attributes'] ) && is_array( $theme['attributes'] )
            ? $theme['attributes']
            : [];
        $has_background_color = array_key_exists( 'background_color', $attributes );
        $has_background_image = array_key_exists( 'background_image', $attributes );
        $has_background_overlay = array_key_exists( 'background_overlay', $attributes );
        $has_overlay_color = array_key_exists( 'overlay_color', $attributes );
        $has_overlay_opacity = array_key_exists( 'overlay_opacity', $attributes );

        $themes[ $theme_id ] = array_merge(
            $theme,
            [
                'id'         => empty( $theme['id'] ) ? $theme_id : $theme['id'],
                'attributes' => [
                    'name'                   => empty( $attributes['name'] ) ? 'My new theme' : $attributes['name'],
                    'font_family'            => helpgent_normalize_theme_font_family( $attributes['font_family'] ?? $global['font_family'] ),
                    'font_weight_variations' => ! empty( $attributes['font_weight_variations'] ) && is_array( $attributes['font_weight_variations'] )
                        ? $attributes['font_weight_variations']
                        : $global['font_weight_variations'],
                    'icon_color'             => empty( $attributes['icon_color'] ) ? $global['icon_color'] : $attributes['icon_color'],
                    'title_color'            => empty( $attributes['title_color'] ) ? $global['title_color'] : $attributes['title_color'],
                    'description_color'      => empty( $attributes['description_color'] ) ? $global['description_color'] : $attributes['description_color'],
                    'button_color'           => empty( $attributes['button_color'] ) ? $global['button_color'] : $attributes['button_color'],
                    'button_text_color'      => empty( $attributes['button_text_color'] ) ? $global['button_text_color'] : $attributes['button_text_color'],
                    'options_color'          => empty( $attributes['options_color'] ) ? $global['options_color'] : $attributes['options_color'],
                    'promoter_score_active_color' => empty( $attributes['promoter_score_active_color'] ) ? $global['promoter_score_active_color'] : $attributes['promoter_score_active_color'],
                    'info_color'             => empty( $attributes['info_color'] ) ? $global['info_color'] : $attributes['info_color'],
                    'step_navigation_color'  => empty( $attributes['step_navigation_color'] ) ? $global['step_navigation_color'] : $attributes['step_navigation_color'],
                    'field_background_color' => empty( $attributes['field_background_color'] ) ? $global['field_background_color'] : $attributes['field_background_color'],
                    'field_icon_color'       => empty( $attributes['field_icon_color'] ) ? $global['field_icon_color'] : $attributes['field_icon_color'],
                    'rating_color'           => empty( $attributes['rating_color'] ) ? $global['rating_color'] : $attributes['rating_color'],
                    'rating_active_color'    => empty( $attributes['rating_active_color'] ) ? $global['rating_active_color'] : $attributes['rating_active_color'],
                    'range_track_color'      => empty( $attributes['range_track_color'] ) ? $global['range_track_color'] : $attributes['range_track_color'],
                    'range_track_active_color' => empty( $attributes['range_track_active_color'] ) ? $global['range_track_active_color'] : $attributes['range_track_active_color'],
                    'placeholder_color'      => empty( $attributes['placeholder_color'] ) ? $global['placeholder_color'] : $attributes['placeholder_color'],
                    'corner'                 => empty( $attributes['corner'] ) ? $global['corner'] : $attributes['corner'],
                    'background_color'       => $has_background_color ? $attributes['background_color'] : $global['background_color'],
                    'background_image'       => $has_background_image &&
                        (
                            is_array( $attributes['background_image'] ) ||
                            is_string( $attributes['background_image'] )
                        )
                        ? $attributes['background_image']
                        : $global['background_image'],
                    'background_overlay'     => $has_background_overlay
                        ? strval( $attributes['background_overlay'] )
                        : strval( $global['background_overlay'] ),
                    'overlay_color'          => $has_overlay_color ? $attributes['overlay_color'] : $global['overlay_color'],
                    'overlay_opacity'        => $has_overlay_opacity
                        ? strval( $attributes['overlay_opacity'] )
                        : strval( $global['overlay_opacity'] ),
                ],
            ]
        );
    }

    $global['themes'] = $themes;

    if ( empty( $global['activeThemeId'] ) || ! isset( $global['themes'][ $global['activeThemeId'] ] ) ) {
        $theme_ids = array_keys( $global['themes'] );
        $global['activeThemeId'] = empty( $theme_ids ) ? null : $theme_ids[0];
    }
}

function helpgent_migrate_end_quiz_settings( array &$form_content ): void {
    if ( empty( $form_content['elements'] ) || ! is_array( $form_content['elements'] ) ) {
        return;
    }

    $global_show_answers = helpgent_get_nested_value( 'global.quiz_show_correct_answers.isActive', $form_content, '0' ) === '1'
        ? '1'
        : '0';

    foreach ( $form_content['elements'] as &$element ) {
        if ( empty( $element['element_type'] ) || 'end' !== $element['element_type'] ) {
            continue;
        }

        if ( empty( $element['attributes'] ) || ! is_array( $element['attributes'] ) ) {
            $element['attributes'] = [];
        }

        if ( ! isset( $element['attributes']['quiz_show_answers'] ) ) {
            $element['attributes']['quiz_show_answers'] = $global_show_answers;
        }

        if ( empty( $element['attributes']['quiz_show_answers_button_label'] ) ) {
            $element['attributes']['quiz_show_answers_button_label'] = 'Show Answers';
        }
    }
}

function helpgent_migrate_chat_bubble_settings( array &$form_content ): void {
    if ( ! isset( $form_content['global'] ) || ! is_array( $form_content['global'] ) ) {
        $form_content['global'] = [];
    }

    $valid_bubble_sizes = [ 'large', 'medium', 'small', 'x_small' ];
    $bubble_size        = $form_content['global']['bubble_size'] ?? '';

    if ( in_array( $bubble_size, $valid_bubble_sizes, true ) ) {
        return;
    }

    $form_content['global']['bubble_size'] = 'small';
}

function helpgent_migrate_collect_contact_details_form( array &$form_content ): void {
    if ( empty( $form_content['elements'] ) || ! is_array( $form_content['elements'] ) ) {
        return;
    }

    foreach ( $form_content['elements'] as &$element ) {
        if ( '1' !== strval( helpgent_get_nested_value( 'attributes.collect_contact_details', $element, '0' ) ) ) {
            continue;
        }

        helpgent_form_enable_collect_contact_details( $element, $form_content['global'] );
        return;
    }
}

function helpgent_form_enable_collect_contact_details( &$element, &$global ) {
    $element['attributes']['collect_contact_details'] = '1';

    if ( ! empty( $global['collect_info_form'] ) && is_array( $global['collect_info_form'] ) ) {
        return;
    }

    $form_fields = json_decode( file_get_contents( helpgent_dir( 'resources/data/defaultContactFormFields.json' ) ), true );

    $global['collect_info_form'] = $form_fields;
}

function helpgent_get_form_elements( array $form_content ): array {
    if ( empty( $form_content ) ) {
        return [];
    }

    if ( ! isset( $form_content['elements'] ) ) {
        return [];
    }

    return array_map(
        function( $element ) {
            return [
                'id'           => $element['id'],
                'element_type' => $element['element_type'],
            ];
        }, $form_content['elements']
    );
}

function helpgent_run_with_no_echo( callable $callback, array $args = [], $default_value = null, bool $error_log = false ) {
    ob_start();

    $result = call_user_func_array( $callback, $args );

    $content = ob_get_clean();

    if ( ! empty( $content ) ) {
        if ( $error_log ) {
            error_log( $content );
        }

        return $default_value;
    }

    return $result;
}
