<?php
/**
 * StoreSheet – Google Sheets Sync for WooCommerce
 *
 * @package           StoreSheet
 * @author            Al Amin Ahamed
 * @copyright         2025 Al Amin Ahamed
 * @license           GPL-2.0-or-later
 *
 * @wordpress-plugin
 * Plugin Name:       StoreSheet – Google Sheets Sync for WooCommerce
 * Plugin URI:        https://alaminahamed.com/projects/storesheet/
 * Description:       Automatically sync WooCommerce products, orders, and coupons to a Google Spreadsheet (one-way, WC → Sheets). OAuth-secured, non-blocking.
 * Version:           1.1.1
 * Author:            Al Amin Ahamed
 * Author URI:        https://alaminahamed.com/
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       storesheet
 * Domain Path:       /languages
 * Requires at least: 6.6
 * Requires PHP:      7.4
 * Requires Plugins:  woocommerce
 * WC requires at least: 3.0
 * WC tested up to:   9.9
 */

defined( 'ABSPATH' ) || exit;

define( 'STORESHEET_VERSION', '1.1.1' );
define( 'STORESHEET_FILE', __FILE__ );
define( 'STORESHEET_DIR', plugin_dir_path( __FILE__ ) );
define( 'STORESHEET_URL', plugin_dir_url( __FILE__ ) );
define( 'STORESHEET_BASENAME', plugin_basename( __FILE__ ) );

if ( ! file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
	return;
}

require_once __DIR__ . '/vendor/autoload.php';

if ( ! function_exists( 'storesheet_fs' ) ) {
	/**
	 * Freemius SDK instance for StoreSheet.
	 *
	 * Freemium single product with a premium version: this free build is on
	 * WordPress.org; the paid features ship in the premium build (`premium_slug`
	 * = storesheet-pro), which Freemius delivers on purchase. The SDK lives under
	 * /freemius — fetch it with `composer freemius:download` (git-ignored,
	 * downloaded at build). See docs/freemius/credentials.md.
	 *
	 * @since 1.0.0
	 * @return \Freemius|null Null when the SDK is absent or init failed.
	 */
	function storesheet_fs() {
		global $storesheet_fs;

		if ( ! isset( $storesheet_fs ) ) {
			$sdk = __DIR__ . '/freemius/start.php';

			// Guard: no fatal until the SDK is dropped in.
			if ( ! file_exists( $sdk ) ) {
				return null;
			}

			require_once $sdk;

			try {
				$storesheet_fs = fs_dynamic_init(
					array(
						'id'                  => '34188',
						'slug'                => 'storesheet',
						'premium_slug'        => 'storesheet-pro',
						'type'                => 'plugin',
						'public_key'          => 'pk_7d37896694215b3ec5e1340f46157',
						'is_premium'          => false,
						'premium_suffix'      => 'Pro',
						'has_premium_version' => true,
						'has_addons'          => false,
						'has_paid_plans'      => true,
						'is_org_compliant'    => true,
						'enable_anonymous'    => true,
						'parallel_activation' => array(
							'enabled'                  => true,
							'premium_version_basename' => 'storesheet-pro/storesheet-pro.php',
						),
						'menu'                => array(
							'slug'    => 'storesheet',
							'account' => true,
							'contact' => false,
							'support' => false,
						),
					)
				);
			} catch ( \Throwable $e ) {
				// A bad id/key or SDK issue must never white-screen the site.
				error_log( 'StoreSheet: Freemius init failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
				$storesheet_fs = null;
			}
		}

		return $storesheet_fs;
	}

	// Init Freemius before the plugin boots.
	storesheet_fs();

	/**
	 * StoreSheet icon on the Freemius opt-in / connect page.
	 * Filter fs_plugin_icon_{slug}; the slug is 'storesheet'. Expects a filesystem path.
	 */
	add_filter(
		'fs_plugin_icon_storesheet',
		static function () {
			$icon = STORESHEET_DIR . 'assets/images/icon-128.png';
			return file_exists( $icon ) ? $icon : false;
		}
	);

	/**
	 * Uninstall cleanup runs through the Freemius `after_uninstall` action rather
	 * than a standalone uninstall.php. A Freemius-managed plugin must not ship one
	 * — it would bypass the SDK's own uninstall handling. Freemius registers its
	 * own WP uninstall handler, so this fires on a normal WordPress uninstall too.
	 */
	if ( storesheet_fs() ) {
		storesheet_fs()->add_action(
			'after_uninstall',
			static function (): void {
				global $wpdb;

				$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}storesheet_sync_log" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
				$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}storesheet_row_map" );  // phpcs:ignore WordPress.DB.DirectDatabaseQuery

				delete_option( 'storesheet_settings' );
				delete_option( 'storesheet_db_version' );
				delete_option( 'storesheet_last_sync' );

				delete_transient( 'storesheet_access_token' );
				delete_transient( 'storesheet_oauth_state' );

				wp_clear_scheduled_hook( 'storesheet_scheduled_sync' );
			}
		);
	}

	// Signal that the Freemius SDK is ready (e.g. for the premium build).
	do_action( 'storesheet_fs_loaded' );
}

/**
 * Returns the main plugin instance.
 *
 * @since 1.0.0
 * @return StoreSheet
 */
function storesheet(): StoreSheet {
	return StoreSheet::get_instance();
}

storesheet()->init();
