Decompiled source of BigPimpin v1.0.11

TheBigPimpin.IL2CPP.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using HarmonyLib;
using Il2CppFishNet;
using Il2CppFishNet.Object;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.AvatarFramework;
using Il2CppScheduleOne.AvatarFramework.Animation;
using Il2CppScheduleOne.AvatarFramework.Equipping;
using Il2CppScheduleOne.Calling;
using Il2CppScheduleOne.Combat;
using Il2CppScheduleOne.Core.Equipping.Framework;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Dialogue;
using Il2CppScheduleOne.Doors;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.Effects;
using Il2CppScheduleOne.GameTime;
using Il2CppScheduleOne.Interaction;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Law;
using Il2CppScheduleOne.Map;
using Il2CppScheduleOne.Messaging;
using Il2CppScheduleOne.Money;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Actions;
using Il2CppScheduleOne.NPCs.Behaviour;
using Il2CppScheduleOne.NPCs.CharacterClasses;
using Il2CppScheduleOne.NPCs.Other;
using Il2CppScheduleOne.NPCs.Relation;
using Il2CppScheduleOne.NPCs.Responses;
using Il2CppScheduleOne.NPCs.Schedules;
using Il2CppScheduleOne.Persistence.Loaders;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Police;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Product.Packaging;
using Il2CppScheduleOne.Quests;
using Il2CppScheduleOne.ScriptableObjects;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Compass;
using Il2CppScheduleOne.UI.Handover;
using Il2CppScheduleOne.UI.Phone;
using Il2CppScheduleOne.UI.Phone.ContactsApp;
using Il2CppScheduleOne.UI.Phone.Messages;
using Il2CppScheduleOne.UI.Phone.ProductManagerApp;
using Il2CppScheduleOne.Vision;
using Il2CppSteamworks;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppTMPro;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using NVorbis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using S1API.Entities;
using S1API.Entities.Appearances.AccessoryFields;
using S1API.Entities.Appearances.BodyLayerFields;
using S1API.Entities.Appearances.CustomizationFields;
using S1API.Entities.Appearances.FaceLayerFields;
using S1API.Internal.Abstraction;
using S1API.Items;
using S1API.Map;
using S1API.Quests;
using S1API.Quests.Identifiers;
using S1API.Saveables;
using S1API.Utils;
using SteamNetworkLib;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using bigpimpin;
using bigpimpin.Brothel;
using bigpimpin.Clients;
using bigpimpin.Compat;
using bigpimpin.Gltf;
using bigpimpin.Gltf.Data;
using bigpimpin.Gltf.Processing;
using bigpimpin.Helper;
using bigpimpin.Messaging;
using bigpimpin.NPC;
using bigpimpin.Net;
using bigpimpin.Patches;
using bigpimpin.Products;
using bigpimpin.Quests;
using bigpimpin.UI;
using bigpimpin.World;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: MelonInfo(typeof(bigpimpinMod), "BigPimpin", "1.0.11", "Virtunerd & Fadestyle", null)]
[assembly: MelonGame(null, null)]
[assembly: MelonOptionalDependencies(new string[] { "NVorbis" })]
[assembly: MelonAdditionalDependencies(new string[] { "S1API" })]
[assembly: AssemblyTitle("Big Pimpin")]
[assembly: AssemblyDescription("Big Pimpin Mod")]
[assembly: AssemblyCompany("Virtunerd")]
[assembly: AssemblyProduct("Big Pimpin")]
[assembly: AssemblyCopyright("Copyright © Virtunerd")]
[assembly: ComVisible(false)]
[assembly: Guid("b6c7a9f1-6c4a-4f6b-b9e2-123456789abc")]
[assembly: MelonColor(255, 255, 0, 255)]
[assembly: MelonAuthorColor(255, 0, 200, 255)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyFileVersion("1.0.11")]
[assembly: AssemblyInformationalVersion("1.0.11")]
[assembly: AssemblyVersion("1.0.11.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace bigpimpin
{
	public class bigpimpinMod : MelonMod
	{
		private bool _dataInitialized = false;

		private bool _npcSpawned = false;

		private bool _nativeRegistryReady = false;

		private float _nativeRegistryTimer = 0f;

		private const float NATIVE_REGISTRY_INTERVAL = 1.5f;

		private const string MAIN_SCENE_NAME = "Main";

		private bool _inMainScene = false;

		private int _lastPayoutDay = -1;

		private float _startupTimer = 0f;

		private const float NPC_SPAWN_DELAY = 3f;

		private float _saveDataRefreshTimer = 0f;

		private const float SAVE_DATA_REFRESH_INTERVAL = 2.5f;

		public override void OnInitializeMelon()
		{
			ModConfig.Initialize();
			if (!ModConfig.ModEnabled)
			{
				MelonLogger.Msg("[bigpimpin] Mod disabled via MelonPreferences (BigPimpin.Mod=false). Skipping init.");
				return;
			}
			TryRegisterIl2Cpp(typeof(BigPimpinCompassController));
			TryRegisterIl2Cpp(typeof(BrothelMapMarker));
		}

		private static void TryRegisterIl2Cpp(Type t)
		{
			try
			{
				ClassInjector.RegisterTypeInIl2Cpp(t);
			}
			catch (Exception ex)
			{
				BPLog.Debug("[bigpimpin] IL2CPP registration skipped for " + t.Name + ": " + ex.Message);
			}
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			if (!ModConfig.ModEnabled)
			{
				return;
			}
			_inMainScene = string.Equals(sceneName, "Main", StringComparison.Ordinal);
			_lastPayoutDay = -1;
			if (!_inMainScene)
			{
				_nativeRegistryReady = false;
				_nativeRegistryTimer = 0f;
				_npcSpawned = false;
				_startupTimer = 0f;
				try
				{
					BrothelMusicController.Cleanup();
					return;
				}
				catch
				{
					return;
				}
			}
			try
			{
				EscortNPCRegistry.ResetForSceneReload();
			}
			catch (Exception)
			{
			}
			try
			{
				EscortStockManager.ResetTickClock();
			}
			catch
			{
			}
			try
			{
				EscortCokeDeadDropMonitor.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				PayphoneQuestStartController.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortLocationDisplayController.HideAll();
			}
			catch
			{
			}
			try
			{
				EscortDealerCollectHook.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortMobileInventoryHook.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortAutoHandoverWatcher.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				BigPimpinIntro.ResetQuestInstanceFlag();
			}
			catch
			{
			}
			try
			{
				WorldPositions.ResetBrothelDoorCache();
			}
			catch
			{
			}
			try
			{
				BrothelDeliveryLocations.ReassertRegistrations();
			}
			catch
			{
			}
			try
			{
				BrothelDeliveryLocations.TryEnsureAll();
			}
			catch
			{
			}
			try
			{
				EscortRoamingPOI.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortRoamingController.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortCityRoamingPOI.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortTracker.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortMugshotEnforcer.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortShowroomReveal.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				PimpProgressionManager.ResetNetworkSeed();
			}
			catch
			{
			}
			try
			{
				PimpFlowNetSync.ResetEarnedBaseline();
			}
			catch
			{
			}
			try
			{
				StashNetSync.Reset();
			}
			catch
			{
			}
			try
			{
				PunchNetSync.Reset();
			}
			catch
			{
			}
			try
			{
				BigPimpMapPoiController.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				WorldPoiScanner.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				BrothelMusicController.OnSceneLoaded();
			}
			catch
			{
			}
			MelonCoroutines.Start(DelayedApplyInitialRevealGate());
			MelonCoroutines.Start(DelayedScanWorldPois());
			MelonCoroutines.Start(DelayedReapplyLeverage());
		}

		private static IEnumerator DelayedApplyInitialRevealGate()
		{
			yield return (object)new WaitForSeconds(2f);
			try
			{
				EscortShowroomReveal.ApplyInitialGlbVisibility();
			}
			catch
			{
			}
		}

		private static IEnumerator DelayedScanWorldPois()
		{
			yield return (object)new WaitForSeconds(5f);
			try
			{
				WorldPoiScanner.Scan();
			}
			catch
			{
			}
			try
			{
				EscortRoamingPOI.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortCityRoamingPOI.ResetForSceneReload();
			}
			catch
			{
			}
		}

		private static IEnumerator DelayedReapplyLeverage()
		{
			yield return (object)new WaitForSeconds(6f);
			try
			{
				BlackmailRewardPatches.ReapplyActiveLeverage();
			}
			catch
			{
			}
		}

		private static void PerformResetAllHookers()
		{
			try
			{
				ModConfig.ClearResetAllHookers();
			}
			catch
			{
			}
			try
			{
				if (!NetworkHelper.IsHost)
				{
					return;
				}
			}
			catch
			{
			}
			try
			{
				EscortStockManager.ResetAllPunchStats();
			}
			catch
			{
			}
			try
			{
				PimpProgressionManager.ResetProgress();
			}
			catch
			{
			}
			try
			{
				EscortLocationDisplayController.Refresh();
			}
			catch
			{
			}
			try
			{
				BigPimpinSaveData.Instance?.PushNow();
			}
			catch
			{
			}
			try
			{
				BigPimpMessaging.SendPimpMessageExternal("Aight, clean slate. All the hoes reset, and I'm back at my spot behind the tattoo joint. Let's run it again.");
			}
			catch
			{
			}
			try
			{
				BPLog.Trace("pimp", "Reset All Hookers executed (matrix + progression reset, big pimp returned).");
			}
			catch
			{
			}
		}

		public override void OnUpdate()
		{
			if (!ModConfig.ModEnabled)
			{
				return;
			}
			try
			{
				ModNet.Tick(Time.deltaTime);
			}
			catch
			{
			}
			if (!_dataInitialized)
			{
				TryInitializeData();
			}
			else
			{
				if (!_inMainScene)
				{
					return;
				}
				BrothelManager.Update(Time.deltaTime);
				try
				{
					BrothelMusicController.Update(Time.deltaTime);
				}
				catch
				{
				}
				EscortContractService.Update(Time.deltaTime);
				EscortLocationDisplayController.Update(Time.deltaTime);
				EscortAutoHandoverWatcher.Update(Time.deltaTime);
				PayphoneQuestStartController.Update(Time.deltaTime);
				try
				{
					IntroNetSync.Tick(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					PimpFlowNetSync.Tick(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					StashNetSync.Tick(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					PunchNetSync.Tick(Time.deltaTime);
				}
				catch
				{
				}
				BigPimpMessaging.Update();
				try
				{
					bool flag = false;
					try
					{
						flag = ModNet.IsMultiplayer;
					}
					catch
					{
					}
					if (!NetworkHelper.IsHost || flag)
					{
						BigPimpNPC.EnsureClientModelVisible();
					}
					else
					{
						BigPimpNPC.EnsureNpcAnchored();
					}
				}
				catch
				{
				}
				try
				{
					BigPimpNPC.EnforceDummyHidden(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					MeetPimpAudioController.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					BigPimpMapPoiController.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					EscortContractPatches.TickCustomerRestoreWatchdog(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					if (ModConfig.ResetAllHookersRequested)
					{
						PerformResetAllHookers();
					}
				}
				catch
				{
				}
				try
				{
					EscortRoamingController.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					EscortTracker.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					EscortMugshotEnforcer.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					EscortStockReminders.EnsureWired();
				}
				catch
				{
				}
				try
				{
					EscortStockManager.Tick();
				}
				catch
				{
				}
				try
				{
					TimeManager instance = NetworkSingleton<TimeManager>.Instance;
					if ((Object)(object)instance != (Object)null)
					{
						int elapsedDays = instance.ElapsedDays;
						BlackmailManager.TickWeeklyTithe(elapsedDays);
						if (_lastPayoutDay < 0)
						{
							_lastPayoutDay = elapsedDays;
						}
						else if (elapsedDays > _lastPayoutDay)
						{
							_lastPayoutDay = elapsedDays;
							try
							{
								DailyPayoutManager.OnDayEnded();
							}
							catch
							{
							}
						}
					}
				}
				catch
				{
				}
				try
				{
					EscortCokeDeadDropMonitor.Tick();
				}
				catch
				{
				}
				try
				{
					EscortDealerCollectHook.Tick();
				}
				catch
				{
				}
				try
				{
					EscortMobileInventoryHook.Tick();
				}
				catch
				{
				}
				try
				{
					EscortInventoryManager.TickDrainStashCoke(Time.deltaTime);
				}
				catch
				{
				}
				if (!_nativeRegistryReady)
				{
					TryInitNativeRegistry();
				}
				if (!_npcSpawned)
				{
					_startupTimer += Time.deltaTime;
					if (_startupTimer >= 3f)
					{
						TrySpawnNPC();
					}
				}
				EscortProductRegistry.TryApplyPendingRefresh();
				_saveDataRefreshTimer -= Time.deltaTime;
				if (_saveDataRefreshTimer <= 0f)
				{
					_saveDataRefreshTimer = 2.5f;
					BigPimpinSaveData.Instance?.PushNow();
				}
				try
				{
					BigPimpNPC.ApplyVisibilityFromRaveState();
				}
				catch
				{
				}
			}
		}

		private void TryInitNativeRegistry()
		{
			_nativeRegistryTimer -= Time.deltaTime;
			if (_nativeRegistryTimer > 0f)
			{
				return;
			}
			_nativeRegistryTimer = 1.5f;
			try
			{
				bool flag = BrothelDeliveryLocations.TryEnsureAll();
				EscortProductRegistry.RegisterAll();
				if (flag && EscortProductRegistry.All.Count > 0)
				{
					_nativeRegistryReady = true;
					MelonLogger.Msg("[bigpimpin] Native escort registry ready (products + delivery locations).");
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] TryInitNativeRegistry: " + ex.Message);
			}
		}

		private void TryInitializeData()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			try
			{
				EscortManager.Initialize();
				BrothelManager.Initialize();
				BigPimpMessaging.Initialize();
				ModProductRegistry.RegisterProducts();
				new BigPimpinSaveData();
				GameObject val = new GameObject("BigPimpinCompass");
				val.AddComponent<BigPimpinCompassController>();
				Object.DontDestroyOnLoad((Object)(object)val);
				EscortContractService.Initialize();
				_dataInitialized = true;
				MelonLogger.Msg("[bigpimpin] Data initialized.");
			}
			catch (Exception ex)
			{
				MelonLogger.Error("[bigpimpin] Init failed: " + ex.Message);
			}
		}

		private void TrySpawnNPC()
		{
			try
			{
				BigPimpNPC instance = BigPimpNPC.Instance;
				if (instance != null)
				{
					GameObject val = null;
					try
					{
						val = ((NPC)instance).gameObject;
					}
					catch
					{
					}
					if ((Object)(object)val != (Object)null)
					{
						_npcSpawned = true;
						BPLog.Debug("[bigpimpin][spawn-diag] BigPimpNPC.Instance alive (host=" + NetworkHelper.IsHost + ") -> attaching GLB to it.");
						try
						{
							BigPimpNPC.EnsureModelOnExistingNpc();
							return;
						}
						catch
						{
							return;
						}
					}
				}
				try
				{
					NPC nPC = NPCManager.GetNPC("big_pimp");
					if ((Object)(object)nPC != (Object)null && (Object)(object)((Component)nPC).gameObject != (Object)null)
					{
						_npcSpawned = true;
						BPLog.Debug("[bigpimpin][spawn-diag] 'big_pimp' already in NPCManager (host=" + NetworkHelper.IsHost + ") -> attaching GLB to existing NPC.");
						try
						{
							BigPimpNPC.EnsureModelOnExistingNpc();
							return;
						}
						catch
						{
							return;
						}
					}
				}
				catch
				{
				}
				_startupTimer = 0f;
			}
			catch (Exception ex)
			{
				BPLog.DebugWarn("[bigpimpin][spawn-diag] TrySpawnNPC threw (host=" + NetworkHelper.IsHost + "): " + ex);
				_startupTimer = 0f;
			}
		}
	}
	internal sealed class BigPimpinSaveData : Saveable
	{
		[SaveableField("brothel_state")]
		private BrothelSaveData _data = new BrothelSaveData();

		public static BigPimpinSaveData Instance { get; private set; }

		public BigPimpinSaveData()
		{
			try
			{
				_data = BrothelSaveData.CreateFromCurrentState();
			}
			catch
			{
			}
			Instance = this;
		}

		public void PushNow()
		{
			try
			{
				_data = BrothelSaveData.CreateFromCurrentState();
			}
			catch (Exception)
			{
			}
		}

		protected override void OnCreated()
		{
			try
			{
				((Registerable)this).OnCreated();
			}
			catch
			{
			}
			try
			{
				BrothelSaveData.ResetAllToNewGame();
				MelonLogger.Msg("[bigpimpin] OnCreated: no mod save-blob -> reset all progression to New-Game defaults.");
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] OnCreated New-Game reset failed: " + ex.Message);
			}
		}

		protected override void OnLoaded()
		{
			MelonLogger.Msg($"[bigpimpin] OnLoaded: data={((_data == null) ? "NULL" : "ok")}, IntroCompleted={_data?.IntroCompleted ?? false}, Escorts={(_data?.Escorts?.Count).GetValueOrDefault()}.");
			BrothelSaveData.LoadIntoCurrentState(_data ?? new BrothelSaveData());
			BrothelManager.SyncAfterLoad();
			try
			{
				BigPimpinIntro.EnsureQuestStarted();
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] EnsureQuestStarted (OnLoaded): " + ex.Message);
			}
		}

		protected override void OnSaved()
		{
			try
			{
				_data = BrothelSaveData.CreateFromCurrentState();
			}
			catch
			{
			}
		}
	}
}
namespace bigpimpin.Quests
{
	[QuestName("Big Pimp's Offer")]
	internal sealed class BigPimpIntroQuestId : IQuestIdentifier
	{
	}
	internal sealed class BigPimpIntroQuest : Quest
	{
		private static Sprite _cachedIcon;

		private static readonly FieldInfo _s1QuestEntryField = typeof(QuestEntry).GetField("S1QuestEntry", BindingFlags.Instance | BindingFlags.NonPublic);

		private float _lastPoiReapplyTime;

		private bool _postQuestPoiCleared;

		protected override string Title => "Big Pimp's Offer";

		protected override string Description => "Some weird looking - tiny - pimp called \"Big Pimp\" hit you up. Hear him out and see what the deal is.";

		protected override bool AutoBegin => true;

		protected override Sprite QuestIcon => GetCachedIcon();

		public QuestEntry EntryNelsonCall { get; private set; }

		public QuestEntry EntryMeetBigPimp { get; private set; }

		public QuestEntry EntryRead { get; private set; }

		public QuestEntry EntryReply { get; private set; }

		public QuestEntry EntryBuy { get; private set; }

		public QuestEntry EntryFinalStep { get; private set; }

		public QuestEntry EntryFirstHandover => EntryFinalStep;

		public BigPimpIntroQuest()
		{
			EntryNelsonCall = ((Quest)this).AddEntry("Answer Uncle Nelson's payphone call", (Vector3?)null);
			EntryMeetBigPimp = ((Quest)this).AddEntry("Go to the meeting behind Midnight Suites", (Vector3?)null);
			EntryRead = ((Quest)this).AddEntry("Read Big Pimp's message", (Vector3?)null);
			EntryReply = ((Quest)this).AddEntry("Reply to Big Pimp", (Vector3?)null);
			EntryBuy = ((Quest)this).AddEntry("Buy the brothel", (Vector3?)null);
			EntryFinalStep = ((Quest)this).AddEntry("Buy Street, Madam, Executive, then Presidential for Midnight Suites & keep the DeadDrop (or talk to an Escort) supplied with coke baggies. Upgrade your pimp status to buy more hoes.", (Vector3?)null);
			SuppressVanillaPoiMarkers();
			EntryFinalStep.OnComplete += OnFinalStepComplete;
			BigPimpinIntro.QuestInstanceCreated = true;
			MelonLogger.Msg("[bigpimpin] BigPimpIntroQuest constructed.");
		}

		public void EnsureBigPimpPoi()
		{
			SuppressVanillaPoiMarkers();
		}

		public void SuppressVanillaPoiMarkers()
		{
			SuppressVanillaPoiMarkersExcept(null);
		}

		public void RefreshMapPois()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			QuestEntry bigPimpMapEntry = GetBigPimpMapEntry();
			SuppressVanillaPoiMarkersExcept(bigPimpMapEntry);
			if (bigPimpMapEntry == null)
			{
				return;
			}
			try
			{
				bigPimpMapEntry.POIPosition = WorldPositions.GetBigPimpMeetingPosition();
				HideVanillaCompassReticle(bigPimpMapEntry);
				MelonCoroutines.Start(HideVanillaCompassReticleLate(bigPimpMapEntry));
			}
			catch
			{
			}
		}

		public void TickMarkerSuppression()
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				QuestEntry bigPimpMapEntry = GetBigPimpMapEntry();
				if (bigPimpMapEntry == null)
				{
					if (!_postQuestPoiCleared)
					{
						_postQuestPoiCleared = true;
						try
						{
							SuppressVanillaPoiMarkersExcept(null);
							return;
						}
						catch
						{
							return;
						}
					}
					return;
				}
				_postQuestPoiCleared = false;
				HideVanillaCompassReticle(bigPimpMapEntry);
				float unscaledTime = Time.unscaledTime;
				if (!(unscaledTime - _lastPoiReapplyTime >= 2f))
				{
					return;
				}
				_lastPoiReapplyTime = unscaledTime;
				try
				{
					Vector3 bigPimpMeetingPosition = WorldPositions.GetBigPimpMeetingPosition();
					Vector3 pOIPosition = bigPimpMapEntry.POIPosition;
					Vector3 val = pOIPosition - bigPimpMeetingPosition;
					if (((Vector3)(ref val)).sqrMagnitude > 0.25f)
					{
						bigPimpMapEntry.POIPosition = bigPimpMeetingPosition;
					}
				}
				catch
				{
				}
			}
			catch
			{
			}
		}

		private void SuppressVanillaPoiMarkersExcept(QuestEntry keep)
		{
			try
			{
				if (EntryNelsonCall != keep)
				{
					QuestEntry entryNelsonCall = EntryNelsonCall;
					if (entryNelsonCall != null)
					{
						entryNelsonCall.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryMeetBigPimp != keep)
				{
					QuestEntry entryMeetBigPimp = EntryMeetBigPimp;
					if (entryMeetBigPimp != null)
					{
						entryMeetBigPimp.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryRead != keep)
				{
					QuestEntry entryRead = EntryRead;
					if (entryRead != null)
					{
						entryRead.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryReply != keep)
				{
					QuestEntry entryReply = EntryReply;
					if (entryReply != null)
					{
						entryReply.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryBuy != keep)
				{
					QuestEntry entryBuy = EntryBuy;
					if (entryBuy != null)
					{
						entryBuy.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryFinalStep != keep)
				{
					QuestEntry entryFinalStep = EntryFinalStep;
					if (entryFinalStep != null)
					{
						entryFinalStep.ClearPOI();
					}
				}
			}
			catch
			{
			}
		}

		private QuestEntry GetBigPimpMapEntry()
		{
			return null;
		}

		private static IEnumerator HideVanillaCompassReticleLate(QuestEntry entry)
		{
			for (int i = 0; i < 12; i++)
			{
				yield return null;
				HideVanillaCompassReticle(entry);
			}
		}

		private static void HideVanillaCompassReticle(QuestEntry entry)
		{
			try
			{
				object? obj = _s1QuestEntryField?.GetValue(entry);
				QuestEntry val = (QuestEntry)((obj is QuestEntry) ? obj : null);
				Element val2 = ((val != null) ? val.compassElement : null);
				if (val2 != null)
				{
					val2.Visible = false;
					if ((Object)(object)val2.Rect != (Object)null && (Object)(object)((Component)val2.Rect).gameObject != (Object)null)
					{
						((Component)val2.Rect).gameObject.SetActive(false);
					}
					if ((Object)(object)val2.Group != (Object)null)
					{
						val2.Group.alpha = 0f;
					}
				}
			}
			catch
			{
			}
		}

		private static Sprite GetCachedIcon()
		{
			if ((Object)(object)_cachedIcon != (Object)null)
			{
				return _cachedIcon;
			}
			try
			{
				_cachedIcon = ImageUtils.LoadImageFromResource(Assembly.GetExecutingAssembly(), "bigpimpin.assets.icon.png", 100f, (FilterMode)1);
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] QuestIcon load failed: " + ex.Message);
			}
			return _cachedIcon;
		}

		private static void OnFinalStepComplete()
		{
			MelonLogger.Msg("[bigpimpin] BigPimpIntroQuest fully completed.");
		}
	}
}
namespace bigpimpin.Products
{
	internal static class EscortProductRegistry
	{
		private static readonly Dictionary<EscortTier, ProductDefinition> _byTier = new Dictionary<EscortTier, ProductDefinition>();

		private static readonly Dictionary<string, EscortTier> _byId = new Dictionary<string, EscortTier>(StringComparer.OrdinalIgnoreCase);

		private static Sprite _cachedProductSprite;

		private static Texture2D _cachedProductTexture;

		private const string ProductIconResource = "bigpimpin.assets.product.png";

		private static readonly Dictionary<EscortTier, Sprite> _tierSprites = new Dictionary<EscortTier, Sprite>();

		private static readonly Dictionary<EscortTier, string[]> _tierIconResources = new Dictionary<EscortTier, string[]>
		{
			{
				EscortTier.Street,
				new string[2] { "bigpimpin.assets.date_street.png", "bigpimpin.assets.street.png" }
			},
			{
				EscortTier.Madam,
				new string[2] { "bigpimpin.assets.date_madam.png", "bigpimpin.assets.madam.png" }
			},
			{
				EscortTier.Executive,
				new string[2] { "bigpimpin.assets.date_exec.png", "bigpimpin.assets.executive.png" }
			},
			{
				EscortTier.Presidential,
				new string[2] { "bigpimpin.assets.date_pres.png", "bigpimpin.assets.presidencial.png" }
			}
		};

		private static readonly Dictionary<string, bool> _listedById = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, int> _persistedPriceById = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

		private static readonly string[] TemplateCandidates = new string[1] { "ogkush" };

		private static bool _pendingRefresh;

		public static IReadOnlyDictionary<EscortTier, ProductDefinition> All => _byTier;

		public static ProductDefinition Get(EscortTier tier)
		{
			_byTier.TryGetValue(tier, out var value);
			return value;
		}

		public static bool TryResolveTier(string productId, out EscortTier tier)
		{
			return _byId.TryGetValue(productId ?? string.Empty, out tier);
		}

		public static EscortTier ResolveTier(string productId)
		{
			_byId.TryGetValue(productId ?? string.Empty, out var value);
			return value;
		}

		private static bool IsTierUnlocked(string productId)
		{
			try
			{
				EscortTier tier;
				return TryResolveTier(productId, out tier) && EscortDealerUnlocks.IsUnlocked(tier);
			}
			catch
			{
				return false;
			}
		}

		private static bool IsTierUnlocked(ProductDefinition def)
		{
			try
			{
				return (Object)(object)def != (Object)null && IsTierUnlocked(((BaseItemDefinition)def).ID);
			}
			catch
			{
				return false;
			}
		}

		public static void RegisterAll()
		{
			try
			{
				ProductDefinition val = TryFindTemplate();
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				int count = _byTier.Count;
				Register(EscortTier.Street, "bp_escort_street", "Street Date", 350, val);
				Register(EscortTier.Madam, "bp_escort_madam", "Madam Date", 500, val);
				Register(EscortTier.Executive, "bp_escort_exec", "Executive Date", 1500, val);
				Register(EscortTier.Presidential, "bp_escort_pres", "Presidential Date", 2500, val);
				foreach (ProductDefinition value2 in _byTier.Values)
				{
					if ((Object)(object)value2 != (Object)null)
					{
						SyncWithProductManager(value2);
					}
				}
				if (_byTier.Count <= count)
				{
				}
			}
			catch (Exception value)
			{
				MelonLogger.Error($"[bigpimpin] EscortProductRegistry.RegisterAll: {value}");
			}
		}

		private static ProductDefinition TryFindTemplate()
		{
			for (int i = 0; i < TemplateCandidates.Length; i++)
			{
				try
				{
					ItemDefinition item = Registry.GetItem(TemplateCandidates[i]);
					ProductDefinition val = (((Object)(object)item != (Object)null) ? ((Il2CppObjectBase)item).TryCast<ProductDefinition>() : null);
					if ((Object)(object)val != (Object)null)
					{
						return val;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private static void Register(EscortTier tier, string id, string displayName, int basePrice, ProductDefinition template)
		{
			try
			{
				if (_byTier.ContainsKey(tier))
				{
					return;
				}
				ItemDefinition item = Registry.GetItem(id);
				ProductDefinition val;
				if ((Object)(object)item != (Object)null)
				{
					val = ((Il2CppObjectBase)item).TryCast<ProductDefinition>();
					if ((Object)(object)val != (Object)null)
					{
						PatchItemDefinition(val, id, displayName, basePrice, tier);
					}
				}
				else
				{
					val = Object.Instantiate<ProductDefinition>(template);
					PatchItemDefinition(val, id, displayName, basePrice, tier);
					try
					{
						Singleton<Registry>.Instance.AddToRegistry((ItemDefinition)(object)val);
					}
					catch (Exception)
					{
					}
				}
				if (!((Object)(object)val == (Object)null))
				{
					_byTier[tier] = val;
					_byId[id] = tier;
				}
			}
			catch (Exception value)
			{
				MelonLogger.Error($"[bigpimpin] EscortProductRegistry.Register({id}): {value}");
			}
		}

		private static void PatchItemDefinition(ProductDefinition clone, string id, string displayName, int basePrice, EscortTier tier)
		{
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Expected O, but got Unknown
			try
			{
				((Object)clone).name = id;
			}
			catch
			{
			}
			try
			{
				((BaseItemDefinition)clone).ID = id;
			}
			catch
			{
			}
			try
			{
				((BaseItemDefinition)clone).Name = displayName;
			}
			catch
			{
			}
			try
			{
				((BaseItemDefinition)clone).Description = displayName + " booking — handoff at the Midnight Suites door.";
			}
			catch
			{
			}
			try
			{
				clone.BasePrice = basePrice;
			}
			catch
			{
			}
			try
			{
				clone.MarketValue = basePrice;
			}
			catch
			{
			}
			try
			{
				((StorableItemDefinition)clone).BasePurchasePrice = basePrice;
			}
			catch
			{
			}
			try
			{
				switch (tier)
				{
				case EscortTier.Street:
					clone.BaseAddictiveness = 0f;
					break;
				case EscortTier.Madam:
					clone.BaseAddictiveness = 0.5f;
					break;
				case EscortTier.Executive:
					clone.BaseAddictiveness = 0.75f;
					break;
				case EscortTier.Presidential:
					clone.BaseAddictiveness = 1f;
					break;
				}
			}
			catch
			{
			}
			int value;
			float num = ((_persistedPriceById.TryGetValue(id, out value) && value > 0) ? value : basePrice);
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				if ((Object)(object)instance != (Object)null && instance.ProductPrices != null)
				{
					instance.ProductPrices[clone] = num;
				}
			}
			catch
			{
			}
			try
			{
				((BaseItemDefinition)clone).StackLimit = 1;
			}
			catch
			{
			}
			try
			{
				clone.FunctionalProduct = null;
			}
			catch
			{
			}
			try
			{
				((ItemDefinition)clone).Equippable = null;
			}
			catch
			{
			}
			try
			{
				((StorableItemDefinition)clone).StationItem = null;
			}
			catch
			{
			}
			try
			{
				((StorableItemDefinition)clone).StoredItem = null;
			}
			catch
			{
			}
			try
			{
				clone.ValidPackaging = GameCompat.RefArray<PackagingDefinition>(0);
			}
			catch
			{
				try
				{
					clone.ValidPackaging = null;
				}
				catch
				{
				}
			}
			try
			{
				((StorableItemDefinition)clone).ShopCategories = null;
			}
			catch
			{
			}
			try
			{
				((StorableItemDefinition)clone).CombatUtility = 0f;
			}
			catch
			{
			}
			try
			{
				List<DrugTypeContainer> val = new List<DrugTypeContainer>();
				DrugTypeContainer val2 = new DrugTypeContainer
				{
					DrugType = (EDrugType)5
				};
				val.Add(val2);
				clone.DrugTypes = val;
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] CHANGE-280 assign DrugTypes(Heroin) failed for " + id + ": " + ex.Message);
			}
			try
			{
				Sprite val3 = LoadTierSprite(tier);
				if ((Object)(object)val3 != (Object)null)
				{
					((BaseItemDefinition)clone).Icon = val3;
				}
			}
			catch (Exception)
			{
			}
		}

		private static Sprite LoadProductSprite()
		{
			if ((Object)(object)_cachedProductSprite != (Object)null)
			{
				return _cachedProductSprite;
			}
			_cachedProductSprite = LoadSpriteFromResource("bigpimpin.assets.product.png", out _cachedProductTexture);
			return _cachedProductSprite;
		}

		private static Sprite LoadTierSprite(EscortTier tier)
		{
			if (_tierSprites.TryGetValue(tier, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (_tierIconResources.TryGetValue(tier, out var value2))
			{
				for (int i = 0; i < value2.Length; i++)
				{
					Texture2D tex;
					Sprite val = LoadSpriteFromResource(value2[i], out tex);
					if ((Object)(object)val != (Object)null)
					{
						_tierSprites[tier] = val;
						return val;
					}
				}
			}
			Sprite val2 = LoadProductSprite();
			if ((Object)(object)val2 != (Object)null)
			{
				_tierSprites[tier] = val2;
			}
			return val2;
		}

		private static Sprite LoadSpriteFromResource(string resourceName, out Texture2D tex)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			tex = null;
			try
			{
				Assembly executingAssembly = Assembly.GetExecutingAssembly();
				using Stream stream = executingAssembly.GetManifestResourceStream(resourceName);
				if (stream == null)
				{
					return null;
				}
				byte[] array = new byte[stream.Length];
				stream.Read(array, 0, array.Length);
				Texture2D val = new Texture2D(2, 2);
				if (!ImageConversion.LoadImage(val, Il2CppStructArray<byte>.op_Implicit(array)))
				{
					return null;
				}
				Object.DontDestroyOnLoad((Object)(object)val);
				tex = val;
				Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				Object.DontDestroyOnLoad((Object)(object)val2);
				return val2;
			}
			catch
			{
				return null;
			}
		}

		public static bool IsEscortProduct(ProductDefinition def)
		{
			try
			{
				return (Object)(object)def != (Object)null && _byId.ContainsKey(((BaseItemDefinition)def).ID ?? string.Empty);
			}
			catch
			{
				return false;
			}
		}

		public static bool IsListed(ProductDefinition def)
		{
			try
			{
				return (Object)(object)def != (Object)null && IsListed(((BaseItemDefinition)def).ID);
			}
			catch
			{
				return false;
			}
		}

		public static bool IsListed(string productId)
		{
			if (string.IsNullOrWhiteSpace(productId))
			{
				return false;
			}
			bool value;
			return _listedById.TryGetValue(productId, out value) && value;
		}

		public static void SetListed(ProductDefinition def, bool listed)
		{
			if ((Object)(object)def == (Object)null)
			{
				return;
			}
			try
			{
				SetListed(((BaseItemDefinition)def).ID, listed);
			}
			catch
			{
			}
		}

		public static void SetListed(string productId, bool listed)
		{
			if (!string.IsNullOrWhiteSpace(productId))
			{
				if (!BigPimpinIntro.IsActivated())
				{
					listed = false;
				}
				if (!IsTierUnlocked(productId))
				{
					listed = false;
				}
				_listedById[productId] = listed;
				SyncListedProduct(productId, listed);
			}
		}

		public static Dictionary<string, bool> GetListedStateForSave()
		{
			return new Dictionary<string, bool>(_listedById, StringComparer.OrdinalIgnoreCase);
		}

		public static void LoadListedState(Dictionary<string, bool> listedById)
		{
			_listedById.Clear();
			if (listedById == null)
			{
				return;
			}
			foreach (KeyValuePair<string, bool> item in listedById)
			{
				if (!string.IsNullOrWhiteSpace(item.Key))
				{
					_listedById[item.Key] = item.Value;
				}
			}
			foreach (KeyValuePair<string, bool> item2 in _listedById)
			{
				if (!string.IsNullOrWhiteSpace(item2.Key))
				{
					try
					{
						SyncListedProduct(item2.Key, item2.Value);
					}
					catch
					{
					}
				}
			}
		}

		public static Dictionary<string, int> GetPricesForSave()
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				float num2 = default(float);
				foreach (KeyValuePair<EscortTier, ProductDefinition> item in _byTier)
				{
					ProductDefinition value = item.Value;
					if (!((Object)(object)value == (Object)null))
					{
						float num = 0f;
						num = ((!((Object)(object)instance != (Object)null) || instance.ProductPrices == null || !instance.ProductPrices.TryGetValue(value, ref num2)) ? value.BasePrice : num2);
						int num3 = Mathf.RoundToInt(num);
						if (num3 > 0)
						{
							dictionary[((BaseItemDefinition)value).ID] = num3;
						}
					}
				}
			}
			catch
			{
			}
			return dictionary;
		}

		public static void LoadPricesState(Dictionary<string, int> prices)
		{
			_persistedPriceById.Clear();
			ProductManager instance = NetworkSingleton<ProductManager>.Instance;
			if (prices == null)
			{
				return;
			}
			foreach (KeyValuePair<string, int> price in prices)
			{
				if (string.IsNullOrWhiteSpace(price.Key) || price.Value <= 0)
				{
					continue;
				}
				_persistedPriceById[price.Key] = price.Value;
				ProductDefinition val = null;
				try
				{
					ItemDefinition item = Registry.GetItem(price.Key);
					val = ((item != null) ? ((Il2CppObjectBase)item).TryCast<ProductDefinition>() : null);
				}
				catch
				{
				}
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				try
				{
					if ((Object)(object)instance != (Object)null && instance.ProductPrices != null)
					{
						instance.ProductPrices[val] = price.Value;
					}
				}
				catch
				{
				}
			}
		}

		private static void ApplyTierVisibilityGate(ProductDefinition def)
		{
			if ((Object)(object)def == (Object)null || (BigPimpinIntro.IsActivated() && IsTierUnlocked(def)))
			{
				return;
			}
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				if (((instance != null) ? instance.AllProducts : null) != null && instance.AllProducts.Contains(def))
				{
					instance.AllProducts.Remove(def);
				}
			}
			catch
			{
			}
			try
			{
				List<ProductDefinition> discoveredProducts = ProductManager.DiscoveredProducts;
				if (discoveredProducts != null && discoveredProducts.Contains(def))
				{
					discoveredProducts.Remove(def);
				}
			}
			catch
			{
			}
			try
			{
				SyncListedProduct(((BaseItemDefinition)def).ID, listed: false);
			}
			catch
			{
			}
		}

		private static void SyncWithProductManager(ProductDefinition def)
		{
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					List<ProductDefinition> allProducts = instance.AllProducts;
					if (allProducts != null && !allProducts.Contains(def))
					{
						allProducts.Add(def);
					}
				}
			}
			catch
			{
			}
			try
			{
				List<ProductDefinition> discoveredProducts = ProductManager.DiscoveredProducts;
				if (discoveredProducts != null && !discoveredProducts.Contains(def))
				{
					discoveredProducts.Add(def);
				}
			}
			catch
			{
			}
			try
			{
				if ((Object)(object)def != (Object)null && _listedById.TryGetValue(((BaseItemDefinition)def).ID, out var value))
				{
					SyncListedProduct(((BaseItemDefinition)def).ID, value);
				}
			}
			catch
			{
			}
		}

		public static void ReapplyVisibility()
		{
			try
			{
				foreach (ProductDefinition value in _byTier.Values)
				{
					if (!((Object)(object)value == (Object)null))
					{
						SyncWithProductManager(value);
						ApplyTierVisibilityGate(value);
					}
				}
				RequestProductManagerRefresh();
			}
			catch
			{
			}
		}

		public static void RefreshVisibility()
		{
			try
			{
				foreach (ProductDefinition value in _byTier.Values)
				{
					if (!((Object)(object)value == (Object)null))
					{
						SyncWithProductManager(value);
						if (BigPimpinIntro.IsActivated() && IsTierUnlocked(value) && !IsListed(value))
						{
							SetListed(value, listed: true);
						}
						ApplyTierVisibilityGate(value);
					}
				}
				RequestProductManagerRefresh();
			}
			catch (Exception)
			{
			}
		}

		private static void SyncListedProduct(string productId, bool listed)
		{
			if (!BigPimpinIntro.IsActivated())
			{
				listed = false;
			}
			if (listed && !IsTierUnlocked(productId))
			{
				listed = false;
			}
			ProductDefinition val = null;
			try
			{
				ItemDefinition item = Registry.GetItem(productId);
				val = ((item != null) ? ((Il2CppObjectBase)item).TryCast<ProductDefinition>() : null);
			}
			catch
			{
			}
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				List<ProductDefinition> listedProducts = ProductManager.ListedProducts;
				if (listedProducts != null)
				{
					bool flag = listedProducts.Contains(val);
					if (listed && !flag)
					{
						listedProducts.Add(val);
					}
					else if (!listed && flag)
					{
						listedProducts.Remove(val);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		public static void PurgeFromProductManagerLists()
		{
			foreach (ProductDefinition value in _byTier.Values)
			{
				if ((Object)(object)value == (Object)null)
				{
					continue;
				}
				try
				{
					List<ProductDefinition> discoveredProducts = ProductManager.DiscoveredProducts;
					if (discoveredProducts != null && discoveredProducts.Contains(value))
					{
						discoveredProducts.Remove(value);
					}
				}
				catch
				{
				}
				try
				{
					List<ProductDefinition> listedProducts = ProductManager.ListedProducts;
					if (listedProducts != null && listedProducts.Contains(value))
					{
						listedProducts.Remove(value);
					}
				}
				catch
				{
				}
			}
		}

		public static void RequestProductManagerRefresh()
		{
			_pendingRefresh = true;
		}

		public static void TryApplyPendingRefresh()
		{
			if (_pendingRefresh)
			{
				_pendingRefresh = false;
			}
		}
	}
	internal static class ModProductRegistry
	{
		internal static Dictionary<EscortTier, ItemDefinition> EscortContracts = new Dictionary<EscortTier, ItemDefinition>();

		internal static void RegisterProducts()
		{
		}

		internal static ItemDefinition GetContract(EscortTier tier)
		{
			if (EscortContracts.TryGetValue(tier, out var value))
			{
				return value;
			}
			return null;
		}
	}
}
namespace bigpimpin.Patches
{
	internal static class BlackmailRewardPatches
	{
		[HarmonyPatch]
		internal static class Patch_BusinessOwnerPrice_Float
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(float), IsShopType, IsPriceMethod, _shopTypeSuffixes);
			}

			private static void Postfix(object __instance, ref float __result)
			{
				try
				{
					if (__result <= 0f)
					{
						return;
					}
					float discountFactorForContext = BlackmailManager.GetDiscountFactorForContext(__instance);
					if (discountFactorForContext >= 1f)
					{
						LogDiscountMissReason(__instance);
						return;
					}
					__result *= (IsPawnContext(__instance) ? (2f - discountFactorForContext) : discountFactorForContext);
					if (!_loggedDiscount)
					{
						_loggedDiscount = true;
						BPLog.Debug("Blackmail discount applied to shop float price.");
					}
				}
				catch
				{
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_BusinessOwnerPrice_Int
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(int), IsShopType, IsPriceMethod, _shopTypeSuffixes);
			}

			private static void Postfix(object __instance, ref int __result)
			{
				try
				{
					if (__result <= 0)
					{
						return;
					}
					float discountFactorForContext = BlackmailManager.GetDiscountFactorForContext(__instance);
					if (discountFactorForContext >= 1f)
					{
						LogDiscountMissReason(__instance);
						return;
					}
					float num = (IsPawnContext(__instance) ? (2f - discountFactorForContext) : discountFactorForContext);
					__result = Math.Max(1, (int)Math.Ceiling((float)__result * num));
					if (!_loggedDiscount)
					{
						_loggedDiscount = true;
						BPLog.Debug("Blackmail discount applied to shop int price.");
					}
				}
				catch
				{
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_PoliceSearch_Bool
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(bool), IsPoliceSearchType, IsBlockableMethod, _policeTypeSuffixes);
			}

			private static bool Prefix(object __instance, ref bool __result)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					__result = false;
					if (!_loggedSearchBlock)
					{
						_loggedSearchBlock = true;
						BPLog.Debug("Blackmail blocked a police/search bool check.");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_PoliceSearch_Void
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(void), IsPoliceSearchType, IsBlockableMethod, _policeTypeSuffixes);
			}

			private static bool Prefix(object __instance)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					if (!_loggedSearchBlock)
					{
						_loggedSearchBlock = true;
						BPLog.Debug("Blackmail blocked a police/search action.");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(PoliceOfficer), "BeginBodySearch")]
		internal static class Patch_PoliceOfficer_BeginBodySearch
		{
			private static bool Prefix(PoliceOfficer __instance)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					if (!_loggedSearchBlock)
					{
						_loggedSearchBlock = true;
						BPLog.Debug("Blackmail blocked PoliceOfficer.BeginBodySearch (cop leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(PoliceOfficer), "ConductBodySearch")]
		internal static class Patch_PoliceOfficer_ConductBodySearch
		{
			private static bool Prefix(PoliceOfficer __instance)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					if (!_loggedSearchBlock)
					{
						_loggedSearchBlock = true;
						BPLog.Debug("Blackmail blocked PoliceOfficer.ConductBodySearch (cop leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(PoliceOfficer), "CheckNewInvestigation")]
		internal static class Patch_PoliceOfficer_CheckNewInvestigation
		{
			private static bool Prefix(PoliceOfficer __instance)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_Curfew_Bool
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(bool), IsCurfewType, IsBlockableMethod, _curfewTypeSuffixes);
			}

			private static bool Prefix(ref bool __result)
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					__result = false;
					if (!_loggedCurfewBlock)
					{
						_loggedCurfewBlock = true;
						BPLog.Debug("Blackmail blocked a curfew bool check.");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_Curfew_Void
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(void), IsCurfewType, IsBlockableMethod, _curfewTypeSuffixes);
			}

			private static bool Prefix()
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					if (!_loggedCurfewBlock)
					{
						_loggedCurfewBlock = true;
						BPLog.Debug("Blackmail blocked a curfew action.");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(CurfewManager), "Enable")]
		internal static class Patch_CurfewManager_Enable
		{
			private static bool Prefix()
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					if (!_loggedCurfewBlock)
					{
						_loggedCurfewBlock = true;
						BPLog.Debug("Blackmail blocked CurfewManager.Enable (mayor leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(CheckpointInstance), "Evaluate")]
		internal static class Patch_CheckpointInstance_Evaluate
		{
			private static bool Prefix(CheckpointInstance __instance)
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					try
					{
						if (__instance != null)
						{
							__instance.DisableCheckpoint();
						}
					}
					catch
					{
					}
					if (!_loggedCheckpointBlock)
					{
						_loggedCheckpointBlock = true;
						BPLog.Debug("Blackmail blocked CheckpointInstance.Evaluate (mayor leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(CheckpointInstance), "EnableCheckpoint")]
		internal static class Patch_CheckpointInstance_Enable
		{
			private static bool Prefix(CheckpointInstance __instance)
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					if (!_loggedCheckpointBlock)
					{
						_loggedCheckpointBlock = true;
						BPLog.Debug("Blackmail blocked CheckpointInstance.EnableCheckpoint (mayor leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(CheckpointManager), "SetCheckpointEnabled")]
		internal static class Patch_CheckpointManager_SetEnabled
		{
			private static bool Prefix(ref bool enabled)
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					if (!enabled)
					{
						return true;
					}
					enabled = false;
					if (!_loggedCheckpointBlock)
					{
						_loggedCheckpointBlock = true;
						BPLog.Debug("Blackmail forced SetCheckpointEnabled=false (mayor leverage).");
					}
					return true;
				}
				catch
				{
					return true;
				}
			}
		}

		private static bool _loggedDiscount;

		private static bool _loggedSearchBlock;

		private static bool _loggedCurfewBlock;

		private static bool _loggedCheckpointBlock;

		private static float _lastDiagLogTime;

		private const float DiagLogIntervalSeconds = 5f;

		private static bool _loggedReapply;

		private static readonly string[] _shopTypeSuffixes = new string[3] { "UI.Shop.Cart", "UI.PawnShopInterface", "UI.Phone.Delivery.DeliveryShop" };

		private static readonly string[] _policeTypeSuffixes = new string[3] { "Effects.Seizure", "UI.BodySearchScreen", "UI.Items.FilterConfigPanel+SearchCategory" };

		private static readonly string[] _curfewTypeSuffixes = new string[3] { "Law.CurfewManager", "Law.CurfewInstance", "Law.ViolatingCurfew" };

		private static readonly string[] _gameNamespacePrefixes = new string[2] { "Il2CppScheduleOne.", "ScheduleOne." };

		private static float DiscountMultiplier()
		{
			int num = ModConfig.BlackmailBusinessDiscountPercent;
			if (num < 0)
			{
				num = 0;
			}
			if (num > 100)
			{
				num = 100;
			}
			return 1f - (float)num / 100f;
		}

		private static void LogDiscountMissReason(object ctx)
		{
			try
			{
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				if (!(realtimeSinceStartup - _lastDiagLogTime < 5f))
				{
					_lastDiagLogTime = realtimeSinceStartup;
					BPLog.Debug("Shop-discount skip: " + BlackmailManager.DiagnoseDiscountForContext(ctx));
				}
			}
			catch
			{
			}
		}

		public static void ReapplyActiveLeverage()
		{
			try
			{
				bool value = BlackmailManager.IsUnlocked(BlackmailTargetClass.BusinessOwner);
				bool value2 = BlackmailManager.IsActive(BlackmailTargetClass.Cop);
				bool flag = BlackmailManager.ShouldBlockCurfew();
				BPLog.Debug($"[blackmail] reapply leverage after load: business={value} cop={value2} mayor={flag}");
				if (flag)
				{
					LiftStandingCurfewAndCheckpoints();
				}
			}
			catch
			{
			}
		}

		public static void LiftStandingCurfewAndCheckpoints()
		{
			try
			{
				if (!BlackmailManager.ShouldBlockCurfew() || !NetworkHelper.IsHost)
				{
					return;
				}
				try
				{
					CheckpointManager val = null;
					try
					{
						val = NetworkSingleton<CheckpointManager>.Instance;
					}
					catch
					{
					}
					if ((Object)(object)val != (Object)null)
					{
						val.SetCheckpointEnabled((ECheckpointLocation)0, false, 0);
						val.SetCheckpointEnabled((ECheckpointLocation)1, false, 0);
						val.SetCheckpointEnabled((ECheckpointLocation)2, false, 0);
						val.SetCheckpointEnabled((ECheckpointLocation)3, false, 0);
					}
				}
				catch
				{
				}
				try
				{
					CurfewManager val2 = null;
					try
					{
						val2 = NetworkSingleton<CurfewManager>.Instance;
					}
					catch
					{
					}
					if ((Object)(object)val2 != (Object)null)
					{
						val2.Disable();
					}
				}
				catch
				{
				}
				if (!_loggedReapply)
				{
					_loggedReapply = true;
					BPLog.Debug("[blackmail] mayor leverage: standing curfew disabled + checkpoints cleared.");
				}
			}
			catch
			{
			}
		}

		private static Type ResolveGameType(string suffix)
		{
			try
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly in assemblies)
				{
					string text;
					try
					{
						text = assembly.GetName().Name ?? string.Empty;
					}
					catch
					{
						continue;
					}
					if (!text.Contains("Assembly-CSharp") && !text.Contains("Il2CppScheduleOne"))
					{
						continue;
					}
					for (int j = 0; j < _gameNamespacePrefixes.Length; j++)
					{
						try
						{
							Type type = assembly.GetType(_gameNamespacePrefixes[j] + suffix, throwOnError: false);
							if (type != null)
							{
								return type;
							}
						}
						catch
						{
						}
					}
				}
			}
			catch
			{
			}
			return null;
		}

		private static IEnumerable<MethodBase> FindMethods(Type returnType, Func<Type, bool> typeFilter, Func<MethodInfo, bool> methodFilter, string[] typeSuffixes)
		{
			List<MethodBase> list = new List<MethodBase>();
			try
			{
				for (int i = 0; i < typeSuffixes.Length; i++)
				{
					Type type = ResolveGameType(typeSuffixes[i]);
					if (type == null || !typeFilter(type))
					{
						continue;
					}
					MethodInfo[] methods;
					try
					{
						methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					}
					catch
					{
						continue;
					}
					foreach (MethodInfo methodInfo in methods)
					{
						if (!(methodInfo == null) && !methodInfo.IsAbstract && !methodInfo.ContainsGenericParameters && !methodInfo.IsSpecialName && !(methodInfo.ReturnType != returnType) && methodFilter(methodInfo))
						{
							list.Add(methodInfo);
						}
					}
				}
			}
			catch
			{
			}
			return list;
		}

		private static bool IsShopType(Type type)
		{
			string value = (type.FullName ?? type.Name).ToLowerInvariant();
			return ContainsAny(value, "shop", "store", "vendor", "merchant", "business");
		}

		private static bool IsPoliceSearchType(Type type)
		{
			string value = (type.FullName ?? type.Name).ToLowerInvariant();
			return ContainsAny(value, "bodysearch", "search", "seizure", "contraband");
		}

		private static bool IsCurfewType(Type type)
		{
			string text = (type.FullName ?? type.Name).ToLowerInvariant();
			return text.Contains("curfew");
		}

		private static bool IsPriceMethod(MethodInfo method)
		{
			string value = method.Name.ToLowerInvariant();
			return ContainsAny(value, "price", "cost", "value", "amount", "purchase") && !ContainsAny(value, "set_", "add_", "remove_");
		}

		private static bool IsBlockableMethod(MethodInfo method)
		{
			string value = method.Name.ToLowerInvariant();
			if (ContainsAny(value, "save", "load", "serialize", "deserialize", "shouldsave"))
			{
				return false;
			}
			return ContainsAny(value, "search", "bust", "curfew", "contraband", "seize", "arrest", "fine", "check", "can", "should", "apply", "begin", "start", "enforce") && !ContainsAny(value, "set_", "add_", "remove_", "update");
		}

		private static bool IsPawnContext(object instance)
		{
			try
			{
				return instance != null && (instance.GetType().Name ?? string.Empty).IndexOf("PawnShop", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			catch
			{
				return false;
			}
		}

		private static NPC ResolveNpc(object instance)
		{
			try
			{
				if (instance == null)
				{
					return null;
				}
				NPC val = (NPC)((instance is NPC) ? instance : null);
				if (val != null)
				{
					return val;
				}
				Type type = instance.GetType();
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (!(fieldInfo == null) && typeof(NPC).IsAssignableFrom(fieldInfo.FieldType))
					{
						object? value = fieldInfo.GetValue(instance);
						NPC val2 = (NPC)((value is NPC) ? value : null);
						if ((Object)(object)val2 != (Object)null)
						{
							return val2;
						}
					}
				}
				PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (PropertyInfo propertyInfo in properties)
				{
					if (!(propertyInfo == null) && propertyInfo.CanRead && typeof(NPC).IsAssignableFrom(propertyInfo.PropertyType))
					{
						object? value2 = propertyInfo.GetValue(instance, null);
						NPC val3 = (NPC)((value2 is NPC) ? value2 : null);
						if ((Object)(object)val3 != (Object)null)
						{
							return val3;
						}
					}
				}
			}
			catch
			{
			}
			return null;
		}

		private static bool ContainsAny(string value, params string[] needles)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				return false;
			}
			for (int i = 0; i < needles.Length; i++)
			{
				if (!string.IsNullOrWhiteSpace(needles[i]) && value.Contains(needles[i]))
				{
					return true;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(ContactsApp), "Update")]
	internal static class Patch_ContactsApp_Update_Safety
	{
		private static bool _logged;

		[HarmonyFinalizer]
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception == null)
			{
				return null;
			}
			if (!_logged)
			{
				_logged = true;
				MelonLogger.Warning("[bigpimpin] CHANGE-313: ContactsApp.Update threw (suppressed once-logged, S1API populates RegionDict via deferred Start) - " + __exception.GetType().Name + ": " + __exception.Message);
			}
			return null;
		}
	}
	[HarmonyPatch]
	internal static class ContactsVanillaOnClientPatch
	{
		private static MethodBase TargetMethod()
		{
			try
			{
				Type type = AccessTools.TypeByName("S1API.Internal.Patches.ContactsAppPatches");
				return (type == null) ? null : AccessTools.Method(type, "HasCustomNpcTypes", (Type[])null, (Type[])null);
			}
			catch
			{
				return null;
			}
		}

		private static bool Prepare()
		{
			return TargetMethod() != null;
		}

		private static void Postfix(ref bool __result)
		{
			try
			{
				if (!NetworkHelper.IsHost)
				{
					__result = false;
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(QuestsLoader), "Load")]
	internal static class Patch_QuestsLoader_Load_ContractMigration
	{
		private const string LegacyProductPrefix = "bp_escort_";

		[HarmonyPrefix]
		private static void Prefix(string mainPath)
		{
			try
			{
				SanitizeQuestsJson(mainPath);
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] CHANGE-334: contract receipts migration failed (fail-open): " + ex.Message);
			}
		}

		private static void SanitizeQuestsJson(string mainPath)
		{
			if (string.IsNullOrWhiteSpace(mainPath))
			{
				return;
			}
			string text = Path.Combine(mainPath, "Quests.json");
			if (!File.Exists(text))
			{
				return;
			}
			string text2 = File.ReadAllText(text);
			if (string.IsNullOrWhiteSpace(text2) || text2.IndexOf("bp_escort_", StringComparison.Ordinal) < 0)
			{
				return;
			}
			JObject val;
			try
			{
				val = JObject.Parse(text2);
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] CHANGE-334: Quests.json parse failed: " + ex.Message);
				return;
			}
			JToken obj = val["Contracts"];
			JArray val2 = (JArray)(object)((obj is JArray) ? obj : null);
			if (val2 == null || ((JContainer)val2).Count == 0)
			{
				return;
			}
			int num = 0;
			for (int num2 = ((JContainer)val2).Count - 1; num2 >= 0; num2--)
			{
				if (ContractReferencesEscortProduct(val2[num2]))
				{
					val2.RemoveAt(num2);
					num++;
				}
			}
			if (num == 0)
			{
				return;
			}
			try
			{
				string text3 = text + ".bp_tmp";
				File.WriteAllText(text3, ((JToken)val).ToString((Formatting)1));
				if (File.Exists(text))
				{
					File.Replace(text3, text, null);
				}
				else
				{
					File.Move(text3, text);
				}
				MelonLogger.Msg($"[bigpimpin] CHANGE-334: stale escort contract receipts removed from Quests.json — {num} entries.");
			}
			catch (Exception ex2)
			{
				MelonLogger.Warning("[bigpimpin] CHANGE-334: failed to write sanitized Quests.json: " + ex2.Message);
			}
		}

		private static bool ContractReferencesEscortProduct(JToken contract)
		{
			try
			{
				JToken val = ((contract != null) ? contract[(object)"ProductList"] : null);
				JToken obj = ((val != null) ? val[(object)"entries"] : null);
				JArray val2 = (JArray)(object)((obj is JArray) ? obj : null);
				if (val2 == null || ((JContainer)val2).Count == 0)
				{
					return false;
				}
				for (int i = 0; i < ((JContainer)val2).Count; i++)
				{
					JToken obj2 = val2[i];
					string text = (string)((obj2 != null) ? obj2[(object)"ProductID"] : null);
					if (!string.IsNullOrEmpty(text) && text.StartsWith("bp_escort_", StringComparison.OrdinalIgnoreCase))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Customer), "UpdateDealAttendance")]
	internal static class Patch_Customer_UpdateDealAttendance_Safety
	{
		private static bool _logged;

		[HarmonyFinalizer]
		private static Exception Finalizer(Customer __instance, Exception __exception)
		{
			if (__exception == null)
			{
				return null;
			}
			if (!_logged)
			{
				_logged = true;
				string text = null;
				try
				{
					object obj;
					if (__instance == null)
					{
						obj = null;
					}
					else
					{
						NPC nPC = __instance.NPC;
						obj = ((nPC != null) ? nPC.FullName : null);
					}
					if (obj == null)
					{
						obj = "<unknown>";
					}
					text = (string)obj;
				}
				catch
				{
					text = "<unresolvable>";
				}
				MelonLogger.Warning("[bigpimpin] CHANGE-322: Customer.UpdateDealAttendance threw (suppressed once-logged) - customer=" + text + " " + __exception.GetType().Name + ": " + __exception.Message);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(QuestsLoader), "Load")]
	internal static class Patch_QuestsLoader_Load_Safety
	{
		private static bool _logged;

		[HarmonyFinalizer]
		private static Exception Finalizer(string mainPath, Exception __exception)
		{
			if (__exception == null)
			{
				return null;
			}
			if (!_logged)
			{
				_logged = true;
				MelonLogger.Warning("[bigpimpin] CHANGE-323: QuestsLoader.Load threw (suppressed once-logged) - path='" + (mainPath ?? "<null>") + "' " + __exception.GetType().Name + ": " + __exception.Message);
			}
			return null;
		}
	}
	internal static class EscortContractPatches
	{
		private sealed class DynamicDeliveryTarget
		{
			public string Guid;

			public DeliveryLocation Location;
		}

		private sealed class PreemptiveWalkState
		{
			public EscortSlotLease Lease;

			public Vector3 MobileTarget;

			public EscortInstance Escort;
		}

		[HarmonyPatch(typeof(Customer), "OfferContractToDealer")]
		internal static class Patch_Customer_OfferContractToDealer
		{
			[HarmonyPrefix]
			private static bool Prefix(ContractInfo info, Dealer dealer)
			{
				if (!ContainsEscortProduct(info))
				{
					return true;
				}
				if (IsBigPimpinEscortDealer(dealer, info))
				{
					PrepareEscortContract(info);
					return true;
				}
				if (!_loggedDealerBlock)
				{
					_loggedDealerBlock = true;
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(Customer), "OfferContract")]
		internal static class Patch_Customer_OfferContract
		{
			[HarmonyPrefix]
			private static bool Prefix(Customer __instance, ContractInfo info)
			{
				if (!IsEscortTierUnlocked(info))
				{
					return false;
				}
				if (!IsEscortTierStocked(__instance, info))
				{
					return false;
				}
				PrepareEscortContract(info, __instance);
				return true;
			}
		}

		[HarmonyPatch(typeof(Customer), "NotifyPlayerOfContract")]
		internal static class Patch_Customer_NotifyPlayerOfContract
		{
			[HarmonyPrefix]
			private static bool Prefix(Customer __instance, ContractInfo contract)
			{
				//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_0058: Unknown result type (might be due to invalid IL or missing references)
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_0066: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Expected O, but got Unknown
				if (!IsEscortTierUnlocked(contract))
				{
					return false;
				}
				if (!IsEscortTierStocked(__instance, contract))
				{
					return false;
				}
				PrepareEscortContract(contract, __instance);
				if (ContainsEscortProduct(contract))
				{
					EDealWindow val = ResolveCurrentDealWindow(contract);
					try
					{
						contract.DeliveryWindow = new QuestWindowConfig
						{
							IsEnabled = true,
							WindowStartTime = WindowStartHHMM(val),
							WindowEndTime = WindowEndHHMM(val)
						};
					}
					catch (Exception ex)
					{
						BPLog.TraceWarn("contract", "DeliveryWindow set failed: " + ex.Message);
					}
					Contract val2 = null;
					try
					{
						val2 = __instance.ContractAccepted(val, true, (Dealer)null);
					}
					catch (Exception ex2)
					{
						if (!_loggedAutoAcceptFailed)
						{
							_loggedAutoAcceptFailed = true;
							DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(51, 3);
							defaultInterpolatedStringHandler.AppendLiteral("ContractAccepted(");
							defaultInterpolatedStringHandler.AppendFormatted<EDealWindow>(val);
							defaultInterpolatedStringHandler.AppendLiteral(") failed ");
							defaultInterpolatedStringHandler.AppendLiteral("for escort contract (");
							object value;
							if (__instance == null)
							{
								value = null;
							}
							else
							{
								NPC nPC = __instance.NPC;
								value = ((nPC != null) ? nPC.FullName : null);
							}
							defaultInterpolatedStringHandler.AppendFormatted((string?)value);
							defaultInterpolatedStringHandler.AppendLiteral("): ");
							defaultInterpolatedStringHandler.AppendFormatted(ex2.Message);
							defaultInterpolatedStringHandler.AppendLiteral(" ");
							MelonLogger.Warning(defaultInterpolatedStringHandler.ToStringAndClear() + "(further warnings suppressed)");
						}
					}
					try
					{
						__instance.SetIsAwaitingDelivery(true);
					}
					catch
					{
					}
					try
					{
						if ((Object)(object)__instance.CurrentContract == (Object)null && (Object)(object)val2 != (Object)null)
						{
							__instance.CurrentContract = val2;
						}
					}
					catch
					{
					}
					try
					{
						Contract val3 = val2 ?? __instance.CurrentContract;
						if ((Object)(object)val3 != (Object)null && ContainsEscortProduct(val3.ProductList))
						{
							StartEscortPreemptiveWalk(val3, __instance);
						}
					}
					catch (Exception ex3)
					{
						if (!_loggedPreemptiveWalkFailed)
						{
							_loggedPreemptiveWalkFailed = true;
							DefaultInterpolatedStringHandler defaultInterpolatedStringHandler2 = new DefaultInterpolatedStringHandler(51, 2);
							defaultInterpolatedStringHandler2.AppendLiteral("StartEscortPreemptiveWalk failed ");
							defaultInterpolatedStringHandler2.AppendLiteral("for customer '");
							object obj3;
							if (__instance == null)
							{
								obj3 = null;
							}
							else
							{
								NPC nPC2 = __instance.NPC;
								obj3 = ((nPC2 != null) ? nPC2.FullName : null);
							}
							if (obj3 == null)
							{
								obj3 = "?";
							}
							defaultInterpolatedStringHandler2.AppendFormatted((string?)obj3);
							defaultInterpolatedStringHandler2.AppendLiteral("': ");
							defaultInterpolatedStringHandler2.AppendFormatted(ex3.Message);
							defaultInterpolatedStringHandler2.AppendLiteral(" ");
							MelonLogger.Warning(defaultInterpolatedStringHandler2.ToStringAndClear() + "(further warnings suppressed)");
						}
					}
					try
					{
						if (TryGetContractTier(contract, out var tier))
						{
							int contractHandle = 0;
							try
							{
								contractHandle = ((Object)contract).GetHashCode();
							}
							catch
							{
							}
							string customerName = null;
							try
							{
								object obj5;
								if (__instance == null)
								{
									obj5 = null;
								}
								else
								{
									NPC nPC3 = __instance.NPC;
									obj5 = ((nPC3 != null) ? nPC3.FullName : null);
								}
								customerName = (string)obj5;
							}
							catch
							{
							}
							EscortWalkUpReporter.NotifyContractAccepted(tier, contractHandle, customerName);
						}
					}
					catch
					{
					}
					return false;
				}
				return true;
			}

			[HarmonyFinalizer]
			private static Exception Finalizer(ContractInfo contract, Exception __exception)
			{
				if (__exception == null)
				{
					return null;
				}
				if (contract != null && ContainsEscortProduct(contract))
				{
					if (!_loggedNotifySuppressed)
					{
						_loggedNotifySuppressed = true;
					}
					return null;
				}
				return __exception;
			}
		}

		[HarmonyPatch(typeof(Customer), "PlayContractAcceptedReaction")]
		internal static class Patch_Customer_PlayContractAcceptedReaction
		{
			[HarmonyPrefix]
			private static void Prefix(Customer __instance)
			{
				try
				{
					ContractInfo val = ((__instance != null) ? __instance.OfferedContractInfo : null);
					if (val != null && ContainsEscortProduct(val))
					{
						PrepareEscortContract(val, __instance);
					}
				}
				catch
				{
				}
			}

			[HarmonyFinalizer]
			private static Exception Finalizer(Customer __instance, Exception __exception)
			{
				if (__exception == null)
				{
					return null;
				}
				try
				{
					Contract val = ((__instance != null) ? __instance.CurrentContract : null);
					if ((Object)(object)val != (Object)null && ContainsEscortProduct(val.ProductList))
					{
						if (!_loggedReactionSwallow)
						{
							_loggedReactionSwallow = true;
						}
						return null;
					}
				}
				catch
				{
				}
				return __exception;
			}
		}

		[HarmonyPatch(typeof(Customer), "CounterOfferClicked")]
		internal static class Patch_Customer_CounterOfferClicked
		{
			[HarmonyPrefix]
			private static void Prefix(Customer __instance)
			{
				try
				{
					ContractInfo val = ((__instance != null) ? __instance.OfferedContractInfo : null);
					if (val != null && ContainsEscortProduct(val))
					{
						PrepareEscortContract(val, __instance);
						if (!_loggedCounterOfferEnabled)
						{
							_loggedCounterOfferEnabled = true;
						}
					}
				}
				catch
				{
				}
			}
		}

		[HarmonyPatch(typeof(MSGConversation), "RenderMessage")]
		internal static class Patch_MSGConversation_RenderMessage
		{
			[HarmonyFinalizer]
			private static Exception Finalizer(Exception __exception)
			{
				if (__exception == null)
				{
					return null;
				}
				if (!_loggedRenderMessageSwallow)
				{
					_loggedRenderMessageSwallow = true;
				}
				return null;
			}
		}

		[HarmonyPatch(typeof(HandoverScreen), "Open")]
		internal static class Patch_HandoverScreen_Open
		{
			[HarmonyPrefix]
			private static bool Prefix(Contract contract, Customer customer, EMode mode, Action<EHandoverOutcome, List<ItemInstance>, float> callback)
			{
				try
				{
					if ((Object)(object)contract == (Object)null)
					{
						return true;
					}
					if (!ContainsEscortProduct(contract.ProductList))
					{
						return true;
					}
					float num = 0f;
					try
					{
						num = contract.Payment;
					}
					catch
					{
					}
					if ((Delegate)(object)callback != (Delegate)null)
					{
						try
						{
							List<ItemInstance> val = new List<ItemInstance>();
							callback.Invoke((EHandoverOutcome)1, val, num);
						}
						catch (Exception ex)
						{
							MelonLogger.Warning("Patch_HandoverScreen_Open: callback invoke failed: " + ex.Message);
						}
					}
					RunEscortHandover(contract, customer);
					return false;
				}
				catch (Exception)
				{
					return true;
				}
			}
		}

		private sealed class SuppressedCustomer
		{
			public NPC Npc;

			public float Deadline;
		}

		[HarmonyPatch(typeof(NPCSignal_WalkToLocation), "WalkCallback")]
		internal static class Patch_NPCSignal_WalkToLocation_WalkCallback
		{
			private static bool _loggedOnce;

			[HarmonyFinalizer]
			private static Exception Finalizer(Exception __exception)
			{
				if (__exception == null)
				{
					return null;
				}
				if (!_loggedOnce)
				{
					_loggedOnce = true;
				}
				return null;
			}
		}

		[HarmonyPatch(typeof(ProductList), "GetCommaSeperatedString")]
		internal static class Patch_ProductList_HideEscortQuantity
		{
			[HarmonyPostfix]
			private static void Postfix(ProductList __instance, ref string __result)
			{
				try
				{
					List<Entry> val = ((__instance != null) ? __instance.entries : null);
					if (val == null || string.IsNullOrEmpty(__result))
					{
						return;
					}
					for (int i = 0; i < val.Count; i++)
					{
						Entry val2 = val[i];
						if (val2 == null || !EscortProductRegistry.TryResolveTier(val2.ProductID, out var _))
						{
							continue;
						}
						string text = null;
						try
						{
							ProductDefinition val3 = EscortProductRegistry.Get(EscortProductRegistry.ResolveTier(val2.ProductID));
							if ((Object)(object)val3 != (Object)null)
							{
								text = ((BaseItemDefinition)val3).Name;
							}
						}
						catch
						{
						}
						if (!string.IsNullOrEmpty(text))
						{
							string text2 = val2.Quantity + "x " + text;
							if (__result.Contains(text2))
							{
								__result = __result.Replace(text2, text);
							}
						}
					}
				}
				catch
				{
				}
			}
		}

		private static bool _loggedDealerBlock;

		private static bool _loggedLocationPatch;

		private static bool _loggedNotifySuppressed;

		private static bool _loggedPreemptiveWalkFailed;

		private static readonly Dictionary<string, DynamicDeliveryTarget> _dynamicDeliveryTargets = new Dictionary<string, DynamicDeliveryTarget>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<int, PreemptiveWalkState> _preemptiveWalkLeases = new Dictionary<int, PreemptiveWalkState>();

		private static readonly Dictionary<string, EscortSlotLease> _escortInPostHandoverWalk = new Dictionary<string, EscortSlotLease>(StringComparer.Ordinal);

		private static readonly HashSet<EscortSlotLease> _leasesHandedToFollowup = new HashSet<EscortSlotLease>();

		private static bool _loggedReactionSwallow;

		private static bool _loggedCounterOfferEnabled;

		private static bool _loggedRenderMessageSwallow;

		private static bool _loggedAutoAcceptFailed;

		private static int _pairCleanupId;

		private const float BrothelCentricEscortRadius = 1.2f;

		private const float CustomerHomeEscortRadius = 1.6f;

		private static readonly HashSet<int> _handledContracts = new HashSet<int>();

		private const float SUPPRESSED_CUSTOMER_TIMEOUT = 360f;

		private static float _watchdogTimer;

		private static readonly Dictionary<int, SuppressedCustomer> _suppressedCustomers = new Dictionary<int, SuppressedCustomer>();

		internal static void PrepareEscortContract(ContractInfo info, Customer customer = null)
		{
			ForcePimpDoorLocation(info, customer);
			EnsureEscortContractShape(info);
			try
			{
				EscortNPCRegistry.EnsureAll();
			}
			catch
			{
			}
		}

		private static bool ContainsEscortProduct(ContractInfo info)
		{
			try
			{
				object obj;
				if (info == null)
				{
					obj = null;
				}
				else
				{
					ProductList products = info.Products;
					obj = ((products != null) ? products.entries : null);
				}
				List<Entry> val = (List<Entry>)obj;
				if (val == null)
				{
					return false;
				}
				for (int i = 0; i < val.Count; i++)
				{
					Entry val2 = val[i];
					if (val2 != null && EscortProductRegistry.TryResolveTier(val2.ProductID, out var _))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool TryGetEscortProductId(ContractInfo info, out string productId)
		{
			productId = null;
			try
			{
				object obj;
				if (info == null)
				{
					obj = null;
				}
				else
				{
					ProductList products = info.Products;
					obj = ((products != null) ? products.entries : null);
				}
				List<Entry> val = (List<Entry>)obj;
				if (val == null)
				{
					return false;
				}
				for (int i = 0; i < val.Count; i++)
				{
					Entry val2 = val[i];
					if (val2 != null && EscortProductRegistry.TryResolveTier(val2.ProductID, out var _))
					{
						productId = val2.ProductID;
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool IsBigPimpinEscortDealer(Dealer dealer, ContractInfo info)
		{
			if ((Object)(object)dealer == (Object)null || !TryGetEscortProductId(info, out var productId))
			{
				return false;
			}
			try
			{
				return (((Component)dealer).GetComponent<EscortSlotBase>() ?? ((Component)dealer).GetComponentInChildren<EscortSlotBase>(true) ?? ((Component)dealer).GetComponentInParent<EscortSlotBase>())?.CanDealDateProduct(productId) ?? false;
			}
			catch
			{
				return false;
			}
		}

		private static bool ContainsEscortProduct(ProductList list)
		{
			try
			{
				List<Entry> val = ((list != null) ? list.entries : null);
				if (val == null)
				{
					return false;
				}
				for (int i = 0; i < val.Count; i++)
				{
					Entry val2 = val[i];
					if (val2 != null && EscortProductRegistry.TryResolveTier(val2.ProductID, out var _))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		internal static bool ContainsEscortProductPublic(ProductList list)
		{
			return ContainsEscortProduct(list);
		}

		private static bool IsEscortTierUnlocked(ContractInfo info)
		{
			try
			{
				if (info == null || !ContainsEscortProduct(info))
				{
					return true;
				}
				if (!TryGetContractTier(info, out var tier))
				{
					return true;
				}
				return EscortDealerUnlocks.IsUnlocked(tier);
			}
			catch
			{
				return true;
			}
		}

		private static void ForcePimpDoorLocation(ContractInfo info, Customer customer)
		{
			if (info == null || !ContainsEscortProduct(info))
			{
				return;
			}
			string text = ResolveLocationIdForCustomer(customer);
			string guid;
			DeliveryLocation val;
			if (TryGetContractTier(info, out var tier) && UsesCustomerHomeRouting(tier) && TryGetOrCreateCustomerDeliveryTarget(customer, tier, out var target))
			{
				guid = target.Guid;
				val = target.Location;
				text = text + ":" + tier;
			}
			else
			{
				BrothelDeliveryLocations.TryEnsureAll();
				guid = BrothelDeliveryLocations.GetGuid(text);
				val = BrothelDeliveryLocations.GetInstance(text);
			}
			if (string.IsNullOrWhiteSpace(guid))
			{
				return;
			}
			if (!string.Equals(info.DeliveryLocationGUID, guid, StringComparison.OrdinalIgnoreCase))
			{
				info.DeliveryLocationGUID = guid;
			}
			try
			{
				if ((Object)(object)val != (Object)null && (Object)(object)info.DeliveryLocation == (Object)null)
				{
					info.DeliveryLocation = val;
				}
			}
			catch (Exception)
			{
			}
			try
			{
			}
			catch
			{
			}
			if (!_loggedLocationPatch)
			{
				_loggedLocationPatch = true;
			}
		}

		internal static string ResolveLocationIdForCustomer(Customer customer)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NPC val = ((customer != null) ? customer.NPC : null);
				if ((Object)(object)val == (Object)null)
				{
					return "MidnightSuites";
				}
				return EscortLocations.GetLocationIdForRegion(val.Region);
			}
			catch
			{
				return "MidnightSuites";
			}
		}

		private static bool TryGetContractTier(ContractInfo info, out EscortTier tier)
		{
			tier = EscortTier.Street;
			try
			{
				object obj;
				if (info == null)
				{
					obj = null;
				}
				else
				{
					ProductList products = info.Products;
					obj = ((products != null) ? products.entries : null);
				}
				List<Entry> val = (List<Entry>)obj;
				if (val == null)
				{
					return false;
				}
				for (int i = 0; i < val.Count; i++)
				{
					Entry val2 = val[i];
					if (val2 != null && EscortProductRegistry.TryResolveTier(val2.ProductID, out tier))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool IsEscortTierStocked(Customer customer, ContractInfo info)
		{
			try
			{
				if (info == null || !ContainsEscortProduct(info))
				{
					return true;
				}
				if (!TryGetContractTier(info, out var tier))
				{
					return true;
				}
				if (EscortSleepSchedule.IsSleeping(tier))
				{
					return false;
				}
				string locationId = ResolveLocationIdForCustomer(customer);
				if (!EscortStockManager.IsAvailable(locationId, tier))
				{
					return false;
				}
				EscortInstance escort = ShowroomEscorts.Get(locationId, tier);
				if (!EscortCooldownManager.CanSellNow(escort))
				{
					return false;
				}
				return true;
			}
			catch
			{
				return true;
			}
		}

		private static void EnsureEscortContractShape(ContractInfo info)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			if (info == null || !ContainsEscortProduct(info))
			{
				return;
			}
			try
			{
				if (info.Products == null)
				{
					info.Products = new ProductList();
				}
				if (info.DeliveryWindow == null)
				{
					info.DeliveryWindow = new QuestWindowConfig
					{
						IsEnabled = false,
						WindowStartTime = 0,
						WindowEndTime = 0
					};
				}
				if (info.ExpiresAfter <= 0)
				{
					info.ExpiresAfter = 600;
				}
			}
			catch (Exception)
			{
			}
		}

		internal static void RunEscortHandover(Contract contract, Customer customer)
		{
			RunEscortHandoverCore(contract, customer, suppressCashPayout: false);
		}

		internal static void RunEscortHandoverNoCash(Contract contract, Customer customer)
		{
			RunEscortHandoverCore(contract, customer, suppressCashPayout: true);
		}

		internal static bool TryGetContractTierExternal(Contract contract, out EscortTier tier)
		{
			return TryGetContractTier(contract, out tier);
		}

		internal static bool TryResolveContractDeliveryPosition(Contract contract, Customer customer, out Vector3 position)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			position = Vector3.zero;
			try
			{
				if ((Object)(object)contract == (Object)null || !ContainsEscortProduct(contract.ProductList))
				{
					return false;
				}
				if (!TryGetContractTier(contract, out var tier))
				{
					return false;
				}
				if (UsesCustomerHomeRouting(tier))
				{
					NPC val = ((customer != null) ? customer.NPC : null);
					if ((Object)(object)val != (Object)null)
					{
						string text = (string.IsNullOrWhiteSpace(val.ID) ? ((Object)val).GetHashCode().ToString() : val.ID);
						string key = text + ":" + tier;
						if (_dynamicDeliveryTargets.TryGetValue(key, out var value) && (Object)(object)value?.Location != (Object)null && (Object)(object)value.Location.CustomerStandPoint != (Object)null)
						{
							position = value.Location.CustomerStandPoint.position;
							return position != Vector3.zero;
						}
						if (TryGetOrCreateCustomerDeliveryTarget(customer, tier, out var target) && (Object)(object)target?.Location != (Object)null && (Object)(object)target.Location.CustomerStandPoint != (Object)null)
						{
							position = target.Location.CustomerStandPoint.position;
							return position != Vector3.zero;
						}
					}
				}
				string locationId = ResolveLocationIdForCustomer(customer);
				position = ResolveEscortSaleTarget(customer, tier, locationId);
				return position != Vector3.zero;
			}
			catch
			{
				position = Vector3.zero;
				return false;
			}
		}

		private static void RunEscortHandoverCore(Contract contract, Customer customer, bool suppressCashPayout)
		{
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0303: Unknown result type (might be due to invalid IL or missing references)
			//IL_0305: Unknown result type (might be due to invalid IL or missing references)
			//IL_0312: Unknown result type (might be due to invalid IL or missing references)
			//IL_033e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_036f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_021d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0282: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0321: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_0271: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)contract == (Object)null)
			{
				return;
			}
			int num;
			try
			{
				num = ((Object)contract).GetHashCode();
			}
			catch
			{
				num = 0;
			}
			if (num != 0 && !_handledContracts.Add(num))
			{
				return;
			}
			float num2 = 0f;
			try
			{
				num2 = contract.Payment;
			}
			catch
			{
				num2 = 0f;
			}
			try
			{
				string value = null;
				try
				{
					object obj3;
					if (customer == null)
					{
						obj3 = null;
					}
					else
					{
						NPC nPC = customer.NPC;
						obj3 = ((nPC != null) ? nPC.FullName : null);
					}
					value = (string)obj3;
				}
				catch
				{
				}
				BPLog.Trace("handover", $"RunEscortHandoverCore enter customer='{value}' payment={num2:0} suppressCash={suppressCashPayout}");
			}
			catch
			{
			}
			if (!suppressCashPayout && num2 > 0f && ModConfig.GetActivePayout() != ModConfig.PayoutMethod.Immediate && TryGetContractTier(contract, out var tier))
			{
				DailyPayoutManager.DispatchPayout((int)Math.Round(num2), "handover", tier);
				suppressCashPayout = true;
			}
			EscortInstance escortInstance = null;
			EscortSlotLease escortSlotLease = null;
			string text = ResolveLocationIdForCustomer(customer);
			TryGetContractTier(contract, out var tier2);
			bool flag = UsesCustomerHomeRouting(tier2);
			Vector3 val = Vector3.zero;
			bool flag2 = false;
			if (TryConsumePreemptiveWalk(contract, out var lease, out var mobileTarget, out var escort))
			{
				escortSlotLease = lease;
				val = mobileTarget;
				escortInstance = escort;
				flag2 = true;
			}
			try
			{
				object obj6;
				if (customer == null)
				{
					obj6 = null;
				}
				else
				{
					NPC nPC2 = customer.NPC;
					obj6 = ((nPC2 != null) ? nPC2.ID : null);
				}
				string customerNpcId = (string)obj6;
				if (escortInstance == null)
				{
					escortInstance = EscortContractService.GetEscortForCustomer(customerNpcId);
					if (escortInstance == null)
					{
						escortInstance = PickEscortForContract(contract, customer);
					}
				}
				if (escortInstance != null)
				{
					EscortContractService.RegisterEscortForCustomer(customerNpcId, escortInstance);
				}
				if (escortInstance != null && !flag2)
				{
					try
					{
						Vector3 val2 = ResolveEscortSaleTarget(customer, tier2, text);
						Vector3 facingTarget = val2;
						LocationDisplayDefinition def;
						if (TryGetCustomerPosition(customer, out var position))
						{
							facingTarget = position;
						}
						else if (EscortLocations.TryGetDefinition(text, out def))
						{
							facingTarget = def.DoorPosition;
						}
						if (flag)
						{
							val = val2;
							escortSlotLease = EscortLocationDisplayController.DetachLease(escortInstance);
							if (escortSlotLease == null || escortSlotLease.Released)
							{
								EscortLocationDisplayController.ReleaseEscort(escortInstance);
								Vector3 anchorPos = ResolveMobileEscortStartPosition(text, tier2);
								escortSlotLease = EscortNPCRegistry.ShowNear(escortInstance, anchorPos, val2, text);
							}
							StartMobileEscortWalk(escortSlotLease, val2);
						}
						else
						{
							val = val2;
							escortSlotLease = EscortLocationDisplayController.DetachLease(escortInstance);
							if (escortSlotLease == null || escortSlotLease.Released)
							{
								EscortLocationDisplayController.ReleaseEscort(escortInstance);
								Vector3 val3 = Vector3.zero;
								try
								{
									val3 = BrothelDoorHelper.GetApproachPoint();
								}
								catch
								{
								}
								if (val3 == Vector3.zero || val3 == val2)
								{
									escortSlotLease = EscortNPCRegistry.ShowNear(escortInstance, val2, facingTarget, text);
								}
								else
								{
									try
									{
										BrothelDoorHelper.TryOpenForNPC((EDoorSide)0);
									}
									catch
									{
									}
									escortSlotLease = EscortNPCRegistry.ShowNear(escortInstance, val3, val2, text);
									StartMobileEscortWalk(escortSlotLease, val2);
								}
							}
							else
							{
								StartMobileEscortWalk(escortSlotLease, val2);
							}
						}
					}
					catch (Exception)
					{
					}
				}
			}
			catch (Exception)
			{
			}
			if (val != Vector3.zero && escortSlotLease != null && !escortSlotLease.Released)
			{
				ScheduleMobileHandoverCompletion(customer, contract, suppressCashPayout, escortSlotLease, escortInstance, tier2, text, num2, val);
			}
			else
			{
				FinishEscortHandoverAfterVisuals(customer, contract, suppressCashPayout, escortSlotLease, escortInstance, tier2, text, num2);
			}
		}

		private static void FinishEscortHandoverAfterVisuals(Customer customer, Contract contract, bool suppressCashPayout, EscortSlotLease lease, EscortInstance escort, EscortTier contractTier, string handoverLocIdOuter, float payment)
		{
			try
			{
				PlayCustomerHandoverReaction(customer, lease);
			}
			catch
			{
			}
			try
			{
				EscortInstance escortInstance = escort;
				if (escortInstance == null)
				{
					EscortTier tier = EscortTier.Street;
					try
					{
						object obj2;
						if (contract == null)
						{
							obj2 = null;
						}
						else
						{
							ProductList productList = contract.ProductList;
							obj2 = ((productList != null) ? productList.entries : null);
						}
						List<Entry> val = (List<Entry>)obj2;
						if (val != null)
						{
							for (int i = 0; i < val.Count; i++)
							{
								Entry val2 = val[i];
								if (val2 != null && EscortProductRegistry.TryResolveTier(val2.ProductID, out var tier2))
								{
									tier = tier2;
									break;
								}
							}
						}
					}
					catch
					{
					}
					escortInstance = ShowroomEscorts.Get(handoverLocIdOuter, tier);
				}
				EscortCooldownManager.MarkSale(escortInstance);
			}
			catch
			{
			}
			try
			{
				int pimpPointMultiplier = EscortStockManager.GetPimpPointMultiplier(handoverLocIdOuter, contractTier);
				if (!EscortStockManager.HasLeftPermanently(handoverLocIdOuter, contractTier))
				{
					PimpProgressionManager.AwardDatePoints(pimpPointMultiplier, contractTier);
					EscortStockManager.NotifyDateCompletedResetStreak(handoverLocIdOuter, contractTier);
				}
			}
			catch
			{
			}
			try
			{
				BlackmailManager.OnEscortDealerDateCompleted(customer, contractTier, handoverLocIdOuter, escort);
			}
			catch
			{
			}
			try
			{
				if (payment > 0f && !EscortStockManager.HasLeftPermanently(handoverLocIdOuter, contractTier))
				{
					PostDateStatusReporter.Report(contractTier, (int)Math.Round(payment), handoverLocIdOuter);
				}
			}
			catch
			{
			}
			try
			{
				object obj8;
				if (customer == null)
				{
					obj8 = null;
				}
				else
				{
					NPC nPC = customer.NPC;
					obj8 = ((nPC != null) ? nPC.DialogueHandler : null);
				}
				DialogueHandler val3 = (DialogueHandler)obj8;
				if ((Object)(object)val3 != (Object)null)
				{
					val3.EndDialogue();
				}
			}
			catch
			{
			}
			if (!UsesCustomerHomeRouting(contractTier))
			{
				try
				{
					MelonCoroutines.Start(WalkCustomerEscortToDoorAndComplete(customer, 

TheBigPimpin.MONO.dll

Decompiled 3 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using FishNet;
using FishNet.Object;
using HarmonyLib;
using MelonLoader;
using MelonLoader.Preferences;
using Microsoft.CodeAnalysis;
using NVorbis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using S1API.Entities;
using S1API.Entities.Appearances.AccessoryFields;
using S1API.Entities.Appearances.BodyLayerFields;
using S1API.Entities.Appearances.CustomizationFields;
using S1API.Entities.Appearances.FaceLayerFields;
using S1API.Internal.Abstraction;
using S1API.Items;
using S1API.Map;
using S1API.Quests;
using S1API.Quests.Identifiers;
using S1API.Saveables;
using S1API.Utils;
using ScheduleOne;
using ScheduleOne.AvatarFramework;
using ScheduleOne.AvatarFramework.Animation;
using ScheduleOne.AvatarFramework.Equipping;
using ScheduleOne.Calling;
using ScheduleOne.Combat;
using ScheduleOne.Core.Equipping.Framework;
using ScheduleOne.Core.Items.Framework;
using ScheduleOne.DevUtilities;
using ScheduleOne.Dialogue;
using ScheduleOne.Doors;
using ScheduleOne.Economy;
using ScheduleOne.Effects;
using ScheduleOne.GameTime;
using ScheduleOne.Interaction;
using ScheduleOne.ItemFramework;
using ScheduleOne.Law;
using ScheduleOne.Map;
using ScheduleOne.Messaging;
using ScheduleOne.Money;
using ScheduleOne.NPCs;
using ScheduleOne.NPCs.Actions;
using ScheduleOne.NPCs.Behaviour;
using ScheduleOne.NPCs.CharacterClasses;
using ScheduleOne.NPCs.Other;
using ScheduleOne.NPCs.Relation;
using ScheduleOne.NPCs.Responses;
using ScheduleOne.NPCs.Schedules;
using ScheduleOne.Persistence.Loaders;
using ScheduleOne.PlayerScripts;
using ScheduleOne.Police;
using ScheduleOne.Product;
using ScheduleOne.Product.Packaging;
using ScheduleOne.Quests;
using ScheduleOne.ScriptableObjects;
using ScheduleOne.Storage;
using ScheduleOne.UI;
using ScheduleOne.UI.Compass;
using ScheduleOne.UI.Handover;
using ScheduleOne.UI.Phone;
using ScheduleOne.UI.Phone.ContactsApp;
using ScheduleOne.UI.Phone.Messages;
using ScheduleOne.UI.Phone.ProductManagerApp;
using ScheduleOne.Vision;
using SteamNetworkLib;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.AI;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using bigpimpin;
using bigpimpin.Brothel;
using bigpimpin.Clients;
using bigpimpin.Compat;
using bigpimpin.Gltf;
using bigpimpin.Gltf.Data;
using bigpimpin.Gltf.Processing;
using bigpimpin.Helper;
using bigpimpin.Messaging;
using bigpimpin.NPC;
using bigpimpin.Net;
using bigpimpin.Patches;
using bigpimpin.Products;
using bigpimpin.Quests;
using bigpimpin.UI;
using bigpimpin.World;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: MelonInfo(typeof(bigpimpinMod), "BigPimpin", "1.0.11", "Virtunerd & Fadestyle", null)]
[assembly: MelonGame(null, null)]
[assembly: MelonOptionalDependencies(new string[] { "NVorbis" })]
[assembly: MelonAdditionalDependencies(new string[] { "S1API" })]
[assembly: AssemblyTitle("Big Pimpin")]
[assembly: AssemblyDescription("Big Pimpin Mod")]
[assembly: AssemblyCompany("Virtunerd")]
[assembly: AssemblyProduct("Big Pimpin")]
[assembly: AssemblyCopyright("Copyright © Virtunerd")]
[assembly: ComVisible(false)]
[assembly: Guid("b6c7a9f1-6c4a-4f6b-b9e2-123456789abc")]
[assembly: MelonColor(255, 255, 0, 255)]
[assembly: MelonAuthorColor(255, 0, 200, 255)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyFileVersion("1.0.11")]
[assembly: AssemblyInformationalVersion("1.0.11")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.11.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace bigpimpin
{
	public class bigpimpinMod : MelonMod
	{
		private bool _dataInitialized = false;

		private bool _npcSpawned = false;

		private bool _nativeRegistryReady = false;

		private float _nativeRegistryTimer = 0f;

		private const float NATIVE_REGISTRY_INTERVAL = 1.5f;

		private const string MAIN_SCENE_NAME = "Main";

		private bool _inMainScene = false;

		private int _lastPayoutDay = -1;

		private float _startupTimer = 0f;

		private const float NPC_SPAWN_DELAY = 3f;

		private float _saveDataRefreshTimer = 0f;

		private const float SAVE_DATA_REFRESH_INTERVAL = 2.5f;

		public override void OnInitializeMelon()
		{
			ModConfig.Initialize();
			if (!ModConfig.ModEnabled)
			{
				MelonLogger.Msg("[bigpimpin] Mod disabled via MelonPreferences (BigPimpin.Mod=false). Skipping init.");
				return;
			}
			TryRegisterIl2Cpp(typeof(BigPimpinCompassController));
			TryRegisterIl2Cpp(typeof(BrothelMapMarker));
		}

		private static void TryRegisterIl2Cpp(Type t)
		{
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			if (!ModConfig.ModEnabled)
			{
				return;
			}
			_inMainScene = string.Equals(sceneName, "Main", StringComparison.Ordinal);
			_lastPayoutDay = -1;
			if (!_inMainScene)
			{
				_nativeRegistryReady = false;
				_nativeRegistryTimer = 0f;
				_npcSpawned = false;
				_startupTimer = 0f;
				try
				{
					BrothelMusicController.Cleanup();
					return;
				}
				catch
				{
					return;
				}
			}
			try
			{
				EscortNPCRegistry.ResetForSceneReload();
			}
			catch (Exception)
			{
			}
			try
			{
				EscortStockManager.ResetTickClock();
			}
			catch
			{
			}
			try
			{
				EscortCokeDeadDropMonitor.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				PayphoneQuestStartController.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortLocationDisplayController.HideAll();
			}
			catch
			{
			}
			try
			{
				EscortDealerCollectHook.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortMobileInventoryHook.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortAutoHandoverWatcher.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				BigPimpinIntro.ResetQuestInstanceFlag();
			}
			catch
			{
			}
			try
			{
				WorldPositions.ResetBrothelDoorCache();
			}
			catch
			{
			}
			try
			{
				BrothelDeliveryLocations.ReassertRegistrations();
			}
			catch
			{
			}
			try
			{
				BrothelDeliveryLocations.TryEnsureAll();
			}
			catch
			{
			}
			try
			{
				EscortRoamingPOI.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortRoamingController.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortCityRoamingPOI.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortTracker.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortMugshotEnforcer.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortShowroomReveal.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				PimpProgressionManager.ResetNetworkSeed();
			}
			catch
			{
			}
			try
			{
				PimpFlowNetSync.ResetEarnedBaseline();
			}
			catch
			{
			}
			try
			{
				StashNetSync.Reset();
			}
			catch
			{
			}
			try
			{
				PunchNetSync.Reset();
			}
			catch
			{
			}
			try
			{
				BigPimpMapPoiController.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				WorldPoiScanner.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				BrothelMusicController.OnSceneLoaded();
			}
			catch
			{
			}
			MelonCoroutines.Start(DelayedApplyInitialRevealGate());
			MelonCoroutines.Start(DelayedScanWorldPois());
			MelonCoroutines.Start(DelayedReapplyLeverage());
		}

		private static IEnumerator DelayedApplyInitialRevealGate()
		{
			yield return (object)new WaitForSeconds(2f);
			try
			{
				EscortShowroomReveal.ApplyInitialGlbVisibility();
			}
			catch
			{
			}
		}

		private static IEnumerator DelayedScanWorldPois()
		{
			yield return (object)new WaitForSeconds(5f);
			try
			{
				WorldPoiScanner.Scan();
			}
			catch
			{
			}
			try
			{
				EscortRoamingPOI.ResetForSceneReload();
			}
			catch
			{
			}
			try
			{
				EscortCityRoamingPOI.ResetForSceneReload();
			}
			catch
			{
			}
		}

		private static IEnumerator DelayedReapplyLeverage()
		{
			yield return (object)new WaitForSeconds(6f);
			try
			{
				BlackmailRewardPatches.ReapplyActiveLeverage();
			}
			catch
			{
			}
		}

		private static void PerformResetAllHookers()
		{
			try
			{
				ModConfig.ClearResetAllHookers();
			}
			catch
			{
			}
			try
			{
				if (!NetworkHelper.IsHost)
				{
					return;
				}
			}
			catch
			{
			}
			try
			{
				EscortStockManager.ResetAllPunchStats();
			}
			catch
			{
			}
			try
			{
				PimpProgressionManager.ResetProgress();
			}
			catch
			{
			}
			try
			{
				EscortLocationDisplayController.Refresh();
			}
			catch
			{
			}
			try
			{
				BigPimpinSaveData.Instance?.PushNow();
			}
			catch
			{
			}
			try
			{
				BigPimpMessaging.SendPimpMessageExternal("Aight, clean slate. All the hoes reset, and I'm back at my spot behind the tattoo joint. Let's run it again.");
			}
			catch
			{
			}
			try
			{
				BPLog.Trace("pimp", "Reset All Hookers executed (matrix + progression reset, big pimp returned).");
			}
			catch
			{
			}
		}

		public override void OnUpdate()
		{
			if (!ModConfig.ModEnabled)
			{
				return;
			}
			try
			{
				ModNet.Tick(Time.deltaTime);
			}
			catch
			{
			}
			if (!_dataInitialized)
			{
				TryInitializeData();
			}
			else
			{
				if (!_inMainScene)
				{
					return;
				}
				BrothelManager.Update(Time.deltaTime);
				try
				{
					BrothelMusicController.Update(Time.deltaTime);
				}
				catch
				{
				}
				EscortContractService.Update(Time.deltaTime);
				EscortLocationDisplayController.Update(Time.deltaTime);
				EscortAutoHandoverWatcher.Update(Time.deltaTime);
				PayphoneQuestStartController.Update(Time.deltaTime);
				try
				{
					IntroNetSync.Tick(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					PimpFlowNetSync.Tick(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					StashNetSync.Tick(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					PunchNetSync.Tick(Time.deltaTime);
				}
				catch
				{
				}
				BigPimpMessaging.Update();
				try
				{
					bool flag = false;
					try
					{
						flag = ModNet.IsMultiplayer;
					}
					catch
					{
					}
					if (!NetworkHelper.IsHost || flag)
					{
						BigPimpNPC.EnsureClientModelVisible();
					}
					else
					{
						BigPimpNPC.EnsureNpcAnchored();
					}
				}
				catch
				{
				}
				try
				{
					BigPimpNPC.EnforceDummyHidden(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					MeetPimpAudioController.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					BigPimpMapPoiController.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					EscortContractPatches.TickCustomerRestoreWatchdog(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					if (ModConfig.ResetAllHookersRequested)
					{
						PerformResetAllHookers();
					}
				}
				catch
				{
				}
				try
				{
					EscortRoamingController.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					EscortTracker.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					EscortMugshotEnforcer.Update(Time.deltaTime);
				}
				catch
				{
				}
				try
				{
					EscortStockReminders.EnsureWired();
				}
				catch
				{
				}
				try
				{
					EscortStockManager.Tick();
				}
				catch
				{
				}
				try
				{
					TimeManager instance = NetworkSingleton<TimeManager>.Instance;
					if ((Object)(object)instance != (Object)null)
					{
						int elapsedDays = instance.ElapsedDays;
						BlackmailManager.TickWeeklyTithe(elapsedDays);
						if (_lastPayoutDay < 0)
						{
							_lastPayoutDay = elapsedDays;
						}
						else if (elapsedDays > _lastPayoutDay)
						{
							_lastPayoutDay = elapsedDays;
							try
							{
								DailyPayoutManager.OnDayEnded();
							}
							catch
							{
							}
						}
					}
				}
				catch
				{
				}
				try
				{
					EscortCokeDeadDropMonitor.Tick();
				}
				catch
				{
				}
				try
				{
					EscortDealerCollectHook.Tick();
				}
				catch
				{
				}
				try
				{
					EscortMobileInventoryHook.Tick();
				}
				catch
				{
				}
				try
				{
					EscortInventoryManager.TickDrainStashCoke(Time.deltaTime);
				}
				catch
				{
				}
				if (!_nativeRegistryReady)
				{
					TryInitNativeRegistry();
				}
				if (!_npcSpawned)
				{
					_startupTimer += Time.deltaTime;
					if (_startupTimer >= 3f)
					{
						TrySpawnNPC();
					}
				}
				EscortProductRegistry.TryApplyPendingRefresh();
				_saveDataRefreshTimer -= Time.deltaTime;
				if (_saveDataRefreshTimer <= 0f)
				{
					_saveDataRefreshTimer = 2.5f;
					BigPimpinSaveData.Instance?.PushNow();
				}
				try
				{
					BigPimpNPC.ApplyVisibilityFromRaveState();
				}
				catch
				{
				}
			}
		}

		private void TryInitNativeRegistry()
		{
			_nativeRegistryTimer -= Time.deltaTime;
			if (_nativeRegistryTimer > 0f)
			{
				return;
			}
			_nativeRegistryTimer = 1.5f;
			try
			{
				bool flag = BrothelDeliveryLocations.TryEnsureAll();
				EscortProductRegistry.RegisterAll();
				if (flag && EscortProductRegistry.All.Count > 0)
				{
					_nativeRegistryReady = true;
					MelonLogger.Msg("[bigpimpin] Native escort registry ready (products + delivery locations).");
				}
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] TryInitNativeRegistry: " + ex.Message);
			}
		}

		private void TryInitializeData()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			try
			{
				EscortManager.Initialize();
				BrothelManager.Initialize();
				BigPimpMessaging.Initialize();
				ModProductRegistry.RegisterProducts();
				new BigPimpinSaveData();
				GameObject val = new GameObject("BigPimpinCompass");
				val.AddComponent<BigPimpinCompassController>();
				Object.DontDestroyOnLoad((Object)(object)val);
				EscortContractService.Initialize();
				_dataInitialized = true;
				MelonLogger.Msg("[bigpimpin] Data initialized.");
			}
			catch (Exception ex)
			{
				MelonLogger.Error("[bigpimpin] Init failed: " + ex.Message);
			}
		}

		private void TrySpawnNPC()
		{
			try
			{
				BigPimpNPC instance = BigPimpNPC.Instance;
				if (instance != null)
				{
					GameObject val = null;
					try
					{
						val = ((NPC)instance).gameObject;
					}
					catch
					{
					}
					if ((Object)(object)val != (Object)null)
					{
						_npcSpawned = true;
						BPLog.Debug("[bigpimpin][spawn-diag] BigPimpNPC.Instance alive (host=" + NetworkHelper.IsHost + ") -> attaching GLB to it.");
						try
						{
							BigPimpNPC.EnsureModelOnExistingNpc();
							return;
						}
						catch
						{
							return;
						}
					}
				}
				try
				{
					NPC nPC = NPCManager.GetNPC("big_pimp");
					if ((Object)(object)nPC != (Object)null && (Object)(object)((Component)nPC).gameObject != (Object)null)
					{
						_npcSpawned = true;
						BPLog.Debug("[bigpimpin][spawn-diag] 'big_pimp' already in NPCManager (host=" + NetworkHelper.IsHost + ") -> attaching GLB to existing NPC.");
						try
						{
							BigPimpNPC.EnsureModelOnExistingNpc();
							return;
						}
						catch
						{
							return;
						}
					}
				}
				catch
				{
				}
				_startupTimer = 0f;
			}
			catch (Exception ex)
			{
				BPLog.DebugWarn("[bigpimpin][spawn-diag] TrySpawnNPC threw (host=" + NetworkHelper.IsHost + "): " + ex);
				_startupTimer = 0f;
			}
		}
	}
	internal sealed class BigPimpinSaveData : Saveable
	{
		[SaveableField("brothel_state")]
		private BrothelSaveData _data = new BrothelSaveData();

		public static BigPimpinSaveData Instance { get; private set; }

		public BigPimpinSaveData()
		{
			try
			{
				_data = BrothelSaveData.CreateFromCurrentState();
			}
			catch
			{
			}
			Instance = this;
		}

		public void PushNow()
		{
			try
			{
				_data = BrothelSaveData.CreateFromCurrentState();
			}
			catch (Exception)
			{
			}
		}

		protected override void OnCreated()
		{
			try
			{
				((Registerable)this).OnCreated();
			}
			catch
			{
			}
			try
			{
				BrothelSaveData.ResetAllToNewGame();
				MelonLogger.Msg("[bigpimpin] OnCreated: no mod save-blob -> reset all progression to New-Game defaults.");
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] OnCreated New-Game reset failed: " + ex.Message);
			}
		}

		protected override void OnLoaded()
		{
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(55, 3);
			defaultInterpolatedStringHandler.AppendLiteral("[bigpimpin] OnLoaded: data=");
			defaultInterpolatedStringHandler.AppendFormatted((_data == null) ? "NULL" : "ok");
			defaultInterpolatedStringHandler.AppendLiteral(", ");
			defaultInterpolatedStringHandler.AppendLiteral("IntroCompleted=");
			defaultInterpolatedStringHandler.AppendFormatted(_data?.IntroCompleted ?? false);
			defaultInterpolatedStringHandler.AppendLiteral(", ");
			defaultInterpolatedStringHandler.AppendLiteral("Escorts=");
			defaultInterpolatedStringHandler.AppendFormatted((_data?.Escorts?.Count).GetValueOrDefault());
			defaultInterpolatedStringHandler.AppendLiteral(".");
			MelonLogger.Msg(defaultInterpolatedStringHandler.ToStringAndClear());
			BrothelSaveData.LoadIntoCurrentState(_data ?? new BrothelSaveData());
			BrothelManager.SyncAfterLoad();
			try
			{
				BigPimpinIntro.EnsureQuestStarted();
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] EnsureQuestStarted (OnLoaded): " + ex.Message);
			}
		}

		protected override void OnSaved()
		{
			try
			{
				_data = BrothelSaveData.CreateFromCurrentState();
			}
			catch
			{
			}
		}
	}
}
namespace bigpimpin.Quests
{
	[QuestName("Big Pimp's Offer")]
	internal sealed class BigPimpIntroQuestId : IQuestIdentifier
	{
	}
	internal sealed class BigPimpIntroQuest : Quest
	{
		private static Sprite _cachedIcon;

		private static readonly FieldInfo _s1QuestEntryField = typeof(QuestEntry).GetField("S1QuestEntry", BindingFlags.Instance | BindingFlags.NonPublic);

		private float _lastPoiReapplyTime;

		private bool _postQuestPoiCleared;

		protected override string Title => "Big Pimp's Offer";

		protected override string Description => "Some weird looking - tiny - pimp called \"Big Pimp\" hit you up. Hear him out and see what the deal is.";

		protected override bool AutoBegin => true;

		protected override Sprite QuestIcon => GetCachedIcon();

		public QuestEntry EntryNelsonCall { get; private set; }

		public QuestEntry EntryMeetBigPimp { get; private set; }

		public QuestEntry EntryRead { get; private set; }

		public QuestEntry EntryReply { get; private set; }

		public QuestEntry EntryBuy { get; private set; }

		public QuestEntry EntryFinalStep { get; private set; }

		public QuestEntry EntryFirstHandover => EntryFinalStep;

		public BigPimpIntroQuest()
		{
			EntryNelsonCall = ((Quest)this).AddEntry("Answer Uncle Nelson's payphone call", (Vector3?)null);
			EntryMeetBigPimp = ((Quest)this).AddEntry("Go to the meeting behind Midnight Suites", (Vector3?)null);
			EntryRead = ((Quest)this).AddEntry("Read Big Pimp's message", (Vector3?)null);
			EntryReply = ((Quest)this).AddEntry("Reply to Big Pimp", (Vector3?)null);
			EntryBuy = ((Quest)this).AddEntry("Buy the brothel", (Vector3?)null);
			EntryFinalStep = ((Quest)this).AddEntry("Buy Street, Madam, Executive, then Presidential for Midnight Suites & keep the DeadDrop (or talk to an Escort) supplied with coke baggies. Upgrade your pimp status to buy more hoes.", (Vector3?)null);
			SuppressVanillaPoiMarkers();
			EntryFinalStep.OnComplete += OnFinalStepComplete;
			BigPimpinIntro.QuestInstanceCreated = true;
			MelonLogger.Msg("[bigpimpin] BigPimpIntroQuest constructed.");
		}

		public void EnsureBigPimpPoi()
		{
			SuppressVanillaPoiMarkers();
		}

		public void SuppressVanillaPoiMarkers()
		{
			SuppressVanillaPoiMarkersExcept(null);
		}

		public void RefreshMapPois()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			QuestEntry bigPimpMapEntry = GetBigPimpMapEntry();
			SuppressVanillaPoiMarkersExcept(bigPimpMapEntry);
			if (bigPimpMapEntry == null)
			{
				return;
			}
			try
			{
				bigPimpMapEntry.POIPosition = WorldPositions.GetBigPimpMeetingPosition();
				HideVanillaCompassReticle(bigPimpMapEntry);
				MelonCoroutines.Start(HideVanillaCompassReticleLate(bigPimpMapEntry));
			}
			catch
			{
			}
		}

		public void TickMarkerSuppression()
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				QuestEntry bigPimpMapEntry = GetBigPimpMapEntry();
				if (bigPimpMapEntry == null)
				{
					if (!_postQuestPoiCleared)
					{
						_postQuestPoiCleared = true;
						try
						{
							SuppressVanillaPoiMarkersExcept(null);
							return;
						}
						catch
						{
							return;
						}
					}
					return;
				}
				_postQuestPoiCleared = false;
				HideVanillaCompassReticle(bigPimpMapEntry);
				float unscaledTime = Time.unscaledTime;
				if (!(unscaledTime - _lastPoiReapplyTime >= 2f))
				{
					return;
				}
				_lastPoiReapplyTime = unscaledTime;
				try
				{
					Vector3 bigPimpMeetingPosition = WorldPositions.GetBigPimpMeetingPosition();
					Vector3 pOIPosition = bigPimpMapEntry.POIPosition;
					Vector3 val = pOIPosition - bigPimpMeetingPosition;
					if (((Vector3)(ref val)).sqrMagnitude > 0.25f)
					{
						bigPimpMapEntry.POIPosition = bigPimpMeetingPosition;
					}
				}
				catch
				{
				}
			}
			catch
			{
			}
		}

		private void SuppressVanillaPoiMarkersExcept(QuestEntry keep)
		{
			try
			{
				if (EntryNelsonCall != keep)
				{
					QuestEntry entryNelsonCall = EntryNelsonCall;
					if (entryNelsonCall != null)
					{
						entryNelsonCall.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryMeetBigPimp != keep)
				{
					QuestEntry entryMeetBigPimp = EntryMeetBigPimp;
					if (entryMeetBigPimp != null)
					{
						entryMeetBigPimp.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryRead != keep)
				{
					QuestEntry entryRead = EntryRead;
					if (entryRead != null)
					{
						entryRead.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryReply != keep)
				{
					QuestEntry entryReply = EntryReply;
					if (entryReply != null)
					{
						entryReply.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryBuy != keep)
				{
					QuestEntry entryBuy = EntryBuy;
					if (entryBuy != null)
					{
						entryBuy.ClearPOI();
					}
				}
			}
			catch
			{
			}
			try
			{
				if (EntryFinalStep != keep)
				{
					QuestEntry entryFinalStep = EntryFinalStep;
					if (entryFinalStep != null)
					{
						entryFinalStep.ClearPOI();
					}
				}
			}
			catch
			{
			}
		}

		private QuestEntry GetBigPimpMapEntry()
		{
			return null;
		}

		private static IEnumerator HideVanillaCompassReticleLate(QuestEntry entry)
		{
			for (int i = 0; i < 12; i++)
			{
				yield return null;
				HideVanillaCompassReticle(entry);
			}
		}

		private static void HideVanillaCompassReticle(QuestEntry entry)
		{
			try
			{
				object? obj = _s1QuestEntryField?.GetValue(entry);
				Element val = ((QuestEntry)(((obj is QuestEntry) ? obj : null)?)).compassElement;
				if (val != null)
				{
					val.Visible = false;
					if ((Object)(object)val.Rect != (Object)null && (Object)(object)((Component)val.Rect).gameObject != (Object)null)
					{
						((Component)val.Rect).gameObject.SetActive(false);
					}
					if ((Object)(object)val.Group != (Object)null)
					{
						val.Group.alpha = 0f;
					}
				}
			}
			catch
			{
			}
		}

		private static Sprite GetCachedIcon()
		{
			if ((Object)(object)_cachedIcon != (Object)null)
			{
				return _cachedIcon;
			}
			try
			{
				_cachedIcon = ImageUtils.LoadImageFromResource(Assembly.GetExecutingAssembly(), "bigpimpin.assets.icon.png", 100f, (FilterMode)1);
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] QuestIcon load failed: " + ex.Message);
			}
			return _cachedIcon;
		}

		private static void OnFinalStepComplete()
		{
			MelonLogger.Msg("[bigpimpin] BigPimpIntroQuest fully completed.");
		}
	}
}
namespace bigpimpin.Products
{
	internal static class EscortProductRegistry
	{
		private static readonly Dictionary<EscortTier, ProductDefinition> _byTier = new Dictionary<EscortTier, ProductDefinition>();

		private static readonly Dictionary<string, EscortTier> _byId = new Dictionary<string, EscortTier>(StringComparer.OrdinalIgnoreCase);

		private static Sprite _cachedProductSprite;

		private static Texture2D _cachedProductTexture;

		private const string ProductIconResource = "bigpimpin.assets.product.png";

		private static readonly Dictionary<EscortTier, Sprite> _tierSprites = new Dictionary<EscortTier, Sprite>();

		private static readonly Dictionary<EscortTier, string[]> _tierIconResources = new Dictionary<EscortTier, string[]>
		{
			{
				EscortTier.Street,
				new string[2] { "bigpimpin.assets.date_street.png", "bigpimpin.assets.street.png" }
			},
			{
				EscortTier.Madam,
				new string[2] { "bigpimpin.assets.date_madam.png", "bigpimpin.assets.madam.png" }
			},
			{
				EscortTier.Executive,
				new string[2] { "bigpimpin.assets.date_exec.png", "bigpimpin.assets.executive.png" }
			},
			{
				EscortTier.Presidential,
				new string[2] { "bigpimpin.assets.date_pres.png", "bigpimpin.assets.presidencial.png" }
			}
		};

		private static readonly Dictionary<string, bool> _listedById = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, int> _persistedPriceById = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);

		private static readonly string[] TemplateCandidates = new string[1] { "ogkush" };

		private static bool _pendingRefresh;

		public static IReadOnlyDictionary<EscortTier, ProductDefinition> All => _byTier;

		public static ProductDefinition Get(EscortTier tier)
		{
			_byTier.TryGetValue(tier, out var value);
			return value;
		}

		public static bool TryResolveTier(string productId, out EscortTier tier)
		{
			return _byId.TryGetValue(productId ?? string.Empty, out tier);
		}

		public static EscortTier ResolveTier(string productId)
		{
			_byId.TryGetValue(productId ?? string.Empty, out var value);
			return value;
		}

		private static bool IsTierUnlocked(string productId)
		{
			try
			{
				EscortTier tier;
				return TryResolveTier(productId, out tier) && EscortDealerUnlocks.IsUnlocked(tier);
			}
			catch
			{
				return false;
			}
		}

		private static bool IsTierUnlocked(ProductDefinition def)
		{
			try
			{
				return (Object)(object)def != (Object)null && IsTierUnlocked(((BaseItemDefinition)def).ID);
			}
			catch
			{
				return false;
			}
		}

		public static void RegisterAll()
		{
			try
			{
				ProductDefinition val = TryFindTemplate();
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				int count = _byTier.Count;
				Register(EscortTier.Street, "bp_escort_street", "Street Date", 350, val);
				Register(EscortTier.Madam, "bp_escort_madam", "Madam Date", 500, val);
				Register(EscortTier.Executive, "bp_escort_exec", "Executive Date", 1500, val);
				Register(EscortTier.Presidential, "bp_escort_pres", "Presidential Date", 2500, val);
				foreach (ProductDefinition value2 in _byTier.Values)
				{
					if ((Object)(object)value2 != (Object)null)
					{
						SyncWithProductManager(value2);
					}
				}
				if (_byTier.Count <= count)
				{
				}
			}
			catch (Exception value)
			{
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(47, 1);
				defaultInterpolatedStringHandler.AppendLiteral("[bigpimpin] EscortProductRegistry.RegisterAll: ");
				defaultInterpolatedStringHandler.AppendFormatted(value);
				MelonLogger.Error(defaultInterpolatedStringHandler.ToStringAndClear());
			}
		}

		private static ProductDefinition TryFindTemplate()
		{
			for (int i = 0; i < TemplateCandidates.Length; i++)
			{
				try
				{
					ItemDefinition item = Registry.GetItem(TemplateCandidates[i]);
					ProductDefinition val = (((Object)(object)item != (Object)null) ? item.TryCast<ProductDefinition>() : null);
					if ((Object)(object)val != (Object)null)
					{
						return val;
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private static void Register(EscortTier tier, string id, string displayName, int basePrice, ProductDefinition template)
		{
			try
			{
				if (_byTier.ContainsKey(tier))
				{
					return;
				}
				ItemDefinition item = Registry.GetItem(id);
				ProductDefinition val;
				if ((Object)(object)item != (Object)null)
				{
					val = item.TryCast<ProductDefinition>();
					if ((Object)(object)val != (Object)null)
					{
						PatchItemDefinition(val, id, displayName, basePrice, tier);
					}
				}
				else
				{
					val = Object.Instantiate<ProductDefinition>(template);
					PatchItemDefinition(val, id, displayName, basePrice, tier);
					try
					{
						Singleton<Registry>.Instance.AddToRegistry((ItemDefinition)(object)val);
					}
					catch (Exception)
					{
					}
				}
				if (!((Object)(object)val == (Object)null))
				{
					_byTier[tier] = val;
					_byId[id] = tier;
				}
			}
			catch (Exception value)
			{
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(46, 2);
				defaultInterpolatedStringHandler.AppendLiteral("[bigpimpin] EscortProductRegistry.Register(");
				defaultInterpolatedStringHandler.AppendFormatted(id);
				defaultInterpolatedStringHandler.AppendLiteral("): ");
				defaultInterpolatedStringHandler.AppendFormatted(value);
				MelonLogger.Error(defaultInterpolatedStringHandler.ToStringAndClear());
			}
		}

		private static void PatchItemDefinition(ProductDefinition clone, string id, string displayName, int basePrice, EscortTier tier)
		{
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ef: Expected O, but got Unknown
			try
			{
				((Object)clone).name = id;
			}
			catch
			{
			}
			try
			{
				((BaseItemDefinition)clone).ID = id;
			}
			catch
			{
			}
			try
			{
				((BaseItemDefinition)clone).Name = displayName;
			}
			catch
			{
			}
			try
			{
				((BaseItemDefinition)clone).Description = displayName + " booking — handoff at the Midnight Suites door.";
			}
			catch
			{
			}
			try
			{
				clone.BasePrice = basePrice;
			}
			catch
			{
			}
			try
			{
				clone.MarketValue = basePrice;
			}
			catch
			{
			}
			try
			{
				((StorableItemDefinition)clone).BasePurchasePrice = basePrice;
			}
			catch
			{
			}
			try
			{
				switch (tier)
				{
				case EscortTier.Street:
					clone.BaseAddictiveness = 0f;
					break;
				case EscortTier.Madam:
					clone.BaseAddictiveness = 0.5f;
					break;
				case EscortTier.Executive:
					clone.BaseAddictiveness = 0.75f;
					break;
				case EscortTier.Presidential:
					clone.BaseAddictiveness = 1f;
					break;
				}
			}
			catch
			{
			}
			int value2;
			float value = ((_persistedPriceById.TryGetValue(id, out value2) && value2 > 0) ? value2 : basePrice);
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				if ((Object)(object)instance != (Object)null && instance.ProductPrices != null)
				{
					instance.ProductPrices[clone] = value;
				}
			}
			catch
			{
			}
			try
			{
				((BaseItemDefinition)clone).StackLimit = 1;
			}
			catch
			{
			}
			try
			{
				clone.FunctionalProduct = null;
			}
			catch
			{
			}
			try
			{
				((ItemDefinition)clone).Equippable = null;
			}
			catch
			{
			}
			try
			{
				((StorableItemDefinition)clone).StationItem = null;
			}
			catch
			{
			}
			try
			{
				((StorableItemDefinition)clone).StoredItem = null;
			}
			catch
			{
			}
			try
			{
				clone.ValidPackaging = GameCompat.RefArray<PackagingDefinition>(0);
			}
			catch
			{
				try
				{
					clone.ValidPackaging = null;
				}
				catch
				{
				}
			}
			try
			{
				((StorableItemDefinition)clone).ShopCategories = null;
			}
			catch
			{
			}
			try
			{
				((StorableItemDefinition)clone).CombatUtility = 0f;
			}
			catch
			{
			}
			try
			{
				List<DrugTypeContainer> list = new List<DrugTypeContainer>();
				DrugTypeContainer item = new DrugTypeContainer
				{
					DrugType = (EDrugType)5
				};
				list.Add(item);
				clone.DrugTypes = list;
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] CHANGE-280 assign DrugTypes(Heroin) failed for " + id + ": " + ex.Message);
			}
			try
			{
				Sprite val = LoadTierSprite(tier);
				if ((Object)(object)val != (Object)null)
				{
					((BaseItemDefinition)clone).Icon = val;
				}
			}
			catch (Exception)
			{
			}
		}

		private static Sprite LoadProductSprite()
		{
			if ((Object)(object)_cachedProductSprite != (Object)null)
			{
				return _cachedProductSprite;
			}
			_cachedProductSprite = LoadSpriteFromResource("bigpimpin.assets.product.png", out _cachedProductTexture);
			return _cachedProductSprite;
		}

		private static Sprite LoadTierSprite(EscortTier tier)
		{
			if (_tierSprites.TryGetValue(tier, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (_tierIconResources.TryGetValue(tier, out var value2))
			{
				for (int i = 0; i < value2.Length; i++)
				{
					Texture2D tex;
					Sprite val = LoadSpriteFromResource(value2[i], out tex);
					if ((Object)(object)val != (Object)null)
					{
						_tierSprites[tier] = val;
						return val;
					}
				}
			}
			Sprite val2 = LoadProductSprite();
			if ((Object)(object)val2 != (Object)null)
			{
				_tierSprites[tier] = val2;
			}
			return val2;
		}

		private static Sprite LoadSpriteFromResource(string resourceName, out Texture2D tex)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			tex = null;
			try
			{
				Assembly executingAssembly = Assembly.GetExecutingAssembly();
				using Stream stream = executingAssembly.GetManifestResourceStream(resourceName);
				if (stream == null)
				{
					return null;
				}
				byte[] array = new byte[stream.Length];
				stream.Read(array, 0, array.Length);
				Texture2D val = new Texture2D(2, 2);
				if (!ImageConversion.LoadImage(val, array))
				{
					return null;
				}
				Object.DontDestroyOnLoad((Object)(object)val);
				tex = val;
				Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				Object.DontDestroyOnLoad((Object)(object)val2);
				return val2;
			}
			catch
			{
				return null;
			}
		}

		public static bool IsEscortProduct(ProductDefinition def)
		{
			try
			{
				return (Object)(object)def != (Object)null && _byId.ContainsKey(((BaseItemDefinition)def).ID ?? string.Empty);
			}
			catch
			{
				return false;
			}
		}

		public static bool IsListed(ProductDefinition def)
		{
			try
			{
				return (Object)(object)def != (Object)null && IsListed(((BaseItemDefinition)def).ID);
			}
			catch
			{
				return false;
			}
		}

		public static bool IsListed(string productId)
		{
			if (string.IsNullOrWhiteSpace(productId))
			{
				return false;
			}
			bool value;
			return _listedById.TryGetValue(productId, out value) && value;
		}

		public static void SetListed(ProductDefinition def, bool listed)
		{
			if ((Object)(object)def == (Object)null)
			{
				return;
			}
			try
			{
				SetListed(((BaseItemDefinition)def).ID, listed);
			}
			catch
			{
			}
		}

		public static void SetListed(string productId, bool listed)
		{
			if (!string.IsNullOrWhiteSpace(productId))
			{
				if (!BigPimpinIntro.IsActivated())
				{
					listed = false;
				}
				if (!IsTierUnlocked(productId))
				{
					listed = false;
				}
				_listedById[productId] = listed;
				SyncListedProduct(productId, listed);
			}
		}

		public static Dictionary<string, bool> GetListedStateForSave()
		{
			return new Dictionary<string, bool>(_listedById, StringComparer.OrdinalIgnoreCase);
		}

		public static void LoadListedState(Dictionary<string, bool> listedById)
		{
			_listedById.Clear();
			if (listedById == null)
			{
				return;
			}
			foreach (KeyValuePair<string, bool> item in listedById)
			{
				if (!string.IsNullOrWhiteSpace(item.Key))
				{
					_listedById[item.Key] = item.Value;
				}
			}
			foreach (KeyValuePair<string, bool> item2 in _listedById)
			{
				if (!string.IsNullOrWhiteSpace(item2.Key))
				{
					try
					{
						SyncListedProduct(item2.Key, item2.Value);
					}
					catch
					{
					}
				}
			}
		}

		public static Dictionary<string, int> GetPricesForSave()
		{
			Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				foreach (KeyValuePair<EscortTier, ProductDefinition> item in _byTier)
				{
					ProductDefinition value = item.Value;
					if (!((Object)(object)value == (Object)null))
					{
						float num = 0f;
						num = ((!((Object)(object)instance != (Object)null) || instance.ProductPrices == null || !instance.ProductPrices.TryGetValue(value, out var value2)) ? value.BasePrice : value2);
						int num2 = Mathf.RoundToInt(num);
						if (num2 > 0)
						{
							dictionary[((BaseItemDefinition)value).ID] = num2;
						}
					}
				}
			}
			catch
			{
			}
			return dictionary;
		}

		public static void LoadPricesState(Dictionary<string, int> prices)
		{
			_persistedPriceById.Clear();
			ProductManager instance = NetworkSingleton<ProductManager>.Instance;
			if (prices == null)
			{
				return;
			}
			foreach (KeyValuePair<string, int> price in prices)
			{
				if (string.IsNullOrWhiteSpace(price.Key) || price.Value <= 0)
				{
					continue;
				}
				_persistedPriceById[price.Key] = price.Value;
				ProductDefinition val = null;
				try
				{
					val = Registry.GetItem(price.Key)?.TryCast<ProductDefinition>();
				}
				catch
				{
				}
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				try
				{
					if ((Object)(object)instance != (Object)null && instance.ProductPrices != null)
					{
						instance.ProductPrices[val] = price.Value;
					}
				}
				catch
				{
				}
			}
		}

		private static void ApplyTierVisibilityGate(ProductDefinition def)
		{
			if ((Object)(object)def == (Object)null || (BigPimpinIntro.IsActivated() && IsTierUnlocked(def)))
			{
				return;
			}
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				if (instance?.AllProducts != null && instance.AllProducts.Contains(def))
				{
					instance.AllProducts.Remove(def);
				}
			}
			catch
			{
			}
			try
			{
				List<ProductDefinition> discoveredProducts = ProductManager.DiscoveredProducts;
				if (discoveredProducts != null && discoveredProducts.Contains(def))
				{
					discoveredProducts.Remove(def);
				}
			}
			catch
			{
			}
			try
			{
				SyncListedProduct(((BaseItemDefinition)def).ID, listed: false);
			}
			catch
			{
			}
		}

		private static void SyncWithProductManager(ProductDefinition def)
		{
			try
			{
				ProductManager instance = NetworkSingleton<ProductManager>.Instance;
				if ((Object)(object)instance != (Object)null)
				{
					List<ProductDefinition> allProducts = instance.AllProducts;
					if (allProducts != null && !allProducts.Contains(def))
					{
						allProducts.Add(def);
					}
				}
			}
			catch
			{
			}
			try
			{
				List<ProductDefinition> discoveredProducts = ProductManager.DiscoveredProducts;
				if (discoveredProducts != null && !discoveredProducts.Contains(def))
				{
					discoveredProducts.Add(def);
				}
			}
			catch
			{
			}
			try
			{
				if ((Object)(object)def != (Object)null && _listedById.TryGetValue(((BaseItemDefinition)def).ID, out var value))
				{
					SyncListedProduct(((BaseItemDefinition)def).ID, value);
				}
			}
			catch
			{
			}
		}

		public static void ReapplyVisibility()
		{
			try
			{
				foreach (ProductDefinition value in _byTier.Values)
				{
					if (!((Object)(object)value == (Object)null))
					{
						SyncWithProductManager(value);
						ApplyTierVisibilityGate(value);
					}
				}
				RequestProductManagerRefresh();
			}
			catch
			{
			}
		}

		public static void RefreshVisibility()
		{
			try
			{
				foreach (ProductDefinition value in _byTier.Values)
				{
					if (!((Object)(object)value == (Object)null))
					{
						SyncWithProductManager(value);
						if (BigPimpinIntro.IsActivated() && IsTierUnlocked(value) && !IsListed(value))
						{
							SetListed(value, listed: true);
						}
						ApplyTierVisibilityGate(value);
					}
				}
				RequestProductManagerRefresh();
			}
			catch (Exception)
			{
			}
		}

		private static void SyncListedProduct(string productId, bool listed)
		{
			if (!BigPimpinIntro.IsActivated())
			{
				listed = false;
			}
			if (listed && !IsTierUnlocked(productId))
			{
				listed = false;
			}
			ProductDefinition val = null;
			try
			{
				val = Registry.GetItem(productId)?.TryCast<ProductDefinition>();
			}
			catch
			{
			}
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				List<ProductDefinition> listedProducts = ProductManager.ListedProducts;
				if (listedProducts != null)
				{
					bool flag = listedProducts.Contains(val);
					if (listed && !flag)
					{
						listedProducts.Add(val);
					}
					else if (!listed && flag)
					{
						listedProducts.Remove(val);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		public static void PurgeFromProductManagerLists()
		{
			foreach (ProductDefinition value in _byTier.Values)
			{
				if ((Object)(object)value == (Object)null)
				{
					continue;
				}
				try
				{
					List<ProductDefinition> discoveredProducts = ProductManager.DiscoveredProducts;
					if (discoveredProducts != null && discoveredProducts.Contains(value))
					{
						discoveredProducts.Remove(value);
					}
				}
				catch
				{
				}
				try
				{
					List<ProductDefinition> listedProducts = ProductManager.ListedProducts;
					if (listedProducts != null && listedProducts.Contains(value))
					{
						listedProducts.Remove(value);
					}
				}
				catch
				{
				}
			}
		}

		public static void RequestProductManagerRefresh()
		{
			_pendingRefresh = true;
		}

		public static void TryApplyPendingRefresh()
		{
			if (_pendingRefresh)
			{
				_pendingRefresh = false;
			}
		}
	}
	internal static class ModProductRegistry
	{
		internal static Dictionary<EscortTier, ItemDefinition> EscortContracts = new Dictionary<EscortTier, ItemDefinition>();

		internal static void RegisterProducts()
		{
		}

		internal static ItemDefinition GetContract(EscortTier tier)
		{
			if (EscortContracts.TryGetValue(tier, out var value))
			{
				return value;
			}
			return null;
		}
	}
}
namespace bigpimpin.Patches
{
	internal static class BlackmailRewardPatches
	{
		[HarmonyPatch]
		internal static class Patch_BusinessOwnerPrice_Float
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(float), IsShopType, IsPriceMethod, _shopTypeSuffixes);
			}

			private static void Postfix(object __instance, ref float __result)
			{
				try
				{
					if (__result <= 0f)
					{
						return;
					}
					float discountFactorForContext = BlackmailManager.GetDiscountFactorForContext(__instance);
					if (discountFactorForContext >= 1f)
					{
						LogDiscountMissReason(__instance);
						return;
					}
					__result *= (IsPawnContext(__instance) ? (2f - discountFactorForContext) : discountFactorForContext);
					if (!_loggedDiscount)
					{
						_loggedDiscount = true;
						BPLog.Debug("Blackmail discount applied to shop float price.");
					}
				}
				catch
				{
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_BusinessOwnerPrice_Int
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(int), IsShopType, IsPriceMethod, _shopTypeSuffixes);
			}

			private static void Postfix(object __instance, ref int __result)
			{
				try
				{
					if (__result <= 0)
					{
						return;
					}
					float discountFactorForContext = BlackmailManager.GetDiscountFactorForContext(__instance);
					if (discountFactorForContext >= 1f)
					{
						LogDiscountMissReason(__instance);
						return;
					}
					float num = (IsPawnContext(__instance) ? (2f - discountFactorForContext) : discountFactorForContext);
					__result = Math.Max(1, (int)Math.Ceiling((float)__result * num));
					if (!_loggedDiscount)
					{
						_loggedDiscount = true;
						BPLog.Debug("Blackmail discount applied to shop int price.");
					}
				}
				catch
				{
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_PoliceSearch_Bool
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(bool), IsPoliceSearchType, IsBlockableMethod, _policeTypeSuffixes);
			}

			private static bool Prefix(object __instance, ref bool __result)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					__result = false;
					if (!_loggedSearchBlock)
					{
						_loggedSearchBlock = true;
						BPLog.Debug("Blackmail blocked a police/search bool check.");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_PoliceSearch_Void
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(void), IsPoliceSearchType, IsBlockableMethod, _policeTypeSuffixes);
			}

			private static bool Prefix(object __instance)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					if (!_loggedSearchBlock)
					{
						_loggedSearchBlock = true;
						BPLog.Debug("Blackmail blocked a police/search action.");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(PoliceOfficer), "BeginBodySearch")]
		internal static class Patch_PoliceOfficer_BeginBodySearch
		{
			private static bool Prefix(PoliceOfficer __instance)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					if (!_loggedSearchBlock)
					{
						_loggedSearchBlock = true;
						BPLog.Debug("Blackmail blocked PoliceOfficer.BeginBodySearch (cop leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(PoliceOfficer), "ConductBodySearch")]
		internal static class Patch_PoliceOfficer_ConductBodySearch
		{
			private static bool Prefix(PoliceOfficer __instance)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					if (!_loggedSearchBlock)
					{
						_loggedSearchBlock = true;
						BPLog.Debug("Blackmail blocked PoliceOfficer.ConductBodySearch (cop leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(PoliceOfficer), "CheckNewInvestigation")]
		internal static class Patch_PoliceOfficer_CheckNewInvestigation
		{
			private static bool Prefix(PoliceOfficer __instance)
			{
				try
				{
					if (!BlackmailManager.IsActive(BlackmailTargetClass.Cop))
					{
						return true;
					}
					if (!BlackmailManager.ShouldBlockPoliceSearch(ResolveNpc(__instance)))
					{
						return true;
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_Curfew_Bool
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(bool), IsCurfewType, IsBlockableMethod, _curfewTypeSuffixes);
			}

			private static bool Prefix(ref bool __result)
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					__result = false;
					if (!_loggedCurfewBlock)
					{
						_loggedCurfewBlock = true;
						BPLog.Debug("Blackmail blocked a curfew bool check.");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch]
		internal static class Patch_Curfew_Void
		{
			[HarmonyPrepare]
			private static bool Prepare()
			{
				foreach (MethodBase item in TargetMethods())
				{
					if (item != null)
					{
						return true;
					}
				}
				return false;
			}

			private static IEnumerable<MethodBase> TargetMethods()
			{
				return FindMethods(typeof(void), IsCurfewType, IsBlockableMethod, _curfewTypeSuffixes);
			}

			private static bool Prefix()
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					if (!_loggedCurfewBlock)
					{
						_loggedCurfewBlock = true;
						BPLog.Debug("Blackmail blocked a curfew action.");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(CurfewManager), "Enable")]
		internal static class Patch_CurfewManager_Enable
		{
			private static bool Prefix()
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					if (!_loggedCurfewBlock)
					{
						_loggedCurfewBlock = true;
						BPLog.Debug("Blackmail blocked CurfewManager.Enable (mayor leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(CheckpointInstance), "Evaluate")]
		internal static class Patch_CheckpointInstance_Evaluate
		{
			private static bool Prefix(CheckpointInstance __instance)
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					try
					{
						if (__instance != null)
						{
							__instance.DisableCheckpoint();
						}
					}
					catch
					{
					}
					if (!_loggedCheckpointBlock)
					{
						_loggedCheckpointBlock = true;
						BPLog.Debug("Blackmail blocked CheckpointInstance.Evaluate (mayor leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(CheckpointInstance), "EnableCheckpoint")]
		internal static class Patch_CheckpointInstance_Enable
		{
			private static bool Prefix(CheckpointInstance __instance)
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					if (!_loggedCheckpointBlock)
					{
						_loggedCheckpointBlock = true;
						BPLog.Debug("Blackmail blocked CheckpointInstance.EnableCheckpoint (mayor leverage).");
					}
					return false;
				}
				catch
				{
					return true;
				}
			}
		}

		[HarmonyPatch(typeof(CheckpointManager), "SetCheckpointEnabled")]
		internal static class Patch_CheckpointManager_SetEnabled
		{
			private static bool Prefix(ref bool enabled)
			{
				try
				{
					if (!BlackmailManager.ShouldBlockCurfew())
					{
						return true;
					}
					if (!enabled)
					{
						return true;
					}
					enabled = false;
					if (!_loggedCheckpointBlock)
					{
						_loggedCheckpointBlock = true;
						BPLog.Debug("Blackmail forced SetCheckpointEnabled=false (mayor leverage).");
					}
					return true;
				}
				catch
				{
					return true;
				}
			}
		}

		private static bool _loggedDiscount;

		private static bool _loggedSearchBlock;

		private static bool _loggedCurfewBlock;

		private static bool _loggedCheckpointBlock;

		private static float _lastDiagLogTime;

		private const float DiagLogIntervalSeconds = 5f;

		private static bool _loggedReapply;

		private static readonly string[] _shopTypeSuffixes = new string[3] { "UI.Shop.Cart", "UI.PawnShopInterface", "UI.Phone.Delivery.DeliveryShop" };

		private static readonly string[] _policeTypeSuffixes = new string[3] { "Effects.Seizure", "UI.BodySearchScreen", "UI.Items.FilterConfigPanel+SearchCategory" };

		private static readonly string[] _curfewTypeSuffixes = new string[3] { "Law.CurfewManager", "Law.CurfewInstance", "Law.ViolatingCurfew" };

		private static readonly string[] _gameNamespacePrefixes = new string[2] { "Il2CppScheduleOne.", "ScheduleOne." };

		private static float DiscountMultiplier()
		{
			int num = ModConfig.BlackmailBusinessDiscountPercent;
			if (num < 0)
			{
				num = 0;
			}
			if (num > 100)
			{
				num = 100;
			}
			return 1f - (float)num / 100f;
		}

		private static void LogDiscountMissReason(object ctx)
		{
			try
			{
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				if (!(realtimeSinceStartup - _lastDiagLogTime < 5f))
				{
					_lastDiagLogTime = realtimeSinceStartup;
					BPLog.Debug("Shop-discount skip: " + BlackmailManager.DiagnoseDiscountForContext(ctx));
				}
			}
			catch
			{
			}
		}

		public static void ReapplyActiveLeverage()
		{
			try
			{
				bool value = BlackmailManager.IsUnlocked(BlackmailTargetClass.BusinessOwner);
				bool value2 = BlackmailManager.IsActive(BlackmailTargetClass.Cop);
				bool flag = BlackmailManager.ShouldBlockCurfew();
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(62, 3);
				defaultInterpolatedStringHandler.AppendLiteral("[blackmail] reapply leverage after load: business=");
				defaultInterpolatedStringHandler.AppendFormatted(value);
				defaultInterpolatedStringHandler.AppendLiteral(" cop=");
				defaultInterpolatedStringHandler.AppendFormatted(value2);
				defaultInterpolatedStringHandler.AppendLiteral(" mayor=");
				defaultInterpolatedStringHandler.AppendFormatted(flag);
				BPLog.Debug(defaultInterpolatedStringHandler.ToStringAndClear());
				if (flag)
				{
					LiftStandingCurfewAndCheckpoints();
				}
			}
			catch
			{
			}
		}

		public static void LiftStandingCurfewAndCheckpoints()
		{
			try
			{
				if (!BlackmailManager.ShouldBlockCurfew() || !NetworkHelper.IsHost)
				{
					return;
				}
				try
				{
					CheckpointManager val = null;
					try
					{
						val = NetworkSingleton<CheckpointManager>.Instance;
					}
					catch
					{
					}
					if ((Object)(object)val != (Object)null)
					{
						val.SetCheckpointEnabled((ECheckpointLocation)0, false, 0);
						val.SetCheckpointEnabled((ECheckpointLocation)1, false, 0);
						val.SetCheckpointEnabled((ECheckpointLocation)2, false, 0);
						val.SetCheckpointEnabled((ECheckpointLocation)3, false, 0);
					}
				}
				catch
				{
				}
				try
				{
					CurfewManager val2 = null;
					try
					{
						val2 = NetworkSingleton<CurfewManager>.Instance;
					}
					catch
					{
					}
					if ((Object)(object)val2 != (Object)null)
					{
						val2.Disable();
					}
				}
				catch
				{
				}
				if (!_loggedReapply)
				{
					_loggedReapply = true;
					BPLog.Debug("[blackmail] mayor leverage: standing curfew disabled + checkpoints cleared.");
				}
			}
			catch
			{
			}
		}

		private static Type ResolveGameType(string suffix)
		{
			try
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly in assemblies)
				{
					string text;
					try
					{
						text = assembly.GetName().Name ?? string.Empty;
					}
					catch
					{
						continue;
					}
					if (!text.Contains("Assembly-CSharp") && !text.Contains("Il2CppScheduleOne"))
					{
						continue;
					}
					for (int j = 0; j < _gameNamespacePrefixes.Length; j++)
					{
						try
						{
							Type type = assembly.GetType(_gameNamespacePrefixes[j] + suffix, throwOnError: false);
							if (type != null)
							{
								return type;
							}
						}
						catch
						{
						}
					}
				}
			}
			catch
			{
			}
			return null;
		}

		private static IEnumerable<MethodBase> FindMethods(Type returnType, Func<Type, bool> typeFilter, Func<MethodInfo, bool> methodFilter, string[] typeSuffixes)
		{
			List<MethodBase> list = new List<MethodBase>();
			try
			{
				for (int i = 0; i < typeSuffixes.Length; i++)
				{
					Type type = ResolveGameType(typeSuffixes[i]);
					if (type == null || !typeFilter(type))
					{
						continue;
					}
					MethodInfo[] methods;
					try
					{
						methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					}
					catch
					{
						continue;
					}
					foreach (MethodInfo methodInfo in methods)
					{
						if (!(methodInfo == null) && !methodInfo.IsAbstract && !methodInfo.ContainsGenericParameters && !methodInfo.IsSpecialName && !(methodInfo.ReturnType != returnType) && methodFilter(methodInfo))
						{
							list.Add(methodInfo);
						}
					}
				}
			}
			catch
			{
			}
			return list;
		}

		private static bool IsShopType(Type type)
		{
			string value = (type.FullName ?? type.Name).ToLowerInvariant();
			return ContainsAny(value, "shop", "store", "vendor", "merchant", "business");
		}

		private static bool IsPoliceSearchType(Type type)
		{
			string value = (type.FullName ?? type.Name).ToLowerInvariant();
			return ContainsAny(value, "bodysearch", "search", "seizure", "contraband");
		}

		private static bool IsCurfewType(Type type)
		{
			string text = (type.FullName ?? type.Name).ToLowerInvariant();
			return text.Contains("curfew");
		}

		private static bool IsPriceMethod(MethodInfo method)
		{
			string value = method.Name.ToLowerInvariant();
			return ContainsAny(value, "price", "cost", "value", "amount", "purchase") && !ContainsAny(value, "set_", "add_", "remove_");
		}

		private static bool IsBlockableMethod(MethodInfo method)
		{
			string value = method.Name.ToLowerInvariant();
			if (ContainsAny(value, "save", "load", "serialize", "deserialize", "shouldsave"))
			{
				return false;
			}
			return ContainsAny(value, "search", "bust", "curfew", "contraband", "seize", "arrest", "fine", "check", "can", "should", "apply", "begin", "start", "enforce") && !ContainsAny(value, "set_", "add_", "remove_", "update");
		}

		private static bool IsPawnContext(object instance)
		{
			try
			{
				return instance != null && (instance.GetType().Name ?? string.Empty).IndexOf("PawnShop", StringComparison.OrdinalIgnoreCase) >= 0;
			}
			catch
			{
				return false;
			}
		}

		private static NPC ResolveNpc(object instance)
		{
			try
			{
				if (instance == null)
				{
					return null;
				}
				NPC val = (NPC)((instance is NPC) ? instance : null);
				if (val != null)
				{
					return val;
				}
				Type type = instance.GetType();
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (!(fieldInfo == null) && typeof(NPC).IsAssignableFrom(fieldInfo.FieldType))
					{
						object? value = fieldInfo.GetValue(instance);
						NPC val2 = (NPC)((value is NPC) ? value : null);
						if ((Object)(object)val2 != (Object)null)
						{
							return val2;
						}
					}
				}
				PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (PropertyInfo propertyInfo in properties)
				{
					if (!(propertyInfo == null) && propertyInfo.CanRead && typeof(NPC).IsAssignableFrom(propertyInfo.PropertyType))
					{
						object? value2 = propertyInfo.GetValue(instance, null);
						NPC val3 = (NPC)((value2 is NPC) ? value2 : null);
						if ((Object)(object)val3 != (Object)null)
						{
							return val3;
						}
					}
				}
			}
			catch
			{
			}
			return null;
		}

		private static bool ContainsAny(string value, params string[] needles)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				return false;
			}
			for (int i = 0; i < needles.Length; i++)
			{
				if (!string.IsNullOrWhiteSpace(needles[i]) && value.Contains(needles[i]))
				{
					return true;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(ContactsApp), "Update")]
	internal static class Patch_ContactsApp_Update_Safety
	{
		private static bool _logged;

		[HarmonyFinalizer]
		private static Exception Finalizer(Exception __exception)
		{
			if (__exception == null)
			{
				return null;
			}
			if (!_logged)
			{
				_logged = true;
				MelonLogger.Warning("[bigpimpin] CHANGE-313: ContactsApp.Update threw (suppressed once-logged, S1API populates RegionDict via deferred Start) - " + __exception.GetType().Name + ": " + __exception.Message);
			}
			return null;
		}
	}
	[HarmonyPatch]
	internal static class ContactsVanillaOnClientPatch
	{
		private static MethodBase TargetMethod()
		{
			try
			{
				Type type = AccessTools.TypeByName("S1API.Internal.Patches.ContactsAppPatches");
				return (type == null) ? null : AccessTools.Method(type, "HasCustomNpcTypes", (Type[])null, (Type[])null);
			}
			catch
			{
				return null;
			}
		}

		private static bool Prepare()
		{
			return TargetMethod() != null;
		}

		private static void Postfix(ref bool __result)
		{
			try
			{
				if (!NetworkHelper.IsHost)
				{
					__result = false;
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(QuestsLoader), "Load")]
	internal static class Patch_QuestsLoader_Load_ContractMigration
	{
		private const string LegacyProductPrefix = "bp_escort_";

		[HarmonyPrefix]
		private static void Prefix(string mainPath)
		{
			try
			{
				SanitizeQuestsJson(mainPath);
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] CHANGE-334: contract receipts migration failed (fail-open): " + ex.Message);
			}
		}

		private static void SanitizeQuestsJson(string mainPath)
		{
			if (string.IsNullOrWhiteSpace(mainPath))
			{
				return;
			}
			string text = Path.Combine(mainPath, "Quests.json");
			if (!File.Exists(text))
			{
				return;
			}
			string text2 = File.ReadAllText(text);
			if (string.IsNullOrWhiteSpace(text2) || text2.IndexOf("bp_escort_", StringComparison.Ordinal) < 0)
			{
				return;
			}
			JObject val;
			try
			{
				val = JObject.Parse(text2);
			}
			catch (Exception ex)
			{
				MelonLogger.Warning("[bigpimpin] CHANGE-334: Quests.json parse failed: " + ex.Message);
				return;
			}
			JToken obj = val["Contracts"];
			JArray val2 = (JArray)(object)((obj is JArray) ? obj : null);
			if (val2 == null || ((JContainer)val2).Count == 0)
			{
				return;
			}
			int num = 0;
			for (int num2 = ((JContainer)val2).Count - 1; num2 >= 0; num2--)
			{
				if (ContractReferencesEscortProduct(val2[num2]))
				{
					val2.RemoveAt(num2);
					num++;
				}
			}
			if (num == 0)
			{
				return;
			}
			try
			{
				string text3 = text + ".bp_tmp";
				File.WriteAllText(text3, ((JToken)val).ToString((Formatting)1, Array.Empty<JsonConverter>()));
				if (File.Exists(text))
				{
					File.Replace(text3, text, null);
				}
				else
				{
					File.Move(text3, text);
				}
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(91, 1);
				defaultInterpolatedStringHandler.AppendLiteral("[bigpimpin] CHANGE-334: stale escort contract receipts removed from Quests.json — ");
				defaultInterpolatedStringHandler.AppendFormatted(num);
				defaultInterpolatedStringHandler.AppendLiteral(" entries.");
				MelonLogger.Msg(defaultInterpolatedStringHandler.ToStringAndClear());
			}
			catch (Exception ex2)
			{
				MelonLogger.Warning("[bigpimpin] CHANGE-334: failed to write sanitized Quests.json: " + ex2.Message);
			}
		}

		private static bool ContractReferencesEscortProduct(JToken contract)
		{
			try
			{
				JToken val = ((contract != null) ? contract[(object)"ProductList"] : null);
				JToken obj = ((val != null) ? val[(object)"entries"] : null);
				JArray val2 = (JArray)(object)((obj is JArray) ? obj : null);
				if (val2 == null || ((JContainer)val2).Count == 0)
				{
					return false;
				}
				for (int i = 0; i < ((JContainer)val2).Count; i++)
				{
					JToken obj2 = val2[i];
					string text = (string)((obj2 != null) ? obj2[(object)"ProductID"] : null);
					if (!string.IsNullOrEmpty(text) && text.StartsWith("bp_escort_", StringComparison.OrdinalIgnoreCase))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Customer), "UpdateDealAttendance")]
	internal static class Patch_Customer_UpdateDealAttendance_Safety
	{
		private static bool _logged;

		[HarmonyFinalizer]
		private static Exception Finalizer(Customer __instance, Exception __exception)
		{
			if (__exception == null)
			{
				return null;
			}
			if (!_logged)
			{
				_logged = true;
				string text = null;
				try
				{
					object obj;
					if (__instance == null)
					{
						obj = null;
					}
					else
					{
						NPC nPC = __instance.NPC;
						obj = ((nPC != null) ? nPC.FullName : null);
					}
					if (obj == null)
					{
						obj = "<unknown>";
					}
					text = (string)obj;
				}
				catch
				{
					text = "<unresolvable>";
				}
				MelonLogger.Warning("[bigpimpin] CHANGE-322: Customer.UpdateDealAttendance threw (suppressed once-logged) - customer=" + text + " " + __exception.GetType().Name + ": " + __exception.Message);
			}
			return null;
		}
	}
	[HarmonyPatch(typeof(QuestsLoader), "Load")]
	internal static class Patch_QuestsLoader_Load_Safety
	{
		private static bool _logged;

		[HarmonyFinalizer]
		private static Exception Finalizer(string mainPath, Exception __exception)
		{
			if (__exception == null)
			{
				return null;
			}
			if (!_logged)
			{
				_logged = true;
				MelonLogger.Warning("[bigpimpin] CHANGE-323: QuestsLoader.Load threw (suppressed once-logged) - path='" + (mainPath ?? "<null>") + "' " + __exception.GetType().Name + ": " + __exception.Message);
			}
			return null;
		}
	}
	internal static class EscortContractPatches
	{
		private sealed class DynamicDeliveryTarget
		{
			public string Guid;

			public DeliveryLocation Location;
		}

		private sealed class PreemptiveWalkState
		{
			public EscortSlotLease Lease;

			public Vector3 MobileTarget;

			public EscortInstance Escort;
		}

		[HarmonyPatch(typeof(Customer), "OfferContractToDealer")]
		internal static class Patch_Customer_OfferContractToDealer
		{
			[HarmonyPrefix]
			private static bool Prefix(ContractInfo info, Dealer dealer)
			{
				if (!ContainsEscortProduct(info))
				{
					return true;
				}
				if (IsBigPimpinEscortDealer(dealer, info))
				{
					PrepareEscortContract(info);
					return true;
				}
				if (!_loggedDealerBlock)
				{
					_loggedDealerBlock = true;
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(Customer), "OfferContract")]
		internal static class Patch_Customer_OfferContract
		{
			[HarmonyPrefix]
			private static bool Prefix(Customer __instance, ContractInfo info)
			{
				if (!IsEscortTierUnlocked(info))
				{
					return false;
				}
				if (!IsEscortTierStocked(__instance, info))
				{
					return false;
				}
				PrepareEscortContract(info, __instance);
				return true;
			}
		}

		[HarmonyPatch(typeof(Customer), "NotifyPlayerOfContract")]
		internal static class Patch_Customer_NotifyPlayerOfContract
		{
			[HarmonyPrefix]
			private static bool Prefix(Customer __instance, ContractInfo contract)
			{
				//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				//IL_004a: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				//IL_0075: Expected O, but got Unknown
				if (!IsEscortTierUnlocked(contract))
				{
					return false;
				}
				if (!IsEscortTierStocked(__instance, contract))
				{
					return false;
				}
				PrepareEscortContract(contract, __instance);
				if (ContainsEscortProduct(contract))
				{
					EDealWindow val = ResolveCurrentDealWindow(contract);
					try
					{
						contract.DeliveryWindow = new QuestWindowConfig
						{
							IsEnabled = true,
							WindowStartTime = WindowStartHHMM(val),
							WindowEndTime = WindowEndHHMM(val)
						};
					}
					catch (Exception ex)
					{
						BPLog.TraceWarn("contract", "DeliveryWindow set failed: " + ex.Message);
					}
					Contract val2 = null;
					try
					{
						val2 = __instance.ContractAccepted(val, true, (Dealer)null);
					}
					catch (Exception ex2)
					{
						if (!_loggedAutoAcceptFailed)
						{
							_loggedAutoAcceptFailed = true;
							DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(51, 3);
							defaultInterpolatedStringHandler.AppendLiteral("ContractAccepted(");
							defaultInterpolatedStringHandler.AppendFormatted<EDealWindow>(val);
							defaultInterpolatedStringHandler.AppendLiteral(") failed ");
							defaultInterpolatedStringHandler.AppendLiteral("for escort contract (");
							object value;
							if (__instance == null)
							{
								value = null;
							}
							else
							{
								NPC nPC = __instance.NPC;
								value = ((nPC != null) ? nPC.FullName : null);
							}
							defaultInterpolatedStringHandler.AppendFormatted((string)value);
							defaultInterpolatedStringHandler.AppendLiteral("): ");
							defaultInterpolatedStringHandler.AppendFormatted(ex2.Message);
							defaultInterpolatedStringHandler.AppendLiteral(" ");
							MelonLogger.Warning(defaultInterpolatedStringHandler.ToStringAndClear() + "(further warnings suppressed)");
						}
					}
					try
					{
						__instance.SetIsAwaitingDelivery(true);
					}
					catch
					{
					}
					try
					{
						if ((Object)(object)__instance.CurrentContract == (Object)null && (Object)(object)val2 != (Object)null)
						{
							__instance.CurrentContract = val2;
						}
					}
					catch
					{
					}
					try
					{
						Contract val3 = val2 ?? __instance.CurrentContract;
						if ((Object)(object)val3 != (Object)null && ContainsEscortProduct(val3.ProductList))
						{
							StartEscortPreemptiveWalk(val3, __instance);
						}
					}
					catch (Exception ex3)
					{
						if (!_loggedPreemptiveWalkFailed)
						{
							_loggedPreemptiveWalkFailed = true;
							DefaultInterpolatedStringHandler defaultInterpolatedStringHandler2 = new DefaultInterpolatedStringHandler(51, 2);
							defaultInterpolatedStringHandler2.AppendLiteral("StartEscortPreemptiveWalk failed ");
							defaultInterpolatedStringHandler2.AppendLiteral("for customer '");
							object obj3;
							if (__instance == null)
							{
								obj3 = null;
							}
							else
							{
								NPC nPC2 = __instance.NPC;
								obj3 = ((nPC2 != null) ? nPC2.FullName : null);
							}
							if (obj3 == null)
							{
								obj3 = "?";
							}
							defaultInterpolatedStringHandler2.AppendFormatted((string)obj3);
							defaultInterpolatedStringHandler2.AppendLiteral("': ");
							defaultInterpolatedStringHandler2.AppendFormatted(ex3.Message);
							defaultInterpolatedStringHandler2.AppendLiteral(" ");
							MelonLogger.Warning(defaultInterpolatedStringHandler2.ToStringAndClear() + "(further warnings suppressed)");
						}
					}
					try
					{
						if (TryGetContractTier(contract, out var tier))
						{
							int contractHandle = 0;
							try
							{
								contractHandle = ((object)contract).GetHashCode();
							}
							catch
							{
							}
							string customerName = null;
							try
							{
								object obj5;
								if (__instance == null)
								{
									obj5 = null;
								}
								else
								{
									NPC nPC3 = __instance.NPC;
									obj5 = ((nPC3 != null) ? nPC3.FullName : null);
								}
								customerName = (string)obj5;
							}
							catch
							{
							}
							EscortWalkUpReporter.NotifyContractAccepted(tier, contractHandle, customerName);
						}
					}
					catch
					{
					}
					return false;
				}
				return true;
			}

			[HarmonyFinalizer]
			private static Exception Finalizer(ContractInfo contract, Exception __exception)
			{
				if (__exception == null)
				{
					return null;
				}
				if (contract != null && ContainsEscortProduct(contract))
				{
					if (!_loggedNotifySuppressed)
					{
						_loggedNotifySuppressed = true;
					}
					return null;
				}
				return __exception;
			}
		}

		[HarmonyPatch(typeof(Customer), "PlayContractAcceptedReaction")]
		internal static class Patch_Customer_PlayContractAcceptedReaction
		{
			[HarmonyPrefix]
			private static void Prefix(Customer __instance)
			{
				try
				{
					ContractInfo val = ((__instance != null) ? __instance.OfferedContractInfo : null);
					if (val != null && ContainsEscortProduct(val))
					{
						PrepareEscortContract(val, __instance);
					}
				}
				catch
				{
				}
			}

			[HarmonyFinalizer]
			private static Exception Finalizer(Customer __instance, Exception __exception)
			{
				if (__exception == null)
				{
					return null;
				}
				try
				{
					Contract val = ((__instance != null) ? __instance.CurrentContract : null);
					if ((Object)(object)val != (Object)null && ContainsEscortProduct(val.ProductList))
					{
						if (!_loggedReactionSwallow)
						{
							_loggedReactionSwallow = true;
						}
						return null;
					}
				}
				catch
				{
				}
				return __exception;
			}
		}

		[HarmonyPatch(typeof(Customer), "CounterOfferClicked")]
		internal static class Patch_Customer_CounterOfferClicked
		{
			[HarmonyPrefix]
			private static void Prefix(Customer __instance)
			{
				try
				{
					ContractInfo val = ((__instance != null) ? __instance.OfferedContractInfo : null);
					if (val != null && ContainsEscortProduct(val))
					{
						PrepareEscortContract(val, __instance);
						if (!_loggedCounterOfferEnabled)
						{
							_loggedCounterOfferEnabled = true;
						}
					}
				}
				catch
				{
				}
			}
		}

		[HarmonyPatch(typeof(MSGConversation), "RenderMessage")]
		internal static class Patch_MSGConversation_RenderMessage
		{
			[HarmonyFinalizer]
			private static Exception Finalizer(Exception __exception)
			{
				if (__exception == null)
				{
					return null;
				}
				if (!_loggedRenderMessageSwallow)
				{
					_loggedRenderMessageSwallow = true;
				}
				return null;
			}
		}

		[HarmonyPatch(typeof(HandoverScreen), "Open")]
		internal static class Patch_HandoverScreen_Open
		{
			[HarmonyPrefix]
			private static bool Prefix(Contract contract, Customer customer, EMode mode, Action<EHandoverOutcome, List<ItemInstance>, float> callback)
			{
				try
				{
					if ((Object)(object)contract == (Object)null)
					{
						return true;
					}
					if (!ContainsEscortProduct(contract.ProductList))
					{
						return true;
					}
					float arg = 0f;
					try
					{
						arg = contract.Payment;
					}
					catch
					{
					}
					if (callback != null)
					{
						try
						{
							List<ItemInstance> arg2 = new List<ItemInstance>();
							callback((EHandoverOutcome)1, arg2, arg);
						}
						catch (Exception ex)
						{
							MelonLogger.Warning("Patch_HandoverScreen_Open: callback invoke failed: " + ex.Message);
						}
					}
					RunEscortHandover(contract, customer);
					return false;
				}
				catch (Exception)
				{
					return true;
				}
			}
		}

		private sealed class SuppressedCustomer
		{
			public NPC Npc;

			public float Deadline;
		}

		[HarmonyPatch(typeof(NPCSignal_WalkToLocation), "WalkCallback")]
		internal static class Patch_NPCSignal_WalkToLocation_WalkCallback
		{
			private static bool _loggedOnce;

			[HarmonyFinalizer]
			private static Exception Finalizer(Exception __exception)
			{
				if (__exception == null)
				{
					return null;
				}
				if (!_loggedOnce)
				{
					_loggedOnce = true;
				}
				return null;
			}
		}

		[HarmonyPatch(typeof(ProductList), "GetCommaSeperatedString")]
		internal static class Patch_ProductList_HideEscortQuantity
		{
			[HarmonyPostfix]
			private static void Postfix(ProductList __instance, ref string __result)
			{
				try
				{
					List<Entry> list = __instance?.entries;
					if (list == null || string.IsNullOrEmpty(__result))
					{
						return;
					}
					for (int i = 0; i < list.Count; i++)
					{
						Entry val = list[i];
						if (val == null || !EscortProductRegistry.TryResolveTier(val.ProductID, out var _))
						{
							continue;
						}
						string text = null;
						try
						{
							ProductDefinition val2 = EscortProductRegistry.Get(EscortProductRegistry.ResolveTier(val.ProductID));
							if ((Object)(object)val2 != (Object)null)
							{
								text = ((BaseItemDefinition)val2).Name;
							}
						}
						catch
						{
						}
						if (!string.IsNullOrEmpty(text))
						{
							string text2 = val.Quantity + "x " + text;
							if (__result.Contains(text2))
							{
								__result = __result.Replace(text2, text);
							}
						}
					}
				}
				catch
				{
				}
			}
		}

		private static bool _loggedDealerBlock;

		private static bool _loggedLocationPatch;

		private static bool _loggedNotifySuppressed;

		private static bool _loggedPreemptiveWalkFailed;

		private static readonly Dictionary<string, DynamicDeliveryTarget> _dynamicDeliveryTargets = new Dictionary<string, DynamicDeliveryTarget>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<int, PreemptiveWalkState> _preemptiveWalkLeases = new Dictionary<int, PreemptiveWalkState>();

		private static readonly Dictionary<string, EscortSlotLease> _escortInPostHandoverWalk = new Dictionary<string, EscortSlotLease>(StringComparer.Ordinal);

		private static readonly HashSet<EscortSlotLease> _leasesHandedToFollowup = new HashSet<EscortSlotLease>();

		private static bool _loggedReactionSwallow;

		private static bool _loggedCounterOfferEnabled;

		private static bool _loggedRenderMessageSwallow;

		private static bool _loggedAutoAcceptFailed;

		private static int _pairCleanupId;

		private const float BrothelCentricEscortRadius = 1.2f;

		private const float CustomerHomeEscortRadius = 1.6f;

		private static readonly HashSet<int> _handledContracts = new HashSet<int>();

		private const float SUPPRESSED_CUSTOMER_TIMEOUT = 360f;

		private static float _watchdogTimer;

		private static readonly Dictionary<int, SuppressedCustomer> _suppressedCustomers = new Dictionary<int, SuppressedCustomer>();

		internal static void PrepareEscortContract(ContractInfo info, Customer customer = null)
		{
			ForcePimpDoorLocation(info, customer);
			EnsureEscortContractShape(info);
			try
			{
				EscortNPCRegistry.EnsureAll();
			}
			catch
			{
			}
		}

		private static bool ContainsEscortProduct(ContractInfo info)
		{
			try
			{
				List<Entry> list = info?.Products?.entries;
				if (list == null)
				{
					return false;
				}
				for (int i = 0; i < list.Count; i++)
				{
					Entry val = list[i];
					if (val != null && EscortProductRegistry.TryResolveTier(val.ProductID, out var _))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool TryGetEscortProductId(ContractInfo info, out string productId)
		{
			productId = null;
			try
			{
				List<Entry> list = info?.Products?.entries;
				if (list == null)
				{
					return false;
				}
				for (int i = 0; i < list.Count; i++)
				{
					Entry val = list[i];
					if (val != null && EscortProductRegistry.TryResolveTier(val.ProductID, out var _))
					{
						productId = val.ProductID;
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool IsBigPimpinEscortDealer(Dealer dealer, ContractInfo info)
		{
			if ((Object)(object)dealer == (Object)null || !TryGetEscortProductId(info, out var productId))
			{
				return false;
			}
			try
			{
				return (((Component)dealer).GetComponent<EscortSlotBase>() ?? ((Component)dealer).GetComponentInChildren<EscortSlotBase>(true) ?? ((Component)dealer).GetComponentInParent<EscortSlotBase>())?.CanDealDateProduct(productId) ?? false;
			}
			catch
			{
				return false;
			}
		}

		private static bool ContainsEscortProduct(ProductList list)
		{
			try
			{
				List<Entry> list2 = list?.entries;
				if (list2 == null)
				{
					return false;
				}
				for (int i = 0; i < list2.Count; i++)
				{
					Entry val = list2[i];
					if (val != null && EscortProductRegistry.TryResolveTier(val.ProductID, out var _))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		internal static bool ContainsEscortProductPublic(ProductList list)
		{
			return ContainsEscortProduct(list);
		}

		private static bool IsEscortTierUnlocked(ContractInfo info)
		{
			try
			{
				if (info == null || !ContainsEscortProduct(info))
				{
					return true;
				}
				if (!TryGetContractTier(info, out var tier))
				{
					return true;
				}
				return EscortDealerUnlocks.IsUnlocked(tier);
			}
			catch
			{
				return true;
			}
		}

		private static void ForcePimpDoorLocation(ContractInfo info, Customer customer)
		{
			if (info == null || !ContainsEscortProduct(info))
			{
				return;
			}
			string text = ResolveLocationIdForCustomer(customer);
			string guid;
			DeliveryLocation val;
			if (TryGetContractTier(info, out var tier) && UsesCustomerHomeRouting(tier) && TryGetOrCreateCustomerDeliveryTarget(customer, tier, out var target))
			{
				guid = target.Guid;
				val = target.Location;
				text = text + ":" + tier;
			}
			else
			{
				BrothelDeliveryLocations.TryEnsureAll();
				guid = BrothelDeliveryLocations.GetGuid(text);
				val = BrothelDeliveryLocations.GetInstance(text);
			}
			if (string.IsNullOrWhiteSpace(guid))
			{
				return;
			}
			if (!string.Equals(info.DeliveryLocationGUID, guid, StringComparison.OrdinalIgnoreCase))
			{
				info.DeliveryLocationGUID = guid;
			}
			try
			{
				if ((Object)(object)val != (Object)null && (Object)(object)info.DeliveryLocation == (Object)null)
				{
					info.DeliveryLocation = val;
				}
			}
			catch (Exception)
			{
			}
			try
			{
			}
			catch
			{
			}
			if (!_loggedLocationPatch)
			{
				_loggedLocationPatch = true;
			}
		}

		internal static string ResolveLocationIdForCustomer(Customer customer)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				NPC val = ((customer != null) ? customer.NPC : null);
				if ((Object)(object)val == (Object)null)
				{
					return "MidnightSuites";
				}
				return EscortLocations.GetLocationIdForRegion(val.Region);
			}
			catch
			{
				return "MidnightSuites";
			}
		}

		private static bool TryGetContractTier(ContractInfo info, out EscortTier tier)
		{
			tier = EscortTier.Street;
			try
			{
				List<Entry> list = info?.Products?.entries;
				if (list == null)
				{
					return false;
				}
				for (int i = 0; i < list.Count; i++)
				{
					Entry val = list[i];
					if (val != null && EscortProductRegistry.TryResolveTier(val.ProductID, out tier))
					{
						return true;
					}
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool IsEscortTierStocked(Customer customer, ContractInfo info)
		{
			try
			{
				if (info == null || !ContainsEscortProduct(info))
				{
					return true;
				}
				if (!TryGetContractTier(info, out var tier))
				{
					return true;
				}
				if (EscortSleepSchedule.IsSleeping(tier))
				{
					return false;
				}
				string locationId = ResolveLocationIdForCustomer(customer);
				if (!EscortStockManager.IsAvailable(locationId, tier))
				{
					return false;
				}
				EscortInstance escort = ShowroomEscorts.Get(locationId, tier);
				if (!EscortCooldownManager.CanSellNow(escort))
				{
					return false;
				}
				return true;
			}
			catch
			{
				return true;
			}
		}

		private static void EnsureEscortContractShape(ContractInfo info)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			if (info == null || !ContainsEscortProduct(info))
			{
				return;
			}
			try
			{
				if (info.Products == null)
				{
					info.Products = new ProductList();
				}
				if (info.DeliveryWindow == null)
				{
					info.DeliveryWindow = new QuestWindowConfig
					{
						IsEnabled = false,
						WindowStartTime = 0,
						WindowEndTime = 0
					};
				}
				if (info.ExpiresAfter <= 0)
				{
					info.ExpiresAfter = 600;
				}
			}
			catch (Exception)
			{
			}
		}

		internal static void RunEscortHandover(Contract contract, Customer customer)
		{
			RunEscortHandoverCore(contract, customer, suppressCashPayout: false);
		}

		internal static void RunEscortHandoverNoCash(Contract contract, Customer customer)
		{
			RunEscortHandoverCore(contract, customer, suppressCashPayout: true);
		}

		internal static bool TryGetContractTierExternal(Contract contract, out EscortTier tier)
		{
			return TryGetContractTier(contract, out tier);
		}

		internal static bool TryResolveContractDeliveryPosition(Contract contract, Customer customer, out Vector3 position)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_017c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			position = Vector3.zero;
			try
			{
				if ((Object)(object)contract == (Object)null || !ContainsEscortProduct(contract.ProductList))
				{
					return false;
				}
				if (!TryGetContractTier(contract, out var tier))
				{
					return false;
				}
				if (UsesCustomerHomeRouting(tier))
				{
					NPC val = ((customer != null) ? customer.NPC : null);
					if ((Object)(object)val != (Object)null)
					{
						string text = (string.IsNullOrWhiteSpace(val.ID) ? ((object)val).GetHashCode().ToString() : val.ID);
						string key = text + ":" + tier;
						if (_dynamicDeliveryTargets.TryGetValue(key, out var value) && (Object)(object)value?.Location != (Object)null && (Object)(object)value.Location.CustomerStandPoint != (Object)null)
						{
							position = value.Location.CustomerStandPoint.position;
							return position != Vector3.zero;
						}
						if (TryGetOrCreateCustomerDeliveryTarget(customer, tier, out var target) && (Object)(object)target?.Location != (Object)null && (Object)(object)target.Location.CustomerStandPoint != (Object)null)
						{
							position = target.Location.CustomerStandPoint.position;
							return position != Vector3.zero;
						}
					}
				}
				string locationId = ResolveLocationIdForCustomer(customer);
				position = ResolveEscortSaleTarget(customer, tier, locationId);
				return position != Vector3.zero;
			}
			catch
			{
				position = Vector3.zero;
				return false;
			}
		}

		private static void RunEscortHandoverCore(Contract contract, Customer customer, bool suppressCashPayout)
		{
			//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0308: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0365: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0276: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0317: Unknown result type (might be due to invalid IL or missing references)
			//IL_029e: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0267: Unknown result type (might be due to invalid IL or missing references)
			//IL_024f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0254: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0259: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ab: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)contract == (Object)null)
			{
				return;
			}
			int num;
			try
			{
				num = ((object)contract).GetHashCode();
			}
			catch
			{
				num = 0;
			}
			if (num != 0 && !_handledContracts.Add(num))
			{
				return;
			}
			float num2 = 0f;
			try
			{
				num2 = contract.Payment;
			}
			catch
			{
				num2 = 0f;
			}
			try
			{
				string value = null;
				try
				{
					object obj3;
					if (customer == null)
					{
						obj3 = null;
					}
					else
					{
						NPC nPC = customer.NPC;
						obj3 = ((nPC != null) ? nPC.FullName : null);
					}
					value = (string)obj3;
				}
				catch
				{
				}
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(62, 3);
				defaultInterpolatedStringHandler.AppendLiteral("RunEscortHandoverCore enter customer='");
				defaultInterpolatedStringHandler.AppendFormatted(value);
				defaultInterpolatedStringHandler.AppendLiteral("' payment=");
				defaultInterpolatedStringHandler.AppendFormatted(num2, "0");
				defaultInterpolatedStringHandler.AppendLiteral(" suppressCash=");
				defaultInterpolatedStringHandler.AppendFormatted(suppressCashPayout);
				BPLog.Trace("handover", defaultInterpolatedStringHandler.ToStringAndClear());
			}
			catch
			{
			}
			if (!suppressCashPayout && num2 > 0f && ModConfig.GetActivePayout() != ModConfig.PayoutMethod.Immediate && TryGetContractTier(contract, out var tier))
			{
				DailyPayoutManager.DispatchPayout((int)Math.Round(num2), "handover", tier);
				suppressCashPayout = true;
			}
			EscortInstance escortInstance = null;
			EscortSlotLease escortSlotLease = null;
			string text = ResolveLocationIdForCustomer(customer);
			TryGetContractTier(contract, out var tier2);
			bool flag = UsesCustomerHomeRouting(tier2);
			Vector3 val = Vector3.zero;
			bool flag2 = false;
			if (TryConsumePreemptiveWalk(contract, out var lease, out var mobileTarget, out var escort))
			{
				escortSlotLease = lease;
				val = mobileTarget;
				escortInstance = escort;
				flag2 = true;
			}
			try
			{
				object obj6;
				if (customer == null)
				{
					obj6 = null;
				}
				else
				{
					NPC nPC2 = customer.NPC;
					obj6 = ((nPC2 != null) ? nPC2.ID : null);
				}
				string customerNpcId = (string)obj6;
				if (escortInstance == null)
				{
					escortInstance = EscortContractService.GetEscortForCustomer(customerNpcId);
					if (escortInstance == null)
					{
						escortInstance = PickEscortForContract(contract, customer);
					}
				}
				if (escortInstance != null)
				{
					EscortContractService.RegisterEscortForCustomer(customerNpcId, escortInstance);
				}
				if (escortInstance != null && !flag2)
				{
					try
					{
						Vector3 val2 = ResolveEscortSaleTarget(customer, tier2, text);
						Vector3 facingTarget = val2;
						LocationDisplayDefinition def;
						if (TryGetCustomerPosition(customer, out var position))
						{
							facingTarget = position;
						}
						else if (EscortLocations.TryGetDefinition(text, out def))
						{
							facingTarget = def.DoorPosition;
						}
						if (flag)
						{
							val = val2;
							escortSlotLease = EscortLocationDisplayController.DetachLease(escortInstance);
							if (escortSlotLease == null || escortSlotLease.Released)
							{
								EscortLocationDisplayController.ReleaseEscort(escortInstance);
								Vector3 anchorPos = ResolveMobileEscortStartPosition(text, tier2);
								escortSlotLease = EscortNPCRegistry.ShowNear(escortInstance, anchorPos, val2, text);
							}
							StartMobileEscortWalk(escortSlotLease, val2);
						}
						else
						{
							val = val2;
							escortSlotLease = EscortLocationDisplayController.DetachLease(escortInstance);
							if (escortSlotLease == null || escortSlotLease.Released)
							{
								EscortLocationDisplayController.ReleaseEscort(escortInstance);
								Vector3 val3 = Vector3.zero;
								try
								{
									val3 = BrothelDoorHelper.GetApproachPoint();
								}
								catch
								{
								}
								if (val3 == Vector3.zero || val3 == val2)
								{
									escortSlotLease = EscortNPCRegistry.ShowNear(escortInstance, val2, facingTarget, text);
								}
								else
								{
									try
									{
										BrothelDoorHelper.TryOpenForNPC((EDoorSide)0);
									}
									catch
									{
									}
									escortSlotLease = EscortNPCRegistry.ShowNear(escortInstance, val3, val2, text);
									StartMobileEscortWalk(escortSlotLease, val2);
								}
							}
							else
							{
								StartMobileEscortWalk(escortSlotLease, val2);
							}
						}
					}
					catch (Exception)
					{
					}
				}
			}
			catch (Exception)
			{
			}
			if (val != Vector3.zero && escortSlotLease != null && !escortSlotLease.Released)
			{
				ScheduleMobileHandoverCompletion(customer, contract, suppressCashPayout, escortSlotLease, escortInstance, tier2, text, num2, val);
			}
			else
			{
				FinishEscortHandoverAfterVisuals(customer, contract, suppressCashPayout, escortSlotLease, escortInstance, tier2, text, num2);
			}
		}

		private static void FinishEscortHandoverAfterVisuals(Customer customer, Contract contract, bool suppressCashPayout, EscortSlotLease lease, EscortInstance escort, EscortTier contractTier, string handoverLocIdOuter, float payment)
		{
			try
			{
				PlayCustomerHandoverReaction(customer, lease);
			}
			catch
			{
			}
			try
			{
				EscortInstance escortInstance = escort;
				if (escortInstance == null)
				{
					EscortTier tier = EscortTier.Street;
					try
					{
						List<Entry> list = contract?.ProductList?.entries;
						if (list != null)
						{
							for (int i = 0; i < list.Count; i++)
							{
								Entry val = list[i];
								if (val != null && EscortProductRegistry.TryResolveTier(val.ProductID, out var tier2))
								{
									tier = tier2;
									break;
								}
							}
						}
					}
					catch
					{
					}
					escortInstance = ShowroomEscorts.Get(handoverLocIdOuter, tier);
				}
				EscortCooldownManager.MarkSale(escortInstance);
			}
			catch
			{
			}
			try
			{
				int pimpPointMultiplier = EscortStockManager.GetPimpPointMultiplier(handoverLocIdOuter, contractTier);
				if (!EscortStockManager.HasLeftPermanently(handoverLocIdOuter, contractTier))
				{
					PimpProgressionManager.AwardDatePoints(pimpPointMultiplier, contractTier);
					EscortStockManager.NotifyDateCompletedResetStreak(handoverLocIdOuter, contractTier);
				}
			}
			catch
			{
			}
			try
			{
				BlackmailManager.OnEscortDealerDateCompleted(customer, contractTier, handoverLocIdOuter, escort);
			}
			catch
			{
			}
			try
			{
				if (payment > 0f && !EscortStockManager.HasLeftPermanently(handoverLocIdOuter, contractTier))
				{
					PostDateStatusReporter.Report(contractTier, (int)Math.Round(payment), handoverLocIdOuter);
				}
			}
			catch
			{
			}
			try
			{
				object obj7;
				if (customer == null)
				{
					obj7 = null;
				}
				else
				{
					NPC nPC = customer.NPC;
					obj7 = ((nPC != null) ? nPC.DialogueHandler : null);
				}
				DialogueHandler val2 = (DialogueHandler)obj7;
				if ((Object)(object)val2 != (Object)null)
				{
					val2.EndDialogue();
				}
			}
			catch
			{
			}
			if (!UsesCustom