<?php
/**
 * Plugin Name: Final POS - Drag & Drop Point of Sale Builder
 * Description: Pair your WooCommerce store with FinalPOS
 * Author: FinalPOS
 * Author URI: https://finalpos.com
 * version: 1.3.9
 * License: GPLv2 or later
 * License URI: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Requires at least: 6.5
 * Tested up to: 6.8.3
 * Requires PHP: 7.4
 * Requires Plugins: woocommerce
 * WC requires at least: 9.4
 *
 * @package FinalPOS
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	die( 'Direct access is not allowed.' );
}

// Define plugin constants.
define( 'FINALPOS_VERSION', '1.3.9' );
define( 'FINALPOS_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'FINALPOS_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'FINALPOS_API_BASE_URL', 'https://services.finalpos.com' );

// Load constants file first.
require_once __DIR__ . '/includes/constants.php';

require_once __DIR__ . '/includes/ajax/save-wc-token.php';
require_once __DIR__ . '/includes/ajax/wc-api-handler.php';
require_once __DIR__ . '/includes/admin/dashboard/class-finalpos-dashboard.php';
require_once __DIR__ . '/includes/admin/wizard/class-finalpos-wizard.php';
require_once __DIR__ . '/includes/admin/class-finalpos-admin-assets.php';
require_once __DIR__ . '/includes/common-functions.php';
require_once __DIR__ . '/includes/lifecycle.php';

// Initialize the wizard.
FinalPOS_Wizard::init();


/**
 * Display admin notice for incomplete wizard setup
 */
function finalpos_incomplete_wizard_notice(): void {
	// Only show to users who can manage options.
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	// Check if wizard is complete.
	$current_stage = get_option( FINALPOS_OPTION_CURRENT_STAGE, FINALPOS_STAGE_AUTH_KEY );
	$current_page  = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';

	if ( FINALPOS_STAGE_COMPLETE !== $current_stage && FINALPOS_PAGE_SETUP !== $current_page ) {
		?>
		<div class="notice notice-warning is-dismissible">
			<p>
				<?php
				echo wp_kses_post(
					sprintf(
						/* translators: %s: Setup wizard URL */
						__( '<strong>Final POS:</strong> Your setup is not complete. Please <a href="%s">complete the setup wizard</a> to fully connect with Final POS.', 'finalpos' ),
						esc_url( admin_url( 'admin.php?page=' . FINALPOS_PAGE_SETUP ) )
					)
				);
				?>
			</p>
		</div>
		<?php
	}
}
add_action( 'admin_notices', 'finalpos_incomplete_wizard_notice', 99 );

/**
 * Main FinalPOS Plugin Class
 */
class FinalPOS_Plugin {



	/**
	 * Class constructor.
	 */
	public function __construct() {

		// TODO: Need extra verification for woocommerce dependencies

		add_action( 'init', array( $this, 'init' ) );

		add_action( 'plugins_loaded', array( $this, 'init_woocommerce' ), 20 );

		// this only fires when WooCommerce is active.
		add_action( 'woocommerce_loaded', array( $this, 'load_woocommerce_integrations' ) );

		register_activation_hook( __FILE__, array( 'FinalPOS_Lifecycle', 'activate' ) );
		register_activation_hook( __FILE__, array( 'FinalPOS_Lifecycle', 'reactivate' ) );
		register_deactivation_hook( __FILE__, array( 'FinalPOS_Lifecycle', 'deactivate' ) );
	}

	/**
	 * Check if WooCommerce is active
	 *
	 * @return bool
	 */
	public function is_woocommerce_active(): bool {
		return in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true );
	}

	/**
	 * Initialize basic WooCommerce integrations.
	 *
	 * @return void
	 */
	public function init_woocommerce(): void {
		if ( ! $this->is_woocommerce_active() ) {
			return;
		}

		require_once __DIR__ . '/integrations/readonly-orders.php';
		require_once __DIR__ . '/integrations/refund-restock.php';
	}

	/**
	 * Load WooCommerce integrations after WooCommerce is fully loaded.
	 *
	 * @return void
	 */
	public function load_woocommerce_integrations(): void {
		if ( ! class_exists( 'Automattic\WooCommerce\Internal\RestApiControllerBase' ) ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'FinalPOS: RestApiControllerBase class not found. WooCommerce may need to be updated.' );
			}
			return;
		}
		require_once __DIR__ . '/integrations/readonly-orders.php';
		require_once __DIR__ . '/integrations/refund-restock.php';
		require_once __DIR__ . '/includes/api/class-finalpos-stock-api.php';

		// Initialize REST API endpoints only if class was successfully loaded.
		if ( class_exists( 'FinalPOS_Stock_API' ) ) {
			FinalPOS_Stock_API::init();
		}
	}

	/**
	 * Plugin initialization
	 */
	public function init(): void {
		if ( ! $this->is_woocommerce_active() ) {
			add_action( 'admin_notices', array( $this, 'woocommerce_required_notice' ) );
			return;
		}

		add_action( 'admin_menu', array( $this, 'admin_menu' ) );

		FinalPOS_Lifecycle::get_instance();

		FinalPOS_Dashboard::init();

		// Register AJAX actions.
		add_action( 'wp_ajax_finalpos_check_sync_status', array( 'FinalPOS_Dashboard', 'check_sync_status' ) );

		// Register webhook failure threshold filter.
		add_filter(
			'woocommerce_max_webhook_delivery_failures',
			function () {
				return FINALPOS_WEBHOOK_MAX_FAILURES;
			}
		);

		// Redirect to wizard on initial activation.
		if ( get_transient( FINALPOS_TRANSIENT_ACTIVATION_REDIRECT ) ) {
			delete_transient( FINALPOS_TRANSIENT_ACTIVATION_REDIRECT );
			if ( ! isset( $_GET['activate-multi'] ) ) {
				// Only redirect if the setup is not complete.
				if ( FINALPOS_STAGE_COMPLETE !== get_option( FINALPOS_OPTION_CURRENT_STAGE ) ) {
					wp_safe_redirect( admin_url( 'admin.php?page=' . FINALPOS_PAGE_SETUP ) );
					exit;
				}
			}
		}

		// Initialize assets.
		FinalPOS_Admin_Assets::init();
	}

	/**
	 * Display admin notice if WooCommerce is not installed or activated
	 */
	public function woocommerce_required_notice() {
		?>
		<div class="notice notice-error">
			<p>
				<?php echo esc_html__( '<strong>Final POS</strong> requires WooCommerce to be installed and activated. Please install and activate WooCommerce to use this plugin.', 'finalpos' ); ?>
			</p>
			<?php if ( current_user_can( 'install_plugins' ) ) : ?>
				<p>
					<a href="<?php echo esc_url( wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=woocommerce' ), 'install-plugin_woocommerce' ) ); ?>"
						class="button button-primary">
						<?php echo esc_html__( 'Install WooCommerce', 'finalpos' ); ?>
					</a>
					<?php if ( file_exists( WP_PLUGIN_DIR . '/woocommerce/woocommerce.php' ) ) : ?>
						<a href="<?php echo esc_url( wp_nonce_url( self_admin_url( 'plugins.php?action=activate&plugin=woocommerce/woocommerce.php' ), 'activate-plugin_woocommerce/woocommerce.php' ) ); ?>"
							class="button button-secondary">
							<?php echo esc_html__( 'Activate WooCommerce', 'finalpos' ); ?>
						</a>
					<?php endif; ?>
				</p>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Create admin menu
	 */
	public function admin_menu() {
		$icon_url = plugins_url( 'assets/img/finalpos-icon.svg', __FILE__ );

		add_menu_page(
			__( 'Final POS', 'finalpos' ),
			__( 'Final POS', 'finalpos' ),
			'manage_options',
			FINALPOS_PAGE_DASHBOARD,
			array( $this, 'render_page' ),
			$icon_url,
			30
		);

		// Dashboard sub-menu item (renames the auto-created duplicate of the top-level entry).
		add_submenu_page(
			FINALPOS_PAGE_DASHBOARD,
			__( 'Dashboard', 'finalpos' ),
			__( 'Dashboard', 'finalpos' ),
			'manage_options',
			FINALPOS_PAGE_DASHBOARD,
			array( $this, 'render_page' )
		);

		// Logs sub-menu item.
		add_submenu_page(
			FINALPOS_PAGE_DASHBOARD,
			__( 'Logs', 'finalpos' ),
			__( 'Logs', 'finalpos' ),
			'manage_options',
			FINALPOS_PAGE_LOGS,
			array( $this, 'render_logs_page' )
		);

		// Add hidden setup page.
		add_submenu_page(
			null,
			__( 'Final POS Setup', 'finalpos' ),
			__( 'Setup', 'finalpos' ),
			'manage_options',
			FINALPOS_PAGE_SETUP,
			array( $this, 'render_page' )
		);
	}

	/**
	 * Main rendering function - handles routing for dashboard and setup pages.
	 */
	public function render_page() {
		$current_page  = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		$current_stage = get_option( FINALPOS_OPTION_CURRENT_STAGE, FINALPOS_STAGE_AUTH_KEY );

		if ( FINALPOS_PAGE_DASHBOARD === $current_page ) {
			if ( FINALPOS_STAGE_COMPLETE !== $current_stage || ! get_option( FINALPOS_OPTION_JWT_TOKEN ) ) {
				wp_safe_redirect( admin_url( 'admin.php?page=' . FINALPOS_PAGE_SETUP ) );
				exit;
			}
			FinalPOS_Dashboard::render();
			return;
		}

		if ( FINALPOS_PAGE_SETUP === $current_page ) {
			if ( FINALPOS_STAGE_COMPLETE === $current_stage ) {
				wp_safe_redirect( admin_url( 'admin.php?page=' . FINALPOS_PAGE_DASHBOARD ) );
				exit;
			}
			FinalPOS_Wizard::render();
			return;
		}

		// Default: Redirect to dashboard.
		wp_safe_redirect( admin_url( 'admin.php?page=' . FINALPOS_PAGE_DASHBOARD ) );
		exit;
	}

	/**
	 * Render the Logs sub-menu page.
	 */
	public function render_logs_page() {
		$current_stage = get_option( FINALPOS_OPTION_CURRENT_STAGE, FINALPOS_STAGE_AUTH_KEY );
		if ( FINALPOS_STAGE_COMPLETE !== $current_stage || ! get_option( FINALPOS_OPTION_JWT_TOKEN ) ) {
			wp_safe_redirect( admin_url( 'admin.php?page=' . FINALPOS_PAGE_SETUP ) );
			exit;
		}
		FinalPOS_Dashboard::render_logs();
	}
}

// Initialize the plugin.
new FinalPOS_Plugin();

