<?php

namespace IGD_PRO;

use IGD\App;
use IGD\Shortcode;
use IGD\Uploader;

defined( 'ABSPATH' ) || exit;

class Integrations extends \IGD\Integrations {

	private static $instance = null;

	public function __construct() {
		parent::__construct();

		// Media Library Integration
		if ( $this->is_active( 'media-library' ) ) {
			include_once IGD_PRO_INCLUDES . '/integrations/MediaLibrary.php';
		} elseif ( ! empty( igd_get_settings( 'mediaLibraryFolders', [] ) ) ) {

			add_filter( 'pre_get_posts', function ( $query ) {

				// Check if we are performing a WooCommerce import to avoid modifying the attachment query
				if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_POST['action'] ) && $_POST['action'] === 'woocommerce_do_ajax_product_import' ) {
					return $query;
				}

				// Ensure we're only targeting 'attachment' post type
				if ( ! isset( $query->query_vars['post_type'] ) || $query->query_vars['post_type'] !== 'attachment' ) {
					return $query;
				}

				// Meta query to include media without '_igd_media_folder_id' or with '_igd_media_replace_id'
				$meta_query[] = [
					'relation' => 'OR',
					[
						'key'     => '_igd_media_folder_id',
						'compare' => 'NOT EXISTS',
					],
					[
						'key'     => '_igd_media_replace_id',
						'compare' => 'EXISTS',
					],
				];

				$query->set( 'meta_query', $meta_query );

				return $query;

			} );
		}

		// Load EDD integration
		if ( $this->is_active( 'edd' ) ) {
			include_once IGD_PRO_INCLUDES . '/integrations/Edd.php';
		}

		// Load WooCommerce integration
		if ( $this->is_active( 'woocommerce' ) ) {

			add_action( 'woocommerce_loaded', function () {
				$is_download_active = igd_get_settings( 'wooCommerceDownload', true );
				$is_upload_active   = igd_get_settings( 'wooCommerceUpload', false );

				$is_dokan_download_active = $this->is_active( 'dokan' ) && igd_get_settings( 'dokanDownload', true );
				$is_dokan_upload_active   = $this->is_active( 'dokan' ) && igd_get_settings( 'dokanUpload', false );

				if ( $is_download_active || $is_dokan_download_active ) {
					include_once IGD_PRO_INCLUDES . '/integrations/woocommerce/WoocommerceDownloads.php';
				}

				if ( $is_upload_active || $is_dokan_upload_active ) {
					include_once IGD_PRO_INCLUDES . '/integrations/woocommerce/WoocommerceUploads.php';
				}

				// Enqueue woocommerce scripts
				if ( $is_download_active || $is_upload_active ) {
					add_action( 'admin_enqueue_scripts', function () {

						if ( function_exists( 'get_current_screen' ) ) {
							$current_screen = get_current_screen();

							if ( isset( $current_screen->post_type ) && $current_screen->post_type == 'product' ) {
								if ( ! wp_script_is( 'igd-admin' ) ) {
									\IGD\Enqueue::instance()->admin_scripts( '', false );
								}

								wp_enqueue_script( 'igd-admin' );
							}
						}

					}, 99 );
				}

			} );
		}

		// Load Dokan integration
		if ( $this->is_active( 'dokan' ) ) {
			add_action( 'dokan_loaded', function () {
				include_once IGD_PRO_INCLUDES . '/integrations/Dokan.php';
			} );
		}

		// Tutor LMS
		if ( $this->is_active( 'tutor' ) ) {
			add_action( 'tutor_loaded', function () {
				include_once IGD_PRO_INCLUDES . '/integrations/Tutor.php';
			} );
		}

		add_action( 'plugins_loaded', function () {

			// Load WPForms integration
			if ( $this->is_active( 'wpforms' ) && defined( 'WPFORMS_VERSION' ) ) {
				include_once IGD_PRO_INCLUDES . '/integrations/WPForms.php';
			}

			// Load Gravity Forms integration
			if ( $this->is_active( 'gravityforms' ) && class_exists( 'GFAddOn' ) ) {
				include_once IGD_PRO_INCLUDES . '/integrations/GravityForms.php';
			}

			// Load Fluent Forms integration
			if ( $this->is_active( 'fluentforms' ) && defined( 'FLUENTFORM' ) ) {
				include_once IGD_PRO_INCLUDES . '/integrations/FluentForms.php';
			}

			// Load Formidable Forms integration
			if ( $this->is_active( 'formidableforms' ) && function_exists( 'load_formidable_forms' ) ) {
				include_once IGD_PRO_INCLUDES . '/integrations/FormidableForms.php';
			}

			// Load Ninja Forms integration
			if ( $this->is_active( 'ninjaforms' ) && function_exists( 'ninja_forms_three_table_exists' ) ) {
				include_once IGD_PRO_INCLUDES . '/integrations/NinjaForms.php';
			}

			// Load ACF integration
			if ( $this->is_active( 'acf' ) && class_exists( 'ACF' ) ) {
				add_action( 'acf/include_field_types', function () {
					include_once IGD_PRO_INCLUDES . '/integrations/ACF.php';
				} );
			}

			// Elementor Form
			if ( $this->is_active( 'elementor-form' ) ) {
				add_action( 'elementor_pro/forms/fields/register', [ $this, 'register_elementor_form_fields' ] );
				add_action( 'elementor_pro/forms/new_record', [ $this, 'elementor_form_may_create_entry_folder' ] );
			}

			// Register MetForm widget
			if ( $this->is_active( 'metform' ) && class_exists( 'MetForm\Plugin' ) ) {
				add_action( 'elementor/widgets/register', [ $this, 'register_widgets' ] );
				add_filter( 'metform/onload/input_widgets', [ $this, 'metform_register_widgets' ] );
				add_action( 'metform_after_store_form_data', [ $this, 'metform_may_create_entry_folder' ], 10, 4 );
			}

		} );

	}

	public function register_elementor_form_fields( $fields_manager ) {
		include_once IGD_PRO_INCLUDES . '/integrations/ElementorForm.php';

		$fields_manager->register( new GoogleDriveUpload() );
	}

	public function elementor_form_may_create_entry_folder( $record ) {

		$fields = $record->get( 'fields' );

		// Return early if fields are empty
		if ( empty( $fields ) ) {
			return;
		}

		// Prepare igd_fields array and populate tags array with field values
		$igd_fields = [];

		foreach ( $fields as $field ) {
			if ( $field['type'] == 'google_drive_upload' ) {
				$igd_fields[ $field['id'] ] = $field;
			}
		}

		if ( ! empty( $igd_fields ) ) {

			$form_fields = $record->get_form_settings( 'form_fields' );

			foreach ( $igd_fields as $id => $field ) {

				$field_data_key = array_search( $id, array_column( $form_fields, 'custom_id' ) );

				if ( $field_data_key === false ) {
					continue; // Exit early if field not found
				}

				$value = $field['value'];
				if ( empty( $value ) ) {
					continue;
				}

				$files = [];

				// Fetch file ids from the value text
				preg_match_all( '/file\/d\/(.*?)\/view/', $value, $matches );

				$file_ids = $matches[1];

				if ( empty( $file_ids ) ) {
					continue;
				}

				foreach ( $file_ids as $file_id ) {
					$files[] = App::instance()->get_file_by_id( $file_id );
				}

				if ( empty( $files ) ) {
					continue; // Exit early if no files
				}


				$field_data = $form_fields[ $field_data_key ];

				$module_data = Shortcode::get_shortcode_data( $field_data['module_id'] );

				error_log( print_r( $module_data, true ) );

				$tag_data = [
					'form' => [
						'form_title' => $record->get_form_settings( 'form_name' ),
						'form_id'    => get_the_ID(),
					]
				];

				// Rename files
				$extra_tags = $this->handle_elementor_form_field_tags( $fields );

				$rename_files = [];
				foreach ( $files as $file ) {
					// We will rename the file name
					$tag_data['name'] = $file['name'];

					$name = igd_replace_template_tags( $tag_data, $extra_tags );

					$rename_files[] = [
						'id'   => $file['id'],
						'name' => $name,
					];
				}

				if ( ! empty( $rename_files ) ) {
					App::instance()->rename_files( $rename_files );
				}

				// Create Entry Folder
				$create_entry_folder   = ! empty( $module_data['createEntryFolders'] );
				$create_private_folder = ! empty( $module_data['createPrivateFolder'] );

				if ( ! $create_entry_folder && ! $create_private_folder ) {
					continue;
				}

				$entry_folder_name_template = $module_data['entryFolderNameTemplate'] ?? 'Entry (%entry_id%) - %form_title% ';

				if ( false !== strpos( $entry_folder_name_template, '%entry_id%' ) ) {
					$submit_actions = $record->get_form_settings( 'submit_actions' );

					if ( in_array( 'save-to-database', $submit_actions ) ) {
						global $wpdb;
						$table                        = "{$wpdb->prefix}e_submissions";
						$submission_id                = $wpdb->get_var( "SELECT MAX(ID) FROM {$table}" );
						$tag_data['form']['entry_id'] = $submission_id;
					}
				}

				if ( igd_contains_tags( 'user', $entry_folder_name_template ) ) {
					if ( is_user_logged_in() ) {
						$tag_data['user'] = get_userdata( get_current_user_id() );
					}
				}

				if ( igd_contains_tags( 'post', $entry_folder_name_template ) ) {
					$referrer = wp_get_referer();

					if ( ! empty( $referrer ) ) {
						$post_id = url_to_postid( $referrer );
						if ( ! empty( $post_id ) ) {
							$tag_data['post'] = get_post( $post_id );
							if ( $tag_data['post']->post_type == 'product' ) {
								$tag_data['wc_product'] = wc_get_product( $post_id );
							}
						}
					}
				}

				$tag_data['name'] = $entry_folder_name_template;
				$folder_name      = igd_replace_template_tags( $tag_data, $extra_tags );

				Uploader::instance()->create_entry_folder_and_move( $files, $folder_name, $module_data );
			}

		}
	}

	private function handle_elementor_form_field_tags( $fields ) {
		$extra_tags = [];

		if ( ! empty( $fields ) ) {
			foreach ( $fields as $field ) {
				if ( $field['type'] == 'google_drive_upload' ) {
					continue;
				}

				$field_id = $field['id'];

				$field_value = $field['value'];

				// Handle array values, such as checkboxes
				if ( is_array( $field_value ) ) {
					$field_value = implode( ', ', $field_value );
				}

				$extra_tags[ '%' . $field_id . '%' ] = $field_value;
			}

		}

		return $extra_tags;
	}

	public function register_widgets( $widgets_manager ) {
		include_once IGD_PRO_INCLUDES . '/integrations/MetForm.php';

		$widgets_manager->register( new MetForm() );
	}

	public function metform_register_widgets( $widget_list ) {
		$widget_list[] = 'mf-igd-uploader';

		return $widget_list;
	}

	public function metform_may_create_entry_folder( $form_id, $form_data, $form_settings, $attributes ) {

		$input_widgets = \Metform\Widgets\Manifest::instance()->get_input_widgets();

		$widget_input_data = get_post_meta( $form_id, '_elementor_data', true );
		$widget_input_data = json_decode( $widget_input_data );

		$widgets = \MetForm\Core\Entries\Map_El::data( $widget_input_data, $input_widgets )->get_el();

		// Return early if fields are empty
		if ( empty( $widgets ) ) {
			return;
		}

		// Prepare igd_fields array and populate tags array with field values
		$igd_widgets = [];
		foreach ( $widgets as $key => $field ) {
			if ( $field->widgetType == 'mf-igd-uploader' ) {
				$igd_widgets[ $key ] = $field;
			}
		}

		if ( empty( $igd_widgets ) ) {
			return;
		}

		foreach ( $igd_widgets as $key => $widget ) {
			if ( ! isset( $form_data[ $key ] ) ) {
				continue;
			}

			$value = $form_data[ $key ];

			if ( empty( $value ) ) {
				continue;
			}

			$files = [];

			// Fetch file ids from the value text
			preg_match_all( '/file\/d\/(.*?)\/view/', $value, $matches );

			$file_ids = $matches[1];

			if ( empty( $file_ids ) ) {
				continue;
			}

			foreach ( $file_ids as $file_id ) {
				$files[] = App::instance()->get_file_by_id( $file_id );
			}

			$module_data = Shortcode::get_shortcode_data( $widget->module_id );

			$tag_data = [
				'form' => [
					'form_title' => $form_settings['form_title'],
					'form_id'    => $form_id,
				]
			];

			// Rename files
			$extra_tags = $this->handle_met_form_field_tags( $widgets, $form_data );

			$rename_files = [];
			foreach ( $files as $file ) {
				// We will rename the file name
				$tag_data['name'] = $file['name'];

				$name = igd_replace_template_tags( $tag_data, $extra_tags );

				$rename_files[] = [
					'id'   => $file['id'],
					'name' => $name,
				];
			}

			if ( ! empty( $rename_files ) ) {
				App::instance()->rename_files( $rename_files );
			}

			// Create Entry Folder
			$create_entry_folder   = ! empty( $module_data['createEntryFolders'] );
			$create_private_folder = ! empty( $module_data['createPrivateFolder'] );

			if ( ! $create_entry_folder && ! $create_private_folder ) {
				continue;
			}

			$entry_folder_name_template = $module_data['entryFolderNameTemplate'] ?? 'Entry (%entry_id%) - %form_title%';

			if ( false !== strpos( $entry_folder_name_template, '%entry_id%' ) ) {
				if ( $form_settings['store_entries'] ) {
					global $wpdb;
					$entry_id                     = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_type = 'metform-entry' ORDER BY ID DESC LIMIT 1" );
					$tag_data['form']['entry_id'] = $entry_id;
				}
			}

			if ( igd_contains_tags( 'user', $entry_folder_name_template ) ) {
				if ( is_user_logged_in() ) {
					$tag_data['user'] = get_userdata( get_current_user_id() );
				}
			}

			if ( igd_contains_tags( 'post', $entry_folder_name_template ) ) {
				$referrer = wp_get_referer();

				if ( ! empty( $referrer ) ) {
					$post_id = url_to_postid( $referrer );
					if ( ! empty( $post_id ) ) {
						$tag_data['post'] = get_post( $post_id );
						if ( $tag_data['post']->post_type == 'product' ) {
							$tag_data['wc_product'] = wc_get_product( $post_id );
						}
					}
				}
			}

			$tag_data['name'] = $entry_folder_name_template;
			$folder_name      = igd_replace_template_tags( $tag_data, $extra_tags );

			Uploader::instance()->create_entry_folder_and_move( $files, $folder_name, $module_data );
		}
	}

	private function handle_met_form_field_tags( $widgets, $form_data ) {
		$extra_tags = [];

		if ( ! empty( $widgets ) ) {
			foreach ( $widgets as $key => $field ) {
				if ( $field->widgetType == 'mf-igd-uploader' ) {
					continue;
				}

				$field_value = $form_data[ $key ];

				// Handle array values, such as checkboxes
				if ( is_array( $field_value ) ) {
					$field_value = implode( ', ', $field_value );
				}

				$extra_tags[ '%' . $key . '%' ] = $field_value;
			}

		}

		return $extra_tags;
	}

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self;
		}

		return self::$instance;
	}

}

Integrations::instance();
