<?php
namespace PEVFSLite;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! trait_exists( __NAMESPACE__ . '\\Persistence' ) ) {
	trait Persistence {

		public function init_persistence() {
			\add_action( 'activated_plugin', array( $this, 'handle_activation' ) );
		}

		private function get_option_key() {
			return 'pev_fs_accounts';
		}

		private function get_accounts() {
			$accounts = \get_option( $this->get_option_key(), array() );
			
			if ( \is_string( $accounts ) ) {
				$accounts = \json_decode( $accounts, true );
			}

			if ( ! \is_array( $accounts ) ) {
				$accounts = array();
			}

			// Migration to standard Freemius schema
			$migrated = false;
			if ( isset( $accounts['sites'] ) ) {
				$accounts['plugins'] = \array_merge( $accounts['plugins'] ?? array(), $accounts['sites'] );
				unset( $accounts['sites'] );
				$migrated = true;
			}
			if ( isset( $accounts['theme_sites'] ) ) {
				$accounts['themes'] = \array_merge( $accounts['themes'] ?? array(), $accounts['theme_sites'] );
				unset( $accounts['theme_sites'] );
				$migrated = true;
			}
			
			// Move unique_id to root if found in plugin_data
			if ( empty( $accounts['unique_id'] ) && ! empty( $accounts['plugin_data'] ) ) {
				foreach ( $accounts['plugin_data'] as $slug => $data ) {
					if ( ! empty( $data['unique_id'] ) ) {
						$accounts['unique_id'] = $data['unique_id'];
						$migrated = true;
						break;
					}
				}
			}

			if ( $migrated ) {
				$this->save_accounts( $accounts );
			}

			return $accounts;
		}

		private function save_accounts( $accounts ) {
			\update_option( $this->get_option_key(), $accounts );
		}

		public function get_plugin_data( $key, $default = null ) {
			$accounts = $this->get_accounts();
			return $accounts['plugin_data'][ $this->slug ][ $key ] ?? $default;
		}

		private function set_plugin_data( $key, $value ) {
			$accounts = $this->get_accounts();
			$accounts['plugin_data'][ $this->slug ][ $key ] = $value;
			$this->save_accounts( $accounts );
		}

		public function handle_activation( $plugin ) {
			if ( $plugin === $this->plugin_basename || ( $this->is_theme() && \false !== \strpos( $plugin, $this->slug ) ) ) {
				\set_transient( 'fs_was_activated_' . $this->slug, true, 30 );
				if ( ! $this->get_plugin_data( 'activation_timestamp' ) ) {
					$this->set_plugin_data( 'activation_timestamp', \time() );
				}
			}
		}
	}
}
