<?php
require_once __DIR__ . '/constants.php';
require_once __DIR__ . '/utils.php';

register_activation_hook( __FILE__, 'r2b2_activate' );
function r2b2_activate() {
	r2b2_run_migrations();
}

add_action( 'plugins_loaded', 'r2b2_check_update' );
function r2b2_check_update() {
	$installed_version = get_option( 'r2b2_plugin_version' );

	if ( $installed_version !== R2B2_PLUGIN_VERSION ) {
		r2b2_run_migrations(); // Run the migrations
	}
}

function r2b2_run_migrations() {
	$installed_version = get_option( 'r2b2_plugin_version', '1.0.0' );

	if ( version_compare( $installed_version, '1.1.0', '<' ) ) {
		r2b2_migrate_to_110();
	}
	if ( version_compare( $installed_version, '1.1.2', '<' ) ) {
		r2b2_migrate_to_112();
	}

	update_option( 'r2b2_plugin_version', R2B2_PLUGIN_VERSION );
}

/**
 * Migrate from separate lists to one list with JSON encoded data.
 * @return void
 */
function r2b2_migrate_to_110() {
	$options        = get_option( R2B2_OPTIONS );
	$listPlacements = $options[ R2B2_OPTION_PLACEMENT_LIST ] ?? '';
	$listDelivery   = $options[ R2B2_OPTION_PLACEMENT_LIST_DELIVERY ] ?? '';
	$listDemo       = $options[ R2B2_OPTION_PLACEMENT_LIST_DEMO ] ?? '';

	$placements         = explode( "\n", $listPlacements ) ?? [];
	$placementsDelivery = explode( "\n", $listDelivery ) ?? [];
	$placementsDemo     = explode( "\n", $listDemo ) ?? [];
	$placementsData     = [];

	for ( $i = 0; $i < count( $placements ); $i ++ ) {
		try {
			$placement = preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $placements[ $i ] );
			if ( empty( $placement ) ) {
				continue;
			}
			$dgpm                 = explode( '/', strtolower( $placement ) );
			$placementsData[ $i ] = wp_json_encode( [
				R2B2_PL_DATA_DGPM            => [
					'd' => $dgpm[0],
					'g' => $dgpm[1],
					'p' => $dgpm[2],
					'm' => r2b2_is_placement_mobile( $placement ),
				],
				R2B2_PL_DATA_DELIVERY        => in_array( $placement, $placementsDelivery ),
				R2B2_PL_DATA_PARAGRAPH_INDEX => null,
				R2B2_PL_DATA_TABLE_INDEX     => null,
				R2B2_PL_DATA_DEMO            => in_array( $placement, $placementsDemo ),
			] );
		} catch ( Exception $e ) {
		}
	}

	$options[ R2B2_OPTION_PLACEMENT_LIST_DATA ] = join( "\n", $placementsData );
	unset( $options[ R2B2_OPTION_PLACEMENT_LIST ] );
	unset( $options[ R2B2_OPTION_PLACEMENT_LIST_DELIVERY ] );
	unset( $options[ R2B2_OPTION_PLACEMENT_LIST_DEMO ] );

	update_option( R2B2_OPTIONS, $options );
}

/**
 * Remove the empty placement that was generated in last migration.
 * @cite a:1:{s:23:"r2b2_settings_list_data";s:123:"{"dgpm":{"d":"","g":null,"p":null,"m":false},"delivery_enabled":true,"paragraph_index":null,"table_index":null,"demo":true}";}
 * @return void
 */
function r2b2_migrate_to_112() {
	$options    = get_option( R2B2_OPTIONS );
	$listData   = $options[ R2B2_OPTION_PLACEMENT_LIST_DATA ] ?? '';
	$placements = explode( "\n", $listData ) ?? [];

	$placementsDataOut = [];

	for ( $i = 0; $i < count( $placements ); $i ++ ) {
		try {
			$placement = preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $placements[ $i ] );
			if ( empty( $placement ) ) {
				continue;
			}
			$placementOrig = json_decode( $placement, true );
			if ( empty( $placementOrig ) || empty( $placementOrig[ R2B2_PL_DATA_DGPM ] ) || empty( $placementOrig[ R2B2_PL_DATA_DELIVERY ] ) ) {
				continue;
			}
			if ( empty( $placementOrig[ R2B2_PL_DATA_DGPM ]['d'] ) || empty( $placementOrig[ R2B2_PL_DATA_DGPM ]['g'] ) || empty( $placementOrig[ R2B2_PL_DATA_DGPM ]['p'] ) ) {
				continue;
			}
			$placementsDataOut[] = wp_json_encode( [
				R2B2_PL_DATA_DGPM            => [
					'd' => $placementOrig[ R2B2_PL_DATA_DGPM ]['d'],
					'g' => $placementOrig[ R2B2_PL_DATA_DGPM ]['g'],
					'p' => $placementOrig[ R2B2_PL_DATA_DGPM ]['p'],
					'm' => $placementOrig[ R2B2_PL_DATA_DGPM ]['m'] ?? false,
				],
				R2B2_PL_DATA_DELIVERY        => $placementOrig[ R2B2_PL_DATA_DELIVERY ],
				R2B2_PL_DATA_PARAGRAPH_INDEX => $placementOrig[ R2B2_PL_DATA_PARAGRAPH_INDEX ] ?? null,
				R2B2_PL_DATA_TABLE_INDEX     => $placementOrig[ R2B2_PL_DATA_TABLE_INDEX ] ?? null,
				R2B2_PL_DATA_DEMO            => $placementOrig[ R2B2_PL_DATA_DEMO ] ?? false,
			] );
		} catch ( Exception $e ) {
		}
	}

	$options[ R2B2_OPTION_PLACEMENT_LIST_DATA ] = join( "\n", $placementsDataOut );

	update_option( R2B2_OPTIONS, $options );
}
