<?php
/**
 * Plugin bootstrap file.
 *
 * @package Live_Traffic_Analytics
 *
 * Plugin Name:     Live Traffic Analytics — Real-Time Visitor & Bot Tracking
 * Plugin URI:      https://wordpress.org/plugins/live-traffic-analytics/
 * Description:     Real-time visitor tracking, live traffic analytics, user journeys, top pages, and bot detection in one lightweight WordPress dashboard.
 * Version:         2.2.0
 * Requires PHP:    7.4
 * Author:          Bhumi
 * Text Domain:     live-traffic-analytics
 * Domain Path:     /languages
 * License:         GPLv2 or later
 * License URI:     https://www.gnu.org/licenses/gpl-2.0.html
 */

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

if ( function_exists( 'wplta_fs' ) ) {
	wplta_fs()->set_basename( true, __FILE__ );
} else {
	if ( ! function_exists( 'wplta_fs' ) ) {
		/**
		 * Create a helper function for easy SDK access.
		 *
		 * @return Freemius
		 */
		function wplta_fs() {
			global $wplta_fs;

			if ( ! isset( $wplta_fs ) ) {
				// Include Freemius SDK.
				require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';

				$wplta_fs = fs_dynamic_init(
					array(
						'id'                  => '34948',
						'slug'                => 'live-traffic-analytics',
						'type'                => 'plugin',
						'public_key'          => 'pk_bd6408e84fad5a52a5dc541a0d8a0',
						// Single-package model: there is no separate "premium" plugin zip --
						// the same package (the one on WordPress.org) unlocks Pro features at
						// runtime via a license check (see wplta_is_pro()). `is_premium` must
						// stay false, since WordPress.org's SVN pre-commit hook rejects any
						// commit where this is true (it flags the package as the paid build).
						'is_premium'          => false,
						// `has_premium_version: false` tells Freemius there is no separate
						// premium zip to download after activation -- without this, Freemius
						// shows a "Download the latest PRO version / Upload and activate it"
						// notice after every license activation, and a "Download Paid Version"
						// column on the Account page, both of which are wrong for a single-zip
						// plugin (see Freemius SDK's get_complete_upgrade_instructions()).
						'has_premium_version' => false,
						'has_addons'          => false,
						'has_paid_plans'      => true,
						'is_org_compliant'    => true,
						// Let users run the plugin without opting in, so activation is not blocking.
						'anonymous_mode'      => true,
						'menu'                => array(
							// Must match the add_menu_page() slug in WPLTA_Admin, otherwise the
							// Freemius Account/Pricing submenus attach to a non-existent parent
							// and WordPress replies "Sorry, you are not allowed to access this page".
							'slug'       => 'wplta-dashboard',
							'first-path' => 'admin.php?page=wplta-dashboard#/',
							'account'    => true,
							'pricing'    => true,
							'contact'    => false,
							'support'    => false,
						),
					)
				);

				// Do not hijack the screen with the opt-in/license page right after activation.
				$wplta_fs->add_filter( 'redirect_on_activation', '__return_false' );
			}

			return $wplta_fs;
		}

		// Init Freemius.
		wplta_fs();
		// Signal that SDK was initiated.
		do_action( 'wplta_fs_loaded' );
	}

	if ( ! function_exists( 'wplta_is_pro' ) ) {
		/**
		 * Determine whether this install has an active Pro license.
		 *
		 * @return bool
		 */
		function wplta_is_pro() {
			return function_exists( 'wplta_fs' ) && wplta_fs()->can_use_premium_code();
		}
	}

	if ( ! function_exists( 'wplta_get_license_status' ) ) {
		/**
		 * Return a summary of the current Freemius license state for the dashboard UI.
		 *
		 * @return array
		 */
		function wplta_get_license_status() {
			if ( ! function_exists( 'wplta_fs' ) ) {
				return array(
					'is_pro'        => false,
					'plan_name'     => __( 'Free', 'live-traffic-analytics' ),
					'status'        => 'free',
					'quota'         => null,
					'activated'     => 0,
					'expiration'    => '',
					'account_url'   => '',
					'upgrade_url'   => '',
					'user_name'     => '',
					'user_email'    => '',
					'user_verified' => false,
					'site_id'       => '',
					'module_id'     => '',
					'public_key'    => '',
					'secret_key'    => '',
					'sync_url'      => '',
				);
			}

			$fs      = wplta_fs();
			$is_pro  = wplta_is_pro();
			$license = $fs->_get_license();
			$plan    = $fs->get_plan();
			$user    = $fs->get_user();
			$site    = $fs->get_site();

			$status = 'free';

			if ( $is_pro ) {
				$status = $fs->is_trial() ? 'trial' : 'active';

				if ( is_object( $license ) && ! empty( $license->expiration ) ) {
					$expires_ts = strtotime( $license->expiration );

					if ( $expires_ts && $expires_ts < time() ) {
						$status = 'expired';
					}
				}
			}

			return array(
				'is_pro'        => $is_pro,
				'plan_name'     => ( $is_pro && is_object( $plan ) ) ? $plan->title : __( 'Free', 'live-traffic-analytics' ),
				'status'        => $status,
				'quota'         => is_object( $license ) ? $license->quota : null,
				'activated'     => is_object( $license ) ? (int) $license->activated : 0,
				'expiration'    => ( is_object( $license ) && ! empty( $license->expiration ) )
					? WPLTA_Helpers::format_datetime( $license->expiration )
					: '',
				'account_url'   => $fs->get_account_url(),
				'upgrade_url'   => $fs->get_upgrade_url(),
				'user_name'     => is_object( $user ) ? $user->get_name() : '',
				'user_email'    => is_object( $user ) ? $user->email : '',
				'user_verified' => is_object( $user ) && $user->is_verified(),
				'site_id'       => is_object( $site ) ? $site->id : '',
				'module_id'     => $fs->get_id(),
				'public_key'    => $fs->get_public_key(),
				'secret_key'    => $fs->get_secret_key(),
				'sync_url'      => $fs->is_registered() ? $fs->_get_sync_license_url() : '',
			);
		}
	}

	if ( ! function_exists( 'wplta_get_single_site_checkout_url' ) ) {
		/**
		 * Return a checkout deep-link for the "PRO — Single Site" plan, resolved
		 * dynamically so it keeps working if the plan/pricing IDs ever change.
		 *
		 * @return string
		 */
		function wplta_get_single_site_checkout_url() {
			if ( ! function_exists( 'wplta_fs' ) ) {
				return '';
			}

			$cache_key = 'wplta_single_site_checkout_url';
			$cached    = get_transient( $cache_key );

			if ( false !== $cached ) {
				return $cached;
			}

			$fs  = wplta_fs();
			$url = '';

			$api    = $fs->get_api_plugin_scope();
			$result = $api->get( 'pricing.json?' . http_build_query( array( 'is_enriched' => true, 'trial' => false ) ) );

			if ( ! FS_Api::is_api_error( $result ) && ! empty( $result->plans ) ) {
				foreach ( $result->plans as $remote_plan ) {
					if ( 'prosinglesite' !== $remote_plan->name || empty( $remote_plan->pricing ) ) {
						continue;
					}

					$pricing = $remote_plan->pricing[0];

					$url = $fs->_get_admin_page_url(
						'pricing',
						array(
							'checkout'      => 'true',
							'plan_id'       => $remote_plan->id,
							'plan_name'     => $remote_plan->name,
							'pricing_id'    => $pricing->id,
							'currency'      => 'usd',
							'billing_cycle' => 'annual',
						)
					);

					break;
				}
			}

			set_transient( $cache_key, $url, 12 * HOUR_IN_SECONDS );

			return $url;
		}
	}

	define( 'WPLTA_VERSION', '2.2.0' );
	define( 'WPLTA_PLUGIN_FILE', __FILE__ );
	define( 'WPLTA_PLUGIN_DIR', plugin_dir_path( WPLTA_PLUGIN_FILE ) );
	define( 'WPLTA_PLUGIN_URL', plugin_dir_url( WPLTA_PLUGIN_FILE ) );
	define( 'WPLTA_TEXT_DOMAIN', 'live-traffic-analytics' );
	define( 'WPLTA_ASSETS_URL', WPLTA_PLUGIN_URL . 'assets/' );
	define( 'WPLTA_INCLUDES_PATH', WPLTA_PLUGIN_DIR . 'includes/' );
	define( 'WPLTA_ADMIN_PATH', WPLTA_PLUGIN_DIR . 'admin/' );
	define( 'WPLTA_PUBLIC_PATH', WPLTA_PLUGIN_DIR . 'public/' );

	require_once WPLTA_INCLUDES_PATH . 'class-wplta-helpers.php';
	require_once WPLTA_INCLUDES_PATH . 'class-wplta-settings.php';
	require_once WPLTA_INCLUDES_PATH . 'class-wplta-repository.php';
	require_once WPLTA_INCLUDES_PATH . 'class-wplta-activator.php';
	require_once WPLTA_PUBLIC_PATH . 'class-wplta-public.php';
	require_once WPLTA_ADMIN_PATH . 'class-wplta-admin.php';
	require_once WPLTA_ADMIN_PATH . 'class-wplta-admin-rest.php';

	WPLTA_Activator::maybe_upgrade();

	/**
	 * Boot the plugin.
	 *
	 * @return void
	 */
	function wplta_boot_plugin() {
		WPLTA_Public::get_instance();
		WPLTA_Admin::get_instance();
		WPLTA_Admin_REST::get_instance();
	}
	add_action( 'plugins_loaded', 'wplta_boot_plugin' );

	register_activation_hook( WPLTA_PLUGIN_FILE, array( 'WPLTA_Activator', 'activate' ) );
}
