<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'elementor/document/after_save', 'elementsell_sync_widgets_on_elementor_save', 10, 2 );

/**
 * @return void
 */
function elementsell_ensure_elementor_sync_dependencies() {
    if ( ! function_exists( 'elementsell_merge_page_access_roles' ) ) {
        require_once PF_PLUGIN_DIR . 'includes/pages/page-access.php';
    }

    if ( ! function_exists( 'elementsell_get_course_roles_from_widget_settings' ) ) {
        require_once PF_PLUGIN_DIR . 'includes/pages/course-roles.php';
    }

    if ( ! function_exists( 'elementsell_sync_thepay_widget_credentials_to_options' ) ) {
        require_once PF_PLUGIN_DIR . 'includes/payments/payment-widget-credentials.php';
    }

    if ( ! function_exists( 'elementsell_normalize_fio_account_number' ) ) {
        require_once PF_PLUGIN_DIR . 'includes/payments/payment-fio-account.php';
    }

    if ( ! function_exists( 'elementsell_ensure_widget_page_dependencies' ) ) {
        require_once PF_PLUGIN_DIR . 'includes/pages/widget-page-ensure.php';
    }

    elementsell_ensure_widget_page_dependencies();
}

/**
 * @param \Elementor\Core\Base\Document $document
 * @param array                         $data
 * @return void
 */
function elementsell_sync_widgets_on_elementor_save( $document, $data ) {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $elements = $document->get_elements_data();

    if ( empty( $elements ) || ! is_array( $elements ) ) {
        return;
    }

    elementsell_ensure_elementor_sync_dependencies();
    elementsell_walk_elements_for_widget_sync( $elements );
    elementsell_sync_course_image_page_access_from_elements( $elements );
}

/**
 * @param array $elements
 * @return void
 */
function elementsell_walk_elements_for_widget_sync( $elements ) {
    foreach ( $elements as $element ) {
        if (
            ! empty( $element['widgetType'] )
            && $element['widgetType'] === 'elementsell_payment_form'
            && ! empty( $element['settings'] )
            && is_array( $element['settings'] )
        ) {
            elementsell_sync_payment_widget_settings_to_options( $element['settings'] );
        }

        if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) {
            elementsell_walk_elements_for_widget_sync( $element['elements'] );
        }
    }
}

/**
 * @param array $settings
 * @return void
 */
function elementsell_sync_payment_widget_settings_to_options( $settings ) {
    if ( function_exists( 'elementsell_sync_payment_widget_credentials_to_options' ) ) {
        elementsell_sync_payment_widget_credentials_to_options( $settings );
    }

    if ( function_exists( 'elementsell_ensure_widget_pages_from_settings' ) ) {
        elementsell_ensure_widget_pages_from_settings( $settings );
    }
}
