<?php
/**
 * Plugin Name:         Responsive Portfolio Image Gallery - Portfolio Gallery
 * Plugin URI:          https://wordpress.org/plugins/responsive-portfolio-image-gallery/
 * Description:         Responsive image gallery plugin to build powerful, lightweight, filterable portfolio galleries on different posts or pages by SHORTCODE.
 * Version:             1.3
 * Requires at least:   5.2
 * Requires PHP:        7.4
 * Author:              Realwebcare
 * Author URI:          https://www.realwebcare.com/
 * Text Domain:         responsive-portfolio-image-gallery
 * Domain Path:         /languages
 * License:             GPL v2 or later
 * License URI:         http://www.gnu.org/licenses/gpl-2.0.html
 */

if (!defined('ABSPATH')) {
	exit; // Exit if accessed directly
}

if (!class_exists('RPGAL_Index')) {
	class RPGAL_Index
	{

		private static $instance;
		private function __construct()
		{
			// Check plugin version older than 1.3
			add_action('plugins_loaded', array($this, 'rpgal_check_version'));

			// Define plugin-specific constants.
			$this->define_constants();

			// Load necessary required files.
			$this->required_files();
		}

		public static function get_instances()
		{
			if (self::$instance) {
				return self::$instance;
			}

			self::$instance = new self();

			return self::$instance;
		}

		/**
		 * Checks and updates plugin options if the installed version is lower than the required version.
		 *
		 * This function runs when the plugin is loaded. If the stored plugin version is older than
		 * the specified version (1.3), it migrates existing options to the new format and updates
		 * the version in the database to prevent re-running the migration in future updates.
		 *
		 * @return void
		 */
		public function rpgal_check_version()
		{
			$current_version = '1.3'; // Set the new version
			$saved_version = get_option('rpgal_plugin_version', ''); // Get stored version

			// Only run migration for versions below 1.3
			if (empty($saved_version) || version_compare($saved_version, '1.3', '<')) {
				// Step 1: Migrate options
				$old_version_general = get_option('rcpig_general', []);
				$old_version_advance = get_option('rcpig_advanced', []);
				$old_version_style = get_option('rcpig_style', []);

				// Define option mappings: old_key => [new_option_group, new_key]
				$option_mappings = array(
					// General Options
					'rcpig_enable_portfolio_' => ['rpgal_general', 'rpgal_enable'],
					'rcpig_cat_include_' => ['rpgal_general', 'rpgal_categories'],
					'rcpig_number_of_post_' => ['rpgal_general', 'rpgal_postno'],
					'rcpig_post_order_' => ['rpgal_general', 'rpgal_postorder'],
					'rcpig_post_order_by_' => ['rpgal_general', 'rpgal_postorder_by'],
					'rcpig_show_plain_' => ['rpgal_general', 'rpgal_show_plain'],
					'rcpig_excerpt_length_' => ['rpgal_general', 'rpgal_excerpt_ln'],
					'rcpig_image_width_' => ['rpgal_general', 'rpgal_img_width'],
					'rcpig_image_height_' => ['rpgal_general', 'rpgal_img_height'],
					// Advanced Options
					'rcpig_filter_effect_' => ['rpgal_advanced', 'rpgal_filter_effect'],
					'rcpig_hover_direction_' => ['rpgal_advanced', 'rpgal_hover_dir'],
					'rcpig_hover_inverse_' => ['rpgal_advanced', 'rpgal_hover_inv'],
					'rcpig_hover_effect_' => ['rpgal_advanced', 'rpgal_hover_effect'],
					'rcpig_hide_excerpt_' => ['rpgal_advanced', 'rpgal_hide_excerpt'],
					'rcpig_expanding_height_' => ['rpgal_advanced', 'rpgal_exp_height'],
					'rcpig_show_wrapper_' => ['rpgal_advanced', 'rpgal_show_wrap'],
					// Style Options
					'rcpig_css_style_' => ['rpgal_style', 'rpgal_css_style'],
					'rcpig_custom_css_' => ['rpgal_style', 'rpgal_custom_css'],
				);

				// Prepare containers for new options
				$new_options = [
					'rpgal_general' => [],
					'rpgal_advanced' => [],
					'rpgal_style' => [],
				];

				// Copy over values from old to new
				foreach ($option_mappings as $old_key => $map) {
					list($new_group, $new_key) = $map;

					$value = null;

					if (strpos($old_key, 'rcpig_enable_portfolio_') === 0) {
						$value = isset($old_version_general[$old_key]) ? $old_version_general[$old_key] : null;
					} elseif (isset($old_version_general[$old_key])) {
						$value = $old_version_general[$old_key];
					} elseif (isset($old_version_advance[$old_key])) {
						$value = $old_version_advance[$old_key];
					} elseif (isset($old_version_style[$old_key])) {
						$value = $old_version_style[$old_key];
					}

					if (!is_null($value)) {
						$new_options[$new_group][$new_key] = $value;
					}
				}

				// Save each grouped new option if it contains data
				foreach ($new_options as $option_name => $option_data) {
					if (!empty($option_data)) {
						update_option($option_name, $option_data);
					}
				}

				// Step 2: Delete old option groups
				delete_option('rcpig_general');
				delete_option('rcpig_advanced');
				delete_option('rcpig_style');

				global $wpdb;

				// Step 3: Rename post meta keys
				$meta_rename_map = [
					'_first_button' => '_button_text',
					'_first_button_link' => '_button_link',
					'_first_button_tab' => '_button_ntab',
				];

				foreach ($meta_rename_map as $old_key => $new_key) {
					$wpdb->query(
						$wpdb->prepare(
							"UPDATE {$wpdb->postmeta} SET meta_key = %s WHERE meta_key = %s",
							$new_key,
							$old_key
						)
					);
				}

				// Step 4: Rename post type
				$wpdb->query(
					"UPDATE {$wpdb->posts} SET post_type = 'rpgal' WHERE post_type = 'rcpig'"
				);

				// Step 5: Rename taxonomy
				$wpdb->query(
					"UPDATE {$wpdb->term_taxonomy} SET taxonomy = 'rpgal-category' WHERE taxonomy = 'rcpig-category'"
				);

				// Step 6: Save updated plugin version
				update_option('rpgal_plugin_version', $current_version);
			}
		}

		/**
		 * Defines essential plugin constants.
		 *
		 * This method sets up constants that are used throughout the plugin for easy access
		 * to important paths and URLs, ensuring a consistent and maintainable structure.
		 *
		 * Constants defined:
		 * - `RPGAL_PLUGIN_PATH`: Absolute path to the plugin directory.
		 * - `RPGAL_PLUGIN_URL`: URL to the plugin directory.
		 * - `RPGAL_AUF`: Absolute path to the main plugin file.
		 *
		 * @return void
		 */
		private function define_constants()
		{
			define('RPGAL_PLUGIN_PATH', plugin_dir_path(__FILE__));
			define('RPGAL_PLUGIN_URL', plugin_dir_url(__FILE__));
			define('RPGAL_AUF', __FILE__);
		}

		/**
		 * Includes initialized files for the plugin.
		 *
		 * @return void
		 */
		private function required_files()
		{
			// Initialize the plugin
			require_once RPGAL_PLUGIN_PATH . 'init/init-rpgal.php';
		}
	}
}

RPGAL_Index::get_instances();
