<?php
if ( ! defined( 'ABSPATH' ) ) {
	die( 'You are not allowed to call this page directly.' );
}

class FormShieldWEFormsIntegration extends FormShieldIntegration {
	public static $form_prefix = 'wef';

	/*
	 * This is where you will add filters and actions
	 */
	public function __construct() {
		add_filter( 'formshield_forms_list', array( __CLASS__, 'get_forms' ), 60, 1 );
		add_filter( 'weforms_before_entry_submission', array( __CLASS__, 'validate_ajax_forms' ), 10, 4 );
		add_action( 'formshield_autoprotect_forms', array( __CLASS__, 'enable_forms' ), 60, 1 );
	}

	/*
	 * Get WeForms
	 * This should return the forms list
	 *
	 * @return Array $forms_list
	 */
	public static function get_forms( $forms_list ) {
		if ( method_exists( 'WeForms_Form_Manager', 'all' ) ) {
			$additional_forms = array();
			$form_list        = ( new WeForms_Form_Manager() )->all();
			if ( isset( $form_list['forms'] ) ) {
				foreach ( $form_list['forms'] as $form ) {
					// Assign unique form id
					$fid = self::get_form_id( $form->get_id() );
					// Get current form entries
					$entries = $form->entries()->all();
					// Get last entry date
					$entry_ids = array();
					foreach ( $entries as $entry ) {
						$entry_ids[] = $entry->id;
					}
					$last_entry_id = ! empty( $entry_ids ) ? max( $entry_ids ) : 0;
					$last_entry    = array_key_exists( $last_entry_id, $entries ) ? $entries[ $last_entry_id ]->created : null;
					// Push to forms list
					$additional_forms[] = array(
						'id'          => $fid,
						'enabled'     => FormShieldSettings::is_form_enabled( $fid ),
						'name'        => $form->post_title,
						'type'        => 'WeForms',
						'location'    => 'WeForms: ' . $form->post_title . ' (ID: ' . $form->ID . ')',
						'submissions' => FormShieldForms::get_form_submissions_ct( $fid, $submissions_count ),
						'activity'    => FormShieldForms::get_latest_form_activity( $fid, $form->post_modified )
					);
				}
			}
			self::prune_disabled_forms( $additional_forms );
			$forms_list = array_merge( $forms_list, $additional_forms );
		}

		return $forms_list;
	}

	/**
	 * Validate WeForms Ajax Submission
	 *
	 * @param Array $entry_fields - Array of submitted data fields
	 * @param Obj $form - Form Obj
	 * @param Array $form_settings - Form Settings
	 * @param Array $form_fields - Form Fields
	 *
	 * @return Array - $entry_fields
	 */
	public static function validate_ajax_forms( $entry_fields, $form, $form_settings, $form_fields ) {
		// If HP protection enabled, validate the form
		$options = form_shield()->get_options();
		$fid     = self::get_form_id( absint( $form->get_id() ) );
		if ( is_array( $options ) && array_key_exists( 'formshield_forms', $options ) && isset( $options['formshield_forms'][ $fid ] ) ) {
			$formshield_form_enabled = $options['formshield_forms'][ $fid ]['form_enabled'];

			if ( $formshield_form_enabled ) {
				// If the detection check fails, prevent the form submission and display an error message.
				$validation_failed = FormShieldForms::fail_form_validation();
				if ( $validation_failed ) {
					// Record suspicious activity
					FormShieldForms::handle_suspicious_form_activity( $fid );
					wp_send_json( [
						'success' => false,
						'error'   => FormShieldForms::fail_form_error_message()
					] );
				}
			}
		}

		return $entry_fields;
	}

	/*
	 * Protect Existing WeForms
	 */
	public static function enable_forms( $unattended ) {
		if ( method_exists( 'WeForms_Form_Manager', 'all' ) ) {
			$form_list = ( new WeForms_Form_Manager() )->all();
			if ( isset( $form_list['forms'] ) ) {
				foreach ( $form_list['forms'] as $form ) {
					// Assign unique form id
					$fid = self::get_form_id( $form->get_id() );
					FormShieldForms::enable_forms( $fid, 1, $unattended );
				}
			}	
		}
	}

	/**
     * Update Human Presence form enabled status from weForms form field save
     *
     * @return void
     */
    public static function update_enabled_status( $form_id, $form_fields, $form_settings ) {
        if ( class_exists( 'FormShieldForms' ) ) {        	
            		$status = isset( $form_settings['formshield_enabled'] ) ? (int)$form_settings['formshield_enabled'] : 0;
            $options = form_shield()->get_options();
            // Disable auto-protect if user wants to disable a form
            if ( 1 === $options['wp_hp_autoprotect'] && !$status ) {
                $options['wp_hp_autoprotect'] = 0;
                form_shield()->update_options( $options );
            }

            FormShieldForms::enable_forms( self::get_form_id( $form_id ), $status, true );
        }
    }

    /**
     * Update Human Presence form enabled status from weForms form field save
     *
     * @return void
     */
    public static function filter_settings_enabled_status( $settings, $form_id ) {
    	$options = form_shield()->get_options();
    			if ( isset( $options['formshield_forms'] ) ) {
			$settings['formshield_enabled'] = !!$options['formshield_forms'][self::get_form_id( $form_id )]['form_enabled'];
		}

        return $settings;
    }

    public static function filter_fields_enabled_status( $fields, $form_id ) {
    	$options = form_shield()->get_options();
    	$enabled = false;
		if ( isset( $options['formshield_forms'] ) ) {
			$enabled = !!$options['formshield_forms'][self::get_form_id( $form_id )]['form_enabled'];
		}
		if( $enabled ) {
			$hp_exists = false;
			foreach ( $fields as $key => $field ) {
							if ( $field['template'] === 'formshield' ) {
				$hp_exists = true;
			}
			}
			if ( !$hp_exists ) {
				if ( class_exists( 'WeForms_Form_Field_FormShield' ) ) {
					$fields[] = (new WeForms_Form_Field_FormShield())->get_field_props();
				} else {
					$fields[] = [
						'template'              => 'formshield',
			            'label'                 => '',
			            'is_meta'               => 'yes',
			            'id'                    => 0,
			            'is_new'                => true,
			            'wpuf_cond'             => null,
					];
				}
				
			}
		} else {
			foreach ( $fields as $key => $field ) {
							if ( $field['template'] === 'formshield' ) {
				unset( $fields[$key] );
			}
			}
		}
    		
        return $fields;
    }

    /*
	 * Usage self::log('error', 'Check out this sweet error!');
	 *
	*/
	public static function log($action, $message="", $logfile=false) {
	    // Use WP_Filesystem for file operations
	    if ( ! function_exists( 'request_filesystem_credentials' ) ) {
	        require_once ABSPATH . 'wp-admin/includes/file.php';
	    }
	    
	    WP_Filesystem();
	    global $wp_filesystem;
	    
	    $uploads = wp_upload_dir();
	    $log_dir = trailingslashit( $uploads['basedir'] ) . 'formshield-logs/';
	    if ( ! file_exists( $log_dir ) ) {
	        wp_mkdir_p( $log_dir ); // създава директорията безопасно
	    }
	    $logfile = $logfile ? $logfile : $log_dir . gmdate('Y-m-d') . '.log';
	    $logfile = wp_normalize_path($logfile);
	    
	    // Ensure logs directory exists
	    $log_dir = dirname($logfile);
	    if ( ! $wp_filesystem->is_dir($log_dir) ) {
	        wp_mkdir_p($log_dir);
	    }
	    
	    $timestamp = gmdate("Y-m-d H:i:s");
	    $content = "{$timestamp} | {$action}: {$message}\n";
	    
	    // Get existing content if file exists
	    $existing_content = '';
	    if ( $wp_filesystem->exists($logfile) ) {
	        $existing_content = $wp_filesystem->get_contents($logfile);
	    }
	    
	    // Append new content
	    $new_content = $existing_content . $content;
	    
	    if ( ! $wp_filesystem->put_contents($logfile, $new_content, FS_CHMOD_FILE) ) {
	        return false;
	    }
	    
	    return true;
	}

    /**
     * Form and form processing for global formshield settings in weForms General settings tabs
     *
     * @return void
     */
    public static function formshield_general_settings() {
    	$options = form_shield()->get_options();
		$premium = form_shield()->is_premium();
		$message = '';
		$message_class = 'updated';
		if ( $premium ) {
			// Verify nonce
			if ( ! wp_verify_nonce( formshield_get_post_string('_wpnonce'), 'formshield_settings' ) ) {
				$message = 'Security check failed.';
				$message_class = 'error';
			} else {
				$minimal_confidence = formshield_get_post_float('minimal_confidence', 0.0, 1.0, 0.5);
				if ( $minimal_confidence !== $options['wp_formshield_min_confidence'] ) {
					$validation_failed = FormShieldSettings::minimal_confidence_validate( $minimal_confidence );
					if ( !$validation_failed ) {
						FormShieldSettings::handle_settings_changes( $_POST );
						$options = form_shield()->get_options();
						$message = 'Settings saved successfully.';
					} else {
						$message = 'Please enter a valid number.';
						$message_class = 'error';
					}
				}
			}
			?>
<form method="POST" action="" class="wp-formshield">
<?php wp_nonce_field('formshield_settings', '_wpnonce'); ?>
<table class="wp-list-table widefat fixed striped">
	<tbody>
		<tr>
			<td class="dl">
				<p>
					Adjust the Minimal Confidence Threshold
					<span class="formshield-pop">
						<i class="fa fa-info-circle fa-fw"></i>
						<span class="popover above">A number between 0 and 100 that represents the minimum percentage of confidence acceptable before failing the form validation.</span>
					</span>
				</p>
			</td>
			<td class="pull-right">
				<label for="minimal_confidence"></label>
				<input class="minimal-confidence" name="minimal_confidence" type="number" value="<?php echo isset( $options['wp_formshield_min_confidence'] ) ? esc_attr( $options['wp_formshield_min_confidence'] ) : 70; ?>" />
			</td>
		</tr>
	</tbody>
</table>
<?php if ( $message ):?>
<div class="wrap">
<div class="<?php echo esc_attr($message_class);?>"><p><?php echo esc_html($message);?></p></div>
</div>
<?php endif;?>
<p class="action-row">
	<input onclick="this.submit()" class="button-primary" name="formshield_settings_save" type="submit" value="Save changes">
</p>
</form>
<?php
		}

    }

}

add_action( 'plugins_loaded', function() { new FormShieldWEFormsIntegration(); });

add_action( 'weforms_after_save_form', [ 'FormShieldWEFormsIntegration', 'update_enabled_status' ], 10, 3 );
add_filter( 'weforms-get-form-settings', [ 'FormShieldWEFormsIntegration', 'filter_settings_enabled_status' ], 999, 2 );
add_filter( 'weforms-get-form-fields', [ 'FormShieldWEFormsIntegration', 'filter_fields_enabled_status' ], 999, 2 );
add_action( 'weforms_formshield_global_settings_form', [ 'FormShieldWEFormsIntegration', 'formshield_general_settings' ], 10 );
