<?php
/*
Plugin Name: 247ChatMate
Plugin URI: https://247chatmate.com
Description: Intent-first WhatsApp chat widget with guided prompts for faster lead capture.
Version: 1.1.55
Requires PHP: 7.4
Author: 247TradeMate
Author URI: https://247trademate.pro
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: 247chatmate
*/

defined( 'ABSPATH' ) || exit;

/* ======================================================================
   CORE CONSTANTS (GUARDED)
====================================================================== */

if ( ! defined( 'MATEWA_MAIN_FILE' ) ) {
	define( 'MATEWA_MAIN_FILE', __FILE__ );
}

if ( ! defined( 'MATEWA_VERSION' ) ) {
	define( 'MATEWA_VERSION', '1.1.55' );
}

if ( ! defined( 'MATEWA_PLUGIN_DIR' ) ) {
	define( 'MATEWA_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}

if ( ! defined( 'MATEWA_PLUGIN_URL' ) ) {
	define( 'MATEWA_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}



if ( ! defined( 'MATEWA_SINGLE_MONTHLY_CHECKOUT_URL' ) ) {
	define( 'MATEWA_SINGLE_MONTHLY_CHECKOUT_URL', 'https://247chatmate.lemonsqueezy.com/checkout/buy/654461de-2eae-4715-a249-a2ac7e032678' );
}

if ( ! defined( 'MATEWA_SINGLE_ANNUAL_CHECKOUT_URL' ) ) {
	define( 'MATEWA_SINGLE_ANNUAL_CHECKOUT_URL', 'https://247chatmate.lemonsqueezy.com/checkout/buy/9d97aef1-740e-49bc-890b-dae019933ead' );
}

if ( ! defined( 'MATEWA_PRO_TRIAL_REGISTRY_ENDPOINT' ) ) {
	define( 'MATEWA_PRO_TRIAL_REGISTRY_ENDPOINT', 'https://247trademate.pro/247chatmate/pro-trial-registry.php' );
}

if ( ! defined( 'MATEWA_PRO_TRIAL_REGISTRY_SECRET' ) ) {
	define( 'MATEWA_PRO_TRIAL_REGISTRY_SECRET', '' );
}

if ( ! defined( 'MATEWA_FOUNDER_BETA_REGISTRY_ENDPOINT' ) ) {
	define( 'MATEWA_FOUNDER_BETA_REGISTRY_ENDPOINT', 'https://247trademate.pro/247chatmate/founder-beta-registry.php' );
}

if ( ! defined( 'MATEWA_AGENCY_REGISTRY_ENDPOINT' ) ) {
	define( 'MATEWA_AGENCY_REGISTRY_ENDPOINT', 'https://247trademate.pro/wp-json/cmcd/v1/agency-code/validate' );
}

/* ======================================================================
   WIDGET VERSION OWNERSHIP
====================================================================== */

if ( ! defined( 'MATEWA_WIDGET_V2' ) ) {
	define( 'MATEWA_WIDGET_V2', true );
}

/* ======================================================================
   MODE CONSTANTS
====================================================================== */

if ( ! defined( 'MATEWA_MODE_FREE' ) ) {
	define( 'MATEWA_MODE_FREE', 'free' );
}

if ( ! defined( 'MATEWA_MODE_TRIAL' ) ) {
	define( 'MATEWA_MODE_TRIAL', 'trial_active' );
}

if ( ! defined( 'MATEWA_MODE_TRIAL_EXPIRED' ) ) {
	define( 'MATEWA_MODE_TRIAL_EXPIRED', 'trial_expired' );
}

if ( ! defined( 'MATEWA_MODE_PRO' ) ) {
	define( 'MATEWA_MODE_PRO', 'pro' );
}

if ( ! defined( 'MATEWA_MODE_MASTER' ) ) {
	define( 'MATEWA_MODE_MASTER', 'master' );
}

/* ======================================================================
   SAFE FILE LOADER
====================================================================== */

function matewa_safe_require( $relative_path ) {
	$matewa_file = MATEWA_PLUGIN_DIR . ltrim( $relative_path, '/' );

	if ( is_readable( $matewa_file ) ) {
		require_once $matewa_file;
	}
}

/* ======================================================================
   LOAD CORE MODULES (ORDER MATTERS)
====================================================================== */

matewa_safe_require( 'includes/helpers.php' );
matewa_safe_require( 'includes/remote-updater.php' );
matewa_safe_require( 'includes/pro-trial-registry.php' );
matewa_safe_require( 'includes/founder-beta.php' );
matewa_safe_require( 'includes/agency-registry-client.php' );
matewa_safe_require( 'includes/agency-entitlement.php' );
matewa_safe_require( 'includes/licensing.php' );
matewa_safe_require( 'includes/agency-bundle-licences.php' );
matewa_safe_require( 'includes/agency-client-packs.php' );
matewa_safe_require( 'includes/agency-client-pdf-upload.php' );
matewa_safe_require( 'includes/agency-client-import.php' );
matewa_safe_require( 'includes/agency-client-setup-key.php' );
matewa_safe_require( 'includes/agency-client-remote-push.php' );
matewa_safe_require( 'includes/agency-client-remote-push-test.php' );
matewa_safe_require( 'includes/paid-licence-registry.php' );
matewa_safe_require( 'includes/lead-history.php' );
matewa_safe_require( 'includes/email-profiles.php' );
matewa_safe_require( 'includes/email-delivery.php' );
matewa_safe_require( 'includes/client-mail-delivery-options.php' );
matewa_safe_require( 'includes/managed-mail-relay.php' );
matewa_safe_require( 'includes/fallback-mail-delivery.php' );
matewa_safe_require( 'includes/pro-lead-routing.php' );
matewa_safe_require( 'includes/weekly-lead-summary.php' );
matewa_safe_require( 'includes/i18n.php' );
matewa_safe_require( 'includes/verticals.php' );
matewa_safe_require( 'includes/platform-services-compat.php' );

/* ======================================================================
   REPO-SAFE MODE RESOLUTION
====================================================================== */

add_action(
	'plugins_loaded',
	function () {
		$matewa_status = MATEWA_MODE_FREE;

		$matewa_defer_status = false;

		if ( is_admin() ) {
			$matewa_option_page = isset( $_POST['option_page'] ) ? sanitize_key( wp_unslash( $_POST['option_page'] ) ) : '';
			$matewa_defer_status = ( 'matewa_settings' === $matewa_option_page ) || ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() );
		}

		if ( ! $matewa_defer_status && function_exists( 'matewa_license_status' ) ) {
			$matewa_status = matewa_license_status();
		}

		$matewa_status = apply_filters( 'matewa_force_license_mode', $matewa_status );

		$valid_statuses = array(
			MATEWA_MODE_FREE,
			MATEWA_MODE_TRIAL,
			MATEWA_MODE_TRIAL_EXPIRED,
			MATEWA_MODE_PRO,
			MATEWA_MODE_MASTER,
		);

		if ( ! in_array( $matewa_status, $valid_statuses, true ) ) {
			$matewa_status = MATEWA_MODE_FREE;
		}

		if ( ! defined( 'MATEWA_CURRENT_STATUS' ) ) {
			define( 'MATEWA_CURRENT_STATUS', $matewa_status );
			define( 'MATEWA_IS_PRO', in_array( $matewa_status, array( MATEWA_MODE_PRO, MATEWA_MODE_MASTER ), true ) );
			define( 'MATEWA_IS_MASTER', MATEWA_MODE_MASTER === $matewa_status );
			define( 'MATEWA_IS_TRIAL', MATEWA_MODE_TRIAL === $matewa_status );
		}
	}
);

/* ======================================================================
   BUILDER-SAFE MODE
====================================================================== */

add_filter(
	'matewa_force_license_mode',
	function ( $mode ) {
		if ( function_exists( 'matewa_builder_active' ) && matewa_builder_active() ) {
			return MATEWA_MODE_FREE;
		}

		return $mode;
	}
);

/* ======================================================================
   MODE ACCESSOR
====================================================================== */

if ( ! function_exists( 'matewa_get_mode' ) ) {
	function matewa_get_mode() {
		$mode = defined( 'MATEWA_CURRENT_STATUS' )
			? MATEWA_CURRENT_STATUS
			: MATEWA_MODE_FREE;

		// AGENCYCLIENTFREEMIUMOVERRIDEFIX1:
		// Client sites imported through the one-time agency setup route must
		// resolve as Pro-style/agency-managed even when no LemonSqueezy key is
		// present. This keeps the frontend widget, dashboard and Visitor Buttons
		// in sync after a remote setup push without exporting an agency master key.
		if ( function_exists( 'matewa_agency_client_entitlement_is_active' ) && matewa_agency_client_entitlement_is_active() ) {
			return MATEWA_MODE_PRO;
		}

		return $mode;
	}
}

/* ======================================================================
   ADMIN LOAD
====================================================================== */

if ( is_admin() ) {
	matewa_safe_require( 'includes/paid-lifecycle-readonly.php' );
	matewa_safe_require( 'includes/test-reset.php' );
	matewa_safe_require( 'admin/helpers.php' );
	matewa_safe_require( 'admin/settings-ui.php' );

	add_action(
		'admin_menu',
		function () {
			add_menu_page(
				'247ChatMate',
				'247ChatMate',
				'manage_options',
				'247chatmate',
				'matewa_render_settings_page',
				'dashicons-format-chat',
				58
			);

			add_submenu_page(
				'247chatmate',
				'Settings',
				'Settings',
				'manage_options',
				'247chatmate',
				'matewa_render_settings_page'
			);
		}
	);

	function matewa_render_settings_page() {
		if ( function_exists( 'matewa_render_settings_ui' ) ) {
			matewa_render_settings_ui();
		}
	}
}


/* ======================================================================
   FRONTEND DISPLAY RULES
====================================================================== */

if ( ! function_exists( 'matewa_normalise_widget_display_mode' ) ) {
	function matewa_normalise_widget_display_mode( $mode ) {
		$mode = is_string( $mode ) ? sanitize_key( $mode ) : 'all';
		$allowed_modes = array( 'all', 'homepage', 'selected', 'excluded' );

		return in_array( $mode, $allowed_modes, true ) ? $mode : 'all';
	}
}

if ( ! function_exists( 'matewa_normalise_widget_page_ids' ) ) {
	function matewa_normalise_widget_page_ids( $page_ids ) {
		if ( is_string( $page_ids ) ) {
			$page_ids = preg_split( '/[\s,]+/', $page_ids );
		}

		if ( ! is_array( $page_ids ) ) {
			return array();
		}

		$page_ids = array_map( 'absint', $page_ids );
		$page_ids = array_filter( $page_ids );
		$page_ids = array_values( array_unique( $page_ids ) );

		return $page_ids;
	}
}

if ( ! function_exists( 'matewa_should_render_widget' ) ) {
	function matewa_should_render_widget() {
		if ( is_admin() ) {
			return false;
		}

		if ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) {
			return false;
		}

		if ( function_exists( 'wp_is_json_request' ) && wp_is_json_request() ) {
			return false;
		}

		if ( is_feed() || is_robots() || is_trackback() ) {
			return false;
		}

		$settings = get_option( 'matewa_widget_settings', array( 'enabled' => '1' ) );
		$settings = is_array( $settings ) ? $settings : array();

		if ( (string) ( $settings['enabled'] ?? '1' ) !== '1' ) {
			return false;
		}

		/*
		 * FRONTENDDISPLAYGATEFIX1
		 * The admin UI stores Homepage separately as include_homepage.
		 * The frontend gate must honour that flag before blocking the render.
		 * Free / expired states also fall back to a safe sitewide widget; the
		 * renderer then limits the visible chips to the free fallback set.
		 */
		$mode = function_exists( 'matewa_get_mode' ) ? matewa_get_mode() : MATEWA_MODE_FREE;

		if ( in_array( $mode, array( MATEWA_MODE_FREE, MATEWA_MODE_TRIAL_EXPIRED ), true ) ) {
			return true;
		}

		$display_mode     = matewa_normalise_widget_display_mode( $settings['display_mode'] ?? 'all' );
		$page_ids         = matewa_normalise_widget_page_ids( $settings['page_ids'] ?? array() );
		$include_homepage = ( (string) ( $settings['include_homepage'] ?? '0' ) === '1' );
		$is_home_request  = is_front_page() || is_home();

		if ( 'homepage' === $display_mode ) {
			return $is_home_request;
		}

		if ( in_array( $display_mode, array( 'selected', 'excluded' ), true ) ) {
			$is_listed = false;

			if ( $is_home_request && $include_homepage ) {
				$is_listed = true;
			}

			$current_ids = array();
			$current_id  = absint( get_queried_object_id() );

			if ( $current_id > 0 ) {
				$current_ids[] = $current_id;
			}

			if ( $is_home_request ) {
				$front_page_id = absint( get_option( 'page_on_front' ) );
				$posts_page_id = absint( get_option( 'page_for_posts' ) );

				if ( $front_page_id > 0 ) {
					$current_ids[] = $front_page_id;
				}

				if ( $posts_page_id > 0 ) {
					$current_ids[] = $posts_page_id;
				}
			}

			$current_ids = array_values( array_unique( array_filter( array_map( 'absint', $current_ids ) ) ) );

			foreach ( $current_ids as $maybe_current_id ) {
				if ( in_array( $maybe_current_id, $page_ids, true ) ) {
					$is_listed = true;
					break;
				}
			}

			if ( ! $is_listed && ! empty( $page_ids ) && ! empty( $_SERVER['REQUEST_URI'] ) ) {
				$current_path = wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH );
				$current_path = '/' . ltrim( (string) $current_path, '/' );
				$current_path = untrailingslashit( $current_path );

				foreach ( $page_ids as $page_id ) {
					$page_url  = get_permalink( $page_id );
					$page_path = $page_url ? wp_parse_url( $page_url, PHP_URL_PATH ) : '';
					$page_path = '/' . ltrim( (string) $page_path, '/' );
					$page_path = untrailingslashit( $page_path );

					if ( '' !== $page_path && $current_path === $page_path ) {
						$is_listed = true;
						break;
					}
				}
			}

			if ( 'selected' === $display_mode ) {
				return $is_listed;
			}

			return ! $is_listed;
		}

		return true;
	}
}

/* ======================================================================
   FRONTEND LOAD
====================================================================== */

add_action(
	'wp_enqueue_scripts',
	function () {
		if ( function_exists( 'matewa_should_render_widget' ) && ! matewa_should_render_widget() ) {
			return;
		}

		require_once MATEWA_PLUGIN_DIR . 'public/matewa-assets.php';
	},
	20
);