<?php
/**
 * Plugin Name:       CareHQ Connector
 * Plugin URI:        https://formconnector.co.uk
 * Description:       Integrates WordPress forms (Forminator, Gravity Forms, FluentForms, WPForms, Contact Form 7) with CareHQ CRM, providing settings for API credentials and field/location mapping.
 * Version:           3.6.0
 * Author:            Victory Digital
 * Author URI:        https://victory.digital
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Update URI:        https://app.formconnector.co.uk/carehq-connector
 * Text Domain:       carehq-connector
 * Domain Path:       /languages
 *
 * @link              https://formconnector.co.uk
 * @since             3.1.2
 * @package           CareHQConnector
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Plugin constants.
 * Using FC_ prefix to avoid conflicts with other plugins.
 */
define( 'FC_VERSION', '3.6.0' );
define( 'FC_PLUGIN_FILE', __FILE__ );
define( 'FC_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
define( 'FC_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'FC_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
define( 'FC_SETTINGS_SLUG', 'CareHQConnector' );

// License Constants
define( 'FC_LICENSE_API_ENDPOINT', 'https://app.formconnector.co.uk' );
define( 'FC_LICENSE_OPTION_KEY', 'fc_license_key' );
define( 'FC_LICENSE_DATA_OPTION', 'fc_license_data' );
define( 'FC_LICENSE_DATA_TRANSIENT', 'fc_license_data_transient' );
define( 'FC_LICENSE_CHECK_INTERVAL', 'daily' );
define( 'FC_LICENSE_CRON_HOOK', 'fc_daily_license_check' );
define( 'FC_UPDATE_CHECK_ENDPOINT', 'https://app.formconnector.co.uk/api/plugin/update-check' );

/**
 * Composer Autoload
 */
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
	require_once __DIR__ . '/vendor/autoload.php';
}

// Global helper files (plain functions, not classes — so not covered by
// the PSR-4 autoloader). Everything else under inc/ is autoloaded on demand.
require_once __DIR__ . '/inc/Core/Admin/admin.php';
require_once __DIR__ . '/inc/Core/Utils/Debug.php';

// Bootstrap the plugin
\FormConnector\Core\Admin\bootstrap();
\FormConnector\Core\Admin\MenuBadge::register();

// Register REST API routes
\FormConnector\API\RestAPI::register();

// Register retry queue cron
add_filter('cron_schedules', ['\FormConnector\Features\Retry\RetryQueue', 'add_cron_interval']);
\FormConnector\Features\Retry\RetryQueue::get_instance()->register_cron();

// Register daily logs retention cleanup
\FormConnector\Features\Logs\RetentionCron::register();

// Register GDPR personal data exporter + eraser
\FormConnector\Core\Privacy\Privacy::register();

// Register email notification hooks
\FormConnector\Features\Notifications\EmailNotifier::get_instance()->register_hooks();

// Register CareHQ two-way integration: webhook receiver + scheduled health pings.
\FormConnector\Integration\Webhook\WebhookHandler::register_hooks();
\FormConnector\Integration\Health\HealthPing::register_hooks();
\FormConnector\Core\Updater\PluginUpdater::register();

/**
 * Plugin activation hook
 * 
 * Runs when the plugin is activated via WordPress admin.
 * Creates database tables, sets default options, schedules events.
 */
register_activation_hook(__FILE__, function() {
	\FormConnector\Core\Setup\Activator::activate();
});

/**
 * Plugin deactivation hook
 * 
 * Runs when the plugin is deactivated via WordPress admin.
 * Cleans up cron jobs and transients but preserves user data.
 */
register_deactivation_hook(__FILE__, function() {
	\FormConnector\Core\Setup\Deactivator::deactivate();
});

/**
 * Ensure upgrades run even if activation hook didn't fire
 * 
 * This catches cases where plugin files are updated via FTP
 * or other methods that bypass the activation hook.
 */
add_action('admin_init', function() {
	\FormConnector\Core\Setup\Activator::maybe_upgrade();
});

/**
 * Show admin notice when CareHQ reports a plugin update is available.
 */
add_action('admin_notices', function() {
	if (!current_user_can('manage_options')) {
		return;
	}

	$update = get_option(\FormConnector\Integration\CareHQ\Signing::OPTION_PLUGIN_UPDATE, null);
	if (!is_array($update) || empty($update['updateAvailable'])) {
		return;
	}

	$is_required = !empty($update['updateRequired']);
	$current = $update['current'] ?? (defined('FC_VERSION') ? FC_VERSION : 'unknown');
	$latest = $update['latest'] ?? '';
	$minimum = $update['minimum'] ?? '';
	$plugin_url = admin_url('plugins.php');
	?>
	<div class="notice <?php echo $is_required ? 'notice-error' : 'notice-warning is-dismissible'; ?>">
		<p>
			<strong>CareHQ Connector:</strong>
			<?php if ($is_required) : ?>
				This plugin version is no longer supported.
			<?php else : ?>
				A newer plugin version is available.
			<?php endif; ?>
			You are running <?php echo esc_html($current); ?><?php echo $latest ? ', latest is ' . esc_html($latest) : ''; ?><?php echo $minimum ? ', minimum supported is ' . esc_html($minimum) : ''; ?>.
			<a href="<?php echo esc_url($plugin_url); ?>">Review plugins</a>.
		</p>
	</div>
	<?php
});

/**
 * Clear stale CareHQ plugin-version state after this plugin is updated.
 */
add_action('upgrader_process_complete', function($upgrader, $hook_extra) {
	if (
		empty($hook_extra['action']) ||
		empty($hook_extra['type']) ||
		empty($hook_extra['plugins']) ||
		$hook_extra['action'] !== 'update' ||
		$hook_extra['type'] !== 'plugin' ||
		!in_array(FC_PLUGIN_BASENAME, (array) $hook_extra['plugins'], true)
	) {
		return;
	}

	delete_option(\FormConnector\Integration\CareHQ\Signing::OPTION_PLUGIN_UPDATE);
	\FormConnector\Integration\Health\HealthPing::send_scheduled_ping();
}, 10, 2);

/**
 * Show admin notice when homes exceed seat limit
 */
add_action('admin_notices', function() {
	// Use the Homes class which already has seat-limit logic
	$homes_manager = new \FormConnector\Features\Homes\Homes();
	$seat_info = $homes_manager->get_active_home_ids();

	// Skip if no finite seat limit is configured, seats are unlimited, or the site is within limit.
	if ($seat_info['total_seats'] === null || !empty($seat_info['is_unlimited']) || !$seat_info['is_over_limit']) {
		return;
	}

	$total_seats = $seat_info['total_seats'];
	$used_seats = $seat_info['used_seats'];
	$over_count = $seat_info['over_limit_count'];
	$settings_url = admin_url('admin.php?page=form-connector#homes');
	?>
	<div class="notice notice-warning is-dismissible">
		<p>
			<strong>CareHQ Connector:</strong>
			You have <?php echo esc_html($used_seats); ?> homes registered but only
			<?php echo esc_html($total_seats); ?> paid seat<?php echo $total_seats !== 1 ? 's' : ''; ?>.
			<strong><?php echo esc_html($over_count); ?> home<?php echo $over_count !== 1 ? 's are' : ' is'; ?>
			not receiving submissions.</strong>
			<a href="<?php echo esc_url($settings_url); ?>">Manage homes</a> or upgrade your plan.
		</p>
	</div>
	<?php
});

/**
 * Register log cleanup cron handler
 */
add_action('fc_daily_log_cleanup', function() {
	$settings = \FormConnector\Core\Settings\Settings::get_instance();
	$retention_days = $settings->get('log_retention_days', 90);
	
	if ($retention_days > 0) {
		\FormConnector\Features\Logs\Logs::get_instance()->delete_old_logs($retention_days);
	}
});

// Initialize form submission handlers (frontend)
add_action('init', function() {
	\FormConnector\Integration\Forms\SubmissionHandler::get_instance()->init();
}, 20);

// Initialize UTM tracking (frontend)
add_action('init', function() {
	\FormConnector\Features\UTM\UTMTracker::get_instance()->init();
}, 10);
