<?php
namespace Pixeldev\SquareWooSync\Payments;

defined( 'ABSPATH' ) || exit;

use Pixeldev\SquareWooSync\Square\SquareHelper;

/**
 * ApplePayDomainVerifier
 *
 * Handles the full Apple-Pay domain-verification flow without Square SDK:
 *   1. Download association file from Square
 *   2. Save under /.well-known/
 *   3. Call POST /v2/apple-pay/domains via SquareHelper
 *
 * Verification is cached per environment (live / sandbox) by a flag
 * in wp_options so we only run once.
 */
class ApplePayDomainVerifier {

	/**
	 * Verify domain for Apple Pay.
	 *
	 * @param string $accessToken  Merchant’s OAuth token.
	 * @param string $environment  'live' | 'sandbox'
	 * @return bool                True when verified or already in place.
	 */
	public static function verify( string $accessToken, string $environment = 'live' ) : bool {

		$flag = "sws_applepay_verified_{$environment}";
		$done = get_option( $flag, false );

		$filePath = trailingslashit( ABSPATH )
		          . '.well-known/apple-developer-merchantid-domain-association';

		/* ── skip if flag + file both present ───────────────────────── */
		if ( $done && file_exists( $filePath ) ) {
			return true;
		}

		/* ── step 1: download canonical file ───────────────────────── */
		$remoteFile = 'https://app.squareup.com/digital-wallets/apple-pay/apple-developer-merchantid-domain-association';
		$response   = wp_remote_get( $remoteFile, [ 'timeout' => 15 ] );

		if ( is_wp_error( $response ) ) {
			error_log( '[ApplePay] download failed: ' . $response->get_error_message() );
			return false;
		}
		if ( wp_remote_retrieve_response_code( $response ) !== 200 ) {
			error_log( '[ApplePay] download failed: HTTP ' . wp_remote_retrieve_response_code( $response ) );
			return false;
		}

		$content = trim( wp_remote_retrieve_body( $response ) );
		if ( ! $content ) {
			error_log( '[ApplePay] association file empty' );
			return false;
		}

		/* ── step 2: write file (create dir if needed) ─────────────── */
		$dir = dirname( $filePath );
		if ( ! is_dir( $dir ) && ! wp_mkdir_p( $dir ) ) {
			error_log( '[ApplePay] cannot create /.well-known directory.' );
			return false;
		}

		if ( ! file_put_contents( $filePath, $content ) ) {
			error_log( '[ApplePay] cannot write association file.' );
			return false;
		}

		/* ── step 3: call POST /v2/apple-pay/domains ──────────────── */
		$domain = wp_parse_url( home_url(), PHP_URL_HOST );

		$sq = new SquareHelper();
		$resp = $sq->square_api_request(
			'/apple-pay/domains',
			'POST',
			[ 'domain_name' => $domain ],
			$accessToken   // override token so helper uses THIS merchant
		);

		if ( ! $resp['success'] ) {
			error_log( '[ApplePay] registerDomain failed: ' . $resp['error'] );
			return false;
		}

		/* ── flag as done ──────────────────────────────────────────── */
		update_option( $flag, true, false );
		return true;
	}
}
