<?php
/**
 * Adapter for "Spreadsheet Sync for WooCommerce" (acowebs).
 *
 * Option shapes below were confirmed against the free plugin's source
 * (spreadsheet-sync-for-woocommerce, v1.0.2 at audit time; see
 * .superpowers/sdd/competitor-spreadsheetsync.md):
 *  - `acowpgs_api_options` is a serialized associative array
 *    `['sheet_id' => string, 'secret_key' => string]`
 *    (includes/class-sheets-api-admin.php:109-138). `sheet_id` is a bare
 *    Google Sheet ID string, saved verbatim with only `sanitize_text_field`
 *    (no URL wrapper) — the admin UI literally instructs the merchant to
 *    paste "just the ID". Neither option row exists until the merchant saves
 *    the settings screen at least once (no activation hook seeds them).
 *  - `acowpgs_api_product_settings` / `acowpgs_api_order_settings` are each a
 *    serialized associative array `['send_fields' => string[], ...]`. This
 *    plugin has no resource-level "enable sync" boolean at all — the closest
 *    signal is whether `send_fields` is non-empty for that resource
 *    (includes/class-sheets-api-routes.php:175-204,
 *    includes/class-sheets-order-api-routes.php:116-160).
 *  - This plugin never calls Google's Sheets API from WordPress at all: WP
 *    exposes a REST namespace (`acowpgs-api/v1`) that a vendor-hosted Apps
 *    Script add-on calls into, authenticated by an `x_sheet_token` header
 *    derived from `acowpgs_api_options['secret_key']` — a plugin-generated
 *    shared secret, not a Google credential of any kind. There is no
 *    client_id/client_secret/refresh_token/service-account anywhere in this
 *    plugin, so `secret_key` is never read or mapped to StoreSheet's
 *    credentials/webhook_secret.
 *
 * @package StoreSheet
 */

declare( strict_types=1 );

namespace StoreSheet\Importer\Adapters;

defined( 'ABSPATH' ) || exit;

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

final class SpreadsheetSyncAdapter implements SourceAdapter {

	private const OPTION_API              = 'acowpgs_api_options';
	private const OPTION_PRODUCT_SETTINGS = 'acowpgs_api_product_settings';
	private const OPTION_ORDER_SETTINGS   = 'acowpgs_api_order_settings';

	public function id(): string {
		return 'spreadsheet-sync';
	}

	public function label(): string {
		return __( 'Spreadsheet Sync for WooCommerce', 'storesheet' );
	}

	public function plugin_files(): array {
		return array( 'spreadsheet-sync-for-woocommerce/spreadsheet-sync-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 '' !== $this->sheet_id();
	}

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

		$spreadsheet    = null;
		$spreadsheet_id = $this->sheet_id();
		if ( '' !== $spreadsheet_id ) {
			$spreadsheet = array(
				'id'  => $spreadsheet_id,
				'url' => 'https://docs.google.com/spreadsheets/d/' . $spreadsheet_id . '/edit',
			);
		}

		$product_settings = get_option( self::OPTION_PRODUCT_SETTINGS, array() );
		$product_fields   = is_array( $product_settings ) ? (array) ( $product_settings['send_fields'] ?? array() ) : array();

		$order_settings = get_option( self::OPTION_ORDER_SETTINGS, array() );
		$order_fields   = is_array( $order_settings ) ? (array) ( $order_settings['send_fields'] ?? array() ) : array();

		// No resource-level enable/disable toggle exists in this plugin — a
		// non-empty send_fields list is the only signal that a resource was
		// actually being pushed. See class doc block above.
		$settings = array_filter(
			array(
				'sync_products' => array() !== $product_fields ? true : null,
				'sync_orders'   => array() !== $order_fields ? true : null,
			),
			static function ( $v ) {
				return null !== $v;
			}
		);

		// The only locally stored secret is a plugin-generated REST token
		// (acowpgs_api_options['secret_key']) that authenticates the vendor's
		// Apps Script add-on back into this site — it is not a Google
		// credential and is never read here.
		$credentials = null;
		$warnings[]  = __( 'Spreadsheet Sync for WooCommerce authenticates its Google Sheets add-on with a plugin-generated REST token, not a Google account — 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;
	}

	/**
	 * Bare Google Sheet ID from `acowpgs_api_options['sheet_id']`, or ''.
	 */
	private function sheet_id(): string {
		$api = get_option( self::OPTION_API, array() );
		return is_array( $api ) ? (string) ( $api['sheet_id'] ?? '' ) : '';
	}
}
