<?php
/**
 * Adapter for "FlexOrder – Order Sync with Google Sheets" (WPPOOL).
 *
 * Option shapes below were confirmed against the free plugin's source
 * (order-sync-with-google-sheets-for-woocommerce, v1.17.7 at audit time; see
 * .superpowers/sdd/competitor-flexorder.md):
 *  - `osgsw_spreadsheet_id` holds the parsed, bare Google Spreadsheet ID
 *    (derived server-side from the pasted URL via regex,
 *    includes/classes/class-hooks.php:621-640) and is used directly in Sheets
 *    API URLs elsewhere in the plugin — no unwrapping needed.
 *    `osgsw_spreadsheet_url` holds the raw pasted URL as a fallback/display
 *    value. Because nearly every `osgsw_*` option row is pre-seeded with an
 *    empty default the moment the plugin boots (`App::reset_options()`,
 *    includes/classes/class-app.php:353-362), presence of the option row is
 *    not a signal — only a non-empty `spreadsheet_id` is.
 *  - Order-status filtering is one boolean option per WooCommerce status slug,
 *    `osgsw_sync_status_{slug}` (e.g. `osgsw_sync_status_processing`,
 *    `osgsw_sync_status_on-hold`), assembled dynamically in
 *    `App::get_default_options()` (includes/classes/class-app.php:134-141).
 *    There is no single array option to read.
 *  - The free build is exclusively an Orders → Sheets pusher (confirmed no
 *    product/coupon/customer WC hooks anywhere in the plugin), so
 *    `sync_orders` is always reported `true` once this adapter is present.
 *  - `osgsw_credentials` stores the merchant's own uploaded Google
 *    service-account JSON key (private RSA key included) verbatim, used for a
 *    JWT-bearer 2-legged auth flow — structurally incompatible with
 *    StoreSheet's user-consent OAuth `GoogleOAuthClient`. It is never read
 *    here; the user reconnects Google through StoreSheet's own flow instead.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Importer\Adapters;

defined( 'ABSPATH' ) || exit;

use StoreSheet\Importer\ImportPlan;
use StoreSheet\Importer\SourceAdapter;

final class FlexOrderAdapter implements SourceAdapter {

	private const OPTION_SPREADSHEET_ID  = 'osgsw_spreadsheet_id';
	private const OPTION_SPREADSHEET_URL = 'osgsw_spreadsheet_url';
	private const OPTION_STATUS_PREFIX   = 'osgsw_sync_status_';

	/** Bare WC order-status slugs FlexOrder exposes a per-status toggle for. */
	private const ALLOWED_STATUSES = array( 'pending', 'processing', 'on-hold', 'completed', 'cancelled', 'refunded', 'failed' );

	public function id(): string {
		return 'flexorder';
	}

	public function label(): string {
		return __( 'FlexOrder – Order Sync with Google Sheets', 'storesheet' );
	}

	public function plugin_files(): array {
		return array( 'order-sync-with-google-sheets-for-woocommerce/order-sync-with-google-sheets-for-woocommerce.php' );
	}

	public function is_present(): bool {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		foreach ( $this->plugin_files() as $file ) {
			if ( is_plugin_active( $file ) ) {
				return true;
			}
		}
		return '' !== (string) get_option( self::OPTION_SPREADSHEET_ID, '' );
	}

	public function read_config(): ImportPlan {
		$warnings = array();

		$spreadsheet    = null;
		$spreadsheet_id = (string) get_option( self::OPTION_SPREADSHEET_ID, '' );
		if ( '' !== $spreadsheet_id ) {
			$raw_url     = (string) get_option( self::OPTION_SPREADSHEET_URL, '' );
			$spreadsheet = array(
				'id'  => $spreadsheet_id,
				'url' => '' !== $raw_url ? $raw_url : 'https://docs.google.com/spreadsheets/d/' . $spreadsheet_id . '/edit',
			);
		}

		// ALLOWED_STATUSES is already the bare-slug allow-list, so each option
		// key below is read/emitted with no `wc-` prefix to strip.
		$order_statuses = array();
		foreach ( self::ALLOWED_STATUSES as $slug ) {
			if ( $this->truthy( get_option( self::OPTION_STATUS_PREFIX . $slug, null ) ) ) {
				$order_statuses[] = $slug;
			}
		}

		$settings = array_filter(
			array(
				'sync_orders'    => true,
				'order_statuses' => array() !== $order_statuses ? $order_statuses : null,
			),
			static function ( $v ) {
				return null !== $v;
			}
		);

		// FlexOrder stores its own Google service-account key for direct,
		// JWT-signed Sheets API access — never a client secret StoreSheet's
		// OAuth flow could reuse. See class doc block above.
		$credentials = null;
		$warnings[]  = __( 'FlexOrder stores its own Google service-account key for direct Sheets API access — this can\'t be reused by StoreSheet\'s OAuth connection; connect your Google account on the next step.', 'storesheet' );

		return new ImportPlan( $this->id(), $this->label(), $credentials, $spreadsheet, $settings, array(), $warnings );
	}

	public function supports_sheet_adopt(): bool {
		return true;
	}

	/**
	 * Map a competitor value to bool, or null when the key is absent.
	 * Arrays (e.g. enabled-order-status lists) are truthy when non-empty.
	 *
	 * @param mixed $value Raw option value.
	 */
	private function truthy( $value ): ?bool {
		if ( null === $value ) {
			return null;
		}
		if ( is_array( $value ) ) {
			return array() !== $value;
		}
		return in_array( $value, array( 'yes', '1', 1, true, 'true', 'on' ), true );
	}
}
