<?php

namespace SplitPay\Integrations\FluentCart\Admin;

use SplitPay\Core\ConnectedAccounts;
use SplitPay\Core\UpgradeCTA;
use SplitPay\Integrations\FluentCart\Adapters\FCProductAdapter;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class ProductSplitPayPanel {

	private FCProductAdapter $productAdapter;
	private ConnectedAccounts $connectedAccounts;

	public function __construct() {
		$this->productAdapter   = new FCProductAdapter();
		$this->connectedAccounts = new ConnectedAccounts();
	}

	public function register(): void {
		add_action( 'add_meta_boxes', [ $this, 'addMetaBox' ] );
		add_action( 'save_post_fluent-products', [ $this, 'save' ], 10, 1 );
	}

	public function addMetaBox(): void {
		add_meta_box(
			'spp_fluentcart_split_pay',
			__( 'Split Pay — Stripe Connect', 'bsd-split-pay-stripe-connect-woo' ),
			[ $this, 'renderMetaBox' ],
			'fluent-products',
			'normal',
			'default'
		);
	}

	public function renderMetaBox( $post ): void {
		$postId    = (int) $post->ID;
		$isPremium = UpgradeCTA::isPremium();
		$disabled      = $isPremium ? '' : 'disabled';
		$amountDisabled = 'disabled';

		$accounts           = $this->productAdapter->getConnectedAccounts( $postId );
		$transferTypes      = $this->productAdapter->getTransferType( $postId );
		$transferPercents   = $this->productAdapter->getTransferPercentage( $postId );
		$transferAmounts    = $this->productAdapter->getTransferAmount( $postId );
		$shippingSettings   = $this->productAdapter->getShippingTransferSettings( $postId );
		$storedAccounts     = $this->connectedAccounts->getStoredAccounts();

		wp_nonce_field( 'spp_fc_product_split_pay', 'spp_fc_nonce' );

		if ( ! $isPremium ) {
			UpgradeCTA::renderInlineUpgrade( 'product-level FluentCart Split Pay settings' );
			echo '<p style="color:#666;font-style:italic;">Global transfer settings still apply to all products. Product-level configuration requires PRO.</p>';
			return;
		}

		echo '<div class="spp-fc-split-pay-panel" style="padding:12px 0;">';

		if ( empty( $storedAccounts ) ) {
			echo '<p>' . esc_html__( 'No connected Stripe accounts found. Add accounts in the Split Pay settings.', 'bsd-split-pay-stripe-connect-woo' ) . '</p>';
			echo '</div>';
			return;
		}

		$slotCount = max( 1, count( $accounts ) );

		for ( $i = 0; $i < $slotCount; $i++ ) {
			$selectedAccount = $accounts[ $i ] ?? '';
			$selectedType    = $transferTypes[ $i ] ?? '';
			$selectedPercent = $transferPercents[ $i ] ?? '';
			$selectedAmount  = $transferAmounts[ $i ] ?? '';

			$shippingType    = $shippingSettings['types'][ $i ] ?? '';
			$shippingPercent = $shippingSettings['percentages'][ $i ] ?? '';
			$shippingAmt     = $shippingSettings['amounts'][ $i ] ?? '';

			echo '<fieldset style="border:1px solid #ccd0d4;padding:12px;margin-bottom:12px;">';
			echo '<legend><strong>' . /* translators: %d = account slot number. */ sprintf( esc_html__( 'Account Slot %d', 'bsd-split-pay-stripe-connect-woo' ), (int) ( $i + 1 ) ) . '</strong></legend>';

			echo '<p><label>' . esc_html__( 'Connected Account', 'bsd-split-pay-stripe-connect-woo' ) . '</label><br>';
			echo '<select name="_bsd_spscwt_product_connected_account[]" ' . esc_attr( $disabled ) . ' style="width:100%;">';
			echo '<option value="">' . esc_html__( 'Select', 'bsd-split-pay-stripe-connect-woo' ) . '</option>';

			foreach ( $storedAccounts as $acct ) {
				$acctId    = trim( $acct['bsd_account_id'] ?? '' );
				$acctLabel = '';

				if ( ! empty( $acct['bsd_account_name'] ) && ! empty( $acct['bsd_account_email'] ) ) {
					$acctLabel = $acct['bsd_account_name'] . ' - ' . $acct['bsd_account_email'];
				} elseif ( ! empty( $acct['bsd_account_name'] ) ) {
					$acctLabel = $acct['bsd_account_name'];
				} else {
					$acctLabel = $acctId;
				}

				printf(
					'<option value="%s" %s>%s</option>',
					esc_attr( $acctId ),
					selected( $selectedAccount, $acctId, false ),
					esc_html( $acctLabel )
				);
			}

			echo '</select></p>';

			echo '<p><label>' . esc_html__( 'Transfer Type', 'bsd-split-pay-stripe-connect-woo' ) . '</label><br>';
			printf(
				'<label><input type="radio" name="_bsd_spscwt_product_type[%d]" value="percentage" %s %s> %s</label> ',
				(int) $i,
				checked( $selectedType, 'percentage', false ),
				esc_attr( $disabled ),
				esc_html__( 'Percentage', 'bsd-split-pay-stripe-connect-woo' )
			);
			printf(
				'<label><input type="radio" name="_bsd_spscwt_product_type[%d]" value="amount" %s %s> %s</label>',
				(int) $i,
				checked( $selectedType, 'amount', false ),
				esc_attr( $disabled ),
				esc_html__( 'Fixed Amount', 'bsd-split-pay-stripe-connect-woo' )
			);
			echo '</p>';

			printf(
				'<p><label>%s</label><br><input type="number" name="_stripe_connect_split_pay_transfer_percentage[%d]" value="%s" step="0.01" min="0" max="100" style="width:100px;" %s></p>',
				esc_html__( 'Transfer Percentage (%)', 'bsd-split-pay-stripe-connect-woo' ),
				(int) $i,
				esc_attr( $selectedPercent ),
				esc_attr( $disabled )
			);

			printf(
				'<p><label>%s</label><br><input type="number" name="_bsd_spscwt_product_amount[%d]" value="%s" step="0.01" min="0" style="width:100px;" %s></p>',
				esc_html__( 'Transfer Amount', 'bsd-split-pay-stripe-connect-woo' ),
				(int) $i,
				esc_attr( $selectedAmount ),
				esc_attr( $disabled )
			);

			echo '<hr style="margin:8px 0;">';
			echo '<strong>' . esc_html__( 'Shipping Transfer', 'bsd-split-pay-stripe-connect-woo' ) . '</strong>';

			printf(
				'<p><label>%s</label><br><select name="bsd_spscwt_shipping_type[%d]" %s>',
				esc_html__( 'Shipping Transfer Type', 'bsd-split-pay-stripe-connect-woo' ),
				(int) $i,
				esc_attr( $disabled )
			);
			printf( '<option value="">%s</option>', esc_html__( 'None', 'bsd-split-pay-stripe-connect-woo' ) );
			printf( '<option value="percentage" %s>%s</option>', selected( $shippingType, 'percentage', false ), esc_html__( 'Percentage', 'bsd-split-pay-stripe-connect-woo' ) );
			// 3.7.5 static-analysis: $isPremium narrowed to true by the early
			// return on line 57 (`if ( ! $isPremium ) { ... return; }`).
			printf( '<option value="amount" %s>%s</option>', selected( $shippingType, 'amount', false ), esc_html__( 'Fixed Amount', 'bsd-split-pay-stripe-connect-woo' ) );
			echo '</select></p>';

			printf(
				'<p><label>%s</label><br><input type="number" name="bsd_prod_shipping_percentage[%d]" value="%s" step="0.01" min="0" max="100" style="width:100px;" %s></p>',
				esc_html__( 'Shipping Percentage (%)', 'bsd-split-pay-stripe-connect-woo' ),
				(int) $i,
				esc_attr( $shippingPercent ),
				esc_attr( $disabled )
			);

			printf(
				'<p><label>%s</label><br><input type="number" name="bsd_prod_shipping_amount[%d]" value="%s" step="0.01" min="0" style="width:100px;" %s></p>',
				esc_html__( 'Shipping Amount', 'bsd-split-pay-stripe-connect-woo' ),
				(int) $i,
				esc_attr( $shippingAmt ),
				esc_attr( $disabled )
			);

			echo '</fieldset>';
		}

		echo '</div>';
	}

	public function save( $postId ): void {
		if ( ! isset( $_POST['spp_fc_nonce'] ) || ! wp_verify_nonce( $_POST['spp_fc_nonce'], 'spp_fc_product_split_pay' ) ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $postId ) ) {
			return;
		}

		if ( ! UpgradeCTA::isPremium() ) {
			return;
		}

		$connectedAccounts    = isset( $_POST['_bsd_spscwt_product_connected_account'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['_bsd_spscwt_product_connected_account'] ) ) : [];
		$transferTypes        = isset( $_POST['_bsd_spscwt_product_type'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['_bsd_spscwt_product_type'] ) ) : [];
		$transferPercentages  = isset( $_POST['_stripe_connect_split_pay_transfer_percentage'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['_stripe_connect_split_pay_transfer_percentage'] ) ) : [];
		$transferAmounts      = isset( $_POST['_bsd_spscwt_product_amount'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['_bsd_spscwt_product_amount'] ) ) : [];
		$shippingTypes        = isset( $_POST['bsd_spscwt_shipping_type'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['bsd_spscwt_shipping_type'] ) ) : [];
		$shippingPercentages  = isset( $_POST['bsd_prod_shipping_percentage'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['bsd_prod_shipping_percentage'] ) ) : [];
		$shippingAmounts      = isset( $_POST['bsd_prod_shipping_amount'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_POST['bsd_prod_shipping_amount'] ) ) : [];

		$this->productAdapter->saveProductSplitPaySettings( (int) $postId, [
			'connected_accounts'   => $connectedAccounts,
			'transfer_types'       => $transferTypes,
			'transfer_percentages' => $transferPercentages,
			'transfer_amounts'     => $transferAmounts,
			'shipping_types'       => $shippingTypes,
			'shipping_percentages' => $shippingPercentages,
			'shipping_amounts'     => $shippingAmounts,
		] );
	}
}
