<?php

	if ( ! defined( 'ABSPATH' ) ) {
		exit;
	}

	// require all widgets
	foreach ( glob( __DIR__ . '/../widgets/*.php' ) as $file ) {
		require_once $file;
	}

	add_action( 'wp_ajax_piotnetforms_widget_preview', 'piotnetforms_widget_preview' );

	function piotnetforms_widget_preview() {
        if(isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], 'piotnetforms_pro_editor_nonce' )){
            $widget_id = $_POST['widget_id'];
            $function  = $_POST['function'];

            $response = [
                'widget_id' => $widget_id,
            ];

            if ( ! is_user_logged_in() || ! current_user_can( 'edit_others_posts' ) ) {
                print_r( 'permission_error' );
                return;
            }

            if ( $function == 'widget_init' ) {
                $widget_data       = $_POST['widget_data'];

                if ( !empty( $widget_data['class_name'] ) ) {
                    $widget            = new $widget_data['class_name']();
                    $widget->widget_id = $widget_id;

                    $response['outputHTML'] = $widget->output( $widget_id, true );
                }
            } elseif ( $function == 'widget_edit' ) {
                $widget_settings    = $_POST['widget_settings'];
                $widget_information = $_POST['widget_information'];

                if ( !empty( $widget_information['class_name'] ) ) {
                    $widget            = new $widget_information['class_name']();
                    $widget->settings  = $widget_settings;
                    $widget->widget_id = $widget_id;

                    $response['outputHTML'] = stripslashes( $widget->output( $widget_id, true ) );
                }
            }

            echo json_encode( $response );
        }else{
            echo "Nonce verification failed.";
        }
		wp_die();
	}
