<?php
/**
 * One destination, as a self-contained card.
 *
 * Structure C: everything about one sheet lives in one card, and the setup
 * help sits next to the field that raises the question rather than in a
 * separate section further up the page.
 *
 * @package Ordsync
 *
 * @var string $tab       Destination type.
 * @var int    $ordsync_slot_i    Slot index.
 * @var array  $ordsync_slot      Slot settings.
 * @var array  $statuses  Order statuses.
 * @var string $secret    Apps Script secret.
 */

defined( 'ABSPATH' ) || exit;

/*
 * Decide this here rather than trusting an inherited variable.
 *
 * This partial previously read $multi, which the including page never
 * defined -- it names its own copy ($ordsync_premium today). The undefined
 * variable evaluated as falsy, so the import section showed its upsell even
 * to licensed users. Asking the licence directly cannot drift out of sync
 * with whoever includes this file.
 *
 * This governs the bulk-import UI only. Ordsync_Import is absent from the
 * free build, so class_exists() below short-circuits and free users see the
 * upsell text for a feature that is genuinely not there -- not a locked one.
 */
$ordsync_slot_premium = function_exists( 'ordsync_is_premium' ) && ordsync_is_premium();

$ordsync_n     = 'ordsync[' . $tab . '][' . $ordsync_slot_i . ']';
$ordsync_id    = $tab . ( $ordsync_slot_i > 0 ? '_' . $ordsync_slot_i : '' );
$ordsync_on    = ( 'yes' === $ordsync_slot['enabled'] );
$ordsync_url   = isset( $ordsync_slot['url'] ) ? trim( (string) $ordsync_slot['url'] ) : '';
$ordsync_state = Ordsync_Settings::status( $ordsync_id );

/*
 * Four states, decided in Ordsync_Settings so the precedence is testable.
 * A destination that has never been configured does not nag: the chip only
 * reports a problem once there is something to report.
 */
$ordsync_chip = Ordsync_Settings::status_state( $ordsync_id );

/*
 * Open the setup help automatically while there is nothing in the URL
 * field, and fold it away once the user has what it was explaining.
 */
$ordsync_help_open = ( 'sheets' === $tab && '' === $ordsync_url );

$ordsync_singular = array(
	'sheets'  => __( 'Sheet', 'ordercarry-order-automation-for-woocommerce' ),
	'webhook' => __( 'Webhook', 'ordercarry-order-automation-for-woocommerce' ),
	'email'   => __( 'Email', 'ordercarry-order-automation-for-woocommerce' ),
	'pdf'     => __( 'Invoice', 'ordercarry-order-automation-for-woocommerce' ),
);

$ordsync_word = isset( $ordsync_singular[ $tab ] ) ? $ordsync_singular[ $tab ] : __( 'Destination', 'ordercarry-order-automation-for-woocommerce' );
?>

<div class="ordsync-slot <?php echo esc_attr( $ordsync_on ? 'is-on' : 'is-off' ); ?>" data-index="<?php echo esc_attr( $ordsync_slot_i ); ?>">

	<div class="ordsync-slot-head">

		<?php
		/*
		 * A plain checkbox buried in a settings table was too easy to miss:
		 * everything else filled in correctly, nothing sending, and the user
		 * concludes the plugin is broken. As a switch at the top of the card
		 * the on/off state is the first thing you see.
		 */
		?>
		<label class="ordsync-switch">
			<input type="checkbox" name="<?php echo esc_attr( $ordsync_n ); ?>[enabled]" value="yes"
				<?php checked( 'yes', $ordsync_slot['enabled'] ); ?> />
			<span class="ordsync-switch-track" aria-hidden="true"></span>
			<?php
			/*
			 * The visible word is "On"/"Off", which on its own is a useless
			 * accessible name -- a screen reader would announce "On, checkbox"
			 * with no clue what it governs. The hidden text names the control;
			 * the visible word is hidden from assistive tech because the
			 * checkbox already announces its own state.
			 *
			 * Placed AFTER the track on purpose: the track is styled through
			 * an adjacent-sibling selector, so anything inserted between the
			 * input and the track silently breaks the switch.
			 */
			?>
			<span class="screen-reader-text">
				<?php esc_html_e( 'Send orders to this destination', 'ordercarry-order-automation-for-woocommerce' ); ?>
			</span>
			<span class="ordsync-switch-text" aria-hidden="true">
				<?php echo $ordsync_on ? esc_html__( 'On', 'ordercarry-order-automation-for-woocommerce' ) : esc_html__( 'Off', 'ordercarry-order-automation-for-woocommerce' ); ?>
			</span>
		</label>

		<?php
		/*
		 * The name is the card's title and is edited in place. Keeping it as
		 * a separate labelled row cost a whole table row to hold a field
		 * almost nobody changes, yet it has to stay reachable: with twenty
		 * sheets it is the only way to tell them apart.
		 */
		?>
		<label class="screen-reader-text" for="ordsync-label-<?php echo esc_attr( $ordsync_id ); ?>">
			<?php esc_html_e( 'Name', 'ordercarry-order-automation-for-woocommerce' ); ?>
		</label>
		<?php
		// Already-translated noun plus its number, e.g. "Sheet 2". Built by
		// concatenation on purpose: a "%s %d" format string would need a
		// translators comment that neither the POT tool nor Plugin Check can
		// reliably attach through the nested esc_attr( sprintf( __() ) ).
		$ordsync_placeholder = $ordsync_word . ' ' . ( $ordsync_slot_i + 1 );
		?>
		<input type="text" class="ordsync-slot-title"
			id="ordsync-label-<?php echo esc_attr( $ordsync_id ); ?>"
			name="<?php echo esc_attr( $ordsync_n ); ?>[label]"
			value="<?php echo esc_attr( $ordsync_slot['label'] ); ?>"
			placeholder="<?php echo esc_attr( $ordsync_placeholder ); ?>" />

		<?php if ( 'error' === $ordsync_chip ) : ?>
			<span class="ordsync-chip is-error" title="<?php echo esc_attr( $ordsync_state['msg'] ); ?>">
				<?php esc_html_e( 'Last attempt failed', 'ordercarry-order-automation-for-woocommerce' ); ?>
			</span>
		<?php elseif ( 'sent' === $ordsync_chip ) : ?>
			<span class="ordsync-chip is-ok">
				<?php
				printf(
					/* translators: %s: human readable time difference, e.g. "5 mins" */
					esc_html__( 'Sent %s ago', 'ordercarry-order-automation-for-woocommerce' ),
					esc_html( human_time_diff( $ordsync_state['ok'], time() ) )
				);
				?>
			</span>
		<?php elseif ( 'test' === $ordsync_chip ) : ?>
			<span class="ordsync-chip is-test">
				<?php esc_html_e( 'Test passed — no orders yet', 'ordercarry-order-automation-for-woocommerce' ); ?>
			</span>
		<?php else : ?>
			<span class="ordsync-chip is-idle">
				<?php esc_html_e( 'Nothing sent yet', 'ordercarry-order-automation-for-woocommerce' ); ?>
			</span>
		<?php endif; ?>

	</div>

	<div class="ordsync-slot-body">

		<?php if ( 'sheets' === $tab || 'webhook' === $tab ) : ?>
			<div class="ordsync-field">
				<label for="ordsync-url-<?php echo esc_attr( $ordsync_id ); ?>">
					<?php
					echo 'sheets' === $tab
						? esc_html__( 'Google Sheet web app URL', 'ordercarry-order-automation-for-woocommerce' )
						: esc_html__( 'URL', 'ordercarry-order-automation-for-woocommerce' );
					?>
				</label>
				<input type="url" class="ordsync-url code"
					id="ordsync-url-<?php echo esc_attr( $ordsync_id ); ?>"
					name="<?php echo esc_attr( $ordsync_n ); ?>[url]"
					value="<?php echo esc_attr( $ordsync_slot['url'] ); ?>"
					placeholder="<?php echo esc_attr( 'sheets' === $tab ? 'https://script.google.com/macros/s/…/exec' : 'https://' ); ?>" />

				<?php if ( 'webhook' === $tab ) : ?>
					<p class="description">
						<?php esc_html_e( 'Every request carries an X-Ordsync-Signature header so the receiver can verify it.', 'ordercarry-order-automation-for-woocommerce' ); ?>
					</p>
				<?php endif; ?>

				<?php if ( 'sheets' === $tab ) : ?>
					<?php
					/*
					 * The setup instructions live here, behind the exact
					 * question the empty field provokes. Putting them in a
					 * separate card further up meant a user who already
					 * finished setup still scrolled past a screen of code
					 * every time they opened the page.
					 */
					?>
					<details class="ordsync-help" <?php echo esc_attr( $ordsync_help_open ? 'open' : '' ); ?>>
						<summary><?php esc_html_e( 'Where do I get this URL?', 'ordercarry-order-automation-for-woocommerce' ); ?></summary>

						<div class="ordsync-help-body">

							<p class="description">
								<?php esc_html_e( 'About 60 seconds. No Google Cloud account, no API keys.', 'ordercarry-order-automation-for-woocommerce' ); ?>
							</p>

							<p>
								<a class="button" href="https://sheets.new" target="_blank" rel="noopener noreferrer">
									<?php esc_html_e( 'Create a blank Google Sheet', 'ordercarry-order-automation-for-woocommerce' ); ?>
								</a>
								<span class="description">
									<?php esc_html_e( 'Skip this if you already have a sheet.', 'ordercarry-order-automation-for-woocommerce' ); ?>
								</span>
							</p>

							<ol class="ordsync-steps">
								<li><?php esc_html_e( 'In your sheet: Extensions → Apps Script', 'ordercarry-order-automation-for-woocommerce' ); ?></li>
								<li><?php esc_html_e( 'Delete everything there and paste the script below', 'ordercarry-order-automation-for-woocommerce' ); ?></li>
								<li><?php esc_html_e( 'Deploy → New deployment → Web app. Execute as: Me. Who has access: Anyone', 'ordercarry-order-automation-for-woocommerce' ); ?></li>
								<li><?php esc_html_e( 'Copy the /exec URL Google shows you and paste it in the box above', 'ordercarry-order-automation-for-woocommerce' ); ?></li>
							</ol>

							<p>
								<button type="button" class="button button-primary ordsync-copy" data-target="ordsync-script-<?php echo esc_attr( $ordsync_id ); ?>">
									<?php esc_html_e( 'Copy script', 'ordercarry-order-automation-for-woocommerce' ); ?>
								</button>
							</p>

							<textarea id="ordsync-script-<?php echo esc_attr( $ordsync_id ); ?>" class="ordsync-script" rows="18" readonly><?php
								echo esc_textarea( ordsync_apps_script( $secret ) );
							?></textarea>

							<p class="description">
								<?php esc_html_e( 'Using several sheets? Paste this same script into each one.', 'ordercarry-order-automation-for-woocommerce' ); ?>
							</p>

						</div>
					</details>
				<?php endif; ?>
			</div>
		<?php endif; ?>

		<?php if ( 'email' === $tab || 'pdf' === $tab ) : ?>
			<div class="ordsync-field">
				<label for="ordsync-to-<?php echo esc_attr( $ordsync_id ); ?>">
					<?php esc_html_e( 'Send to', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</label>
				<input type="text" class="regular-text"
					id="ordsync-to-<?php echo esc_attr( $ordsync_id ); ?>"
					name="<?php echo esc_attr( $ordsync_n ); ?>[to]"
					value="<?php echo esc_attr( $ordsync_slot['to'] ); ?>" />
				<p class="description">
					<?php esc_html_e( 'An email address, or the word "customer" to send it to the buyer.', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</p>
			</div>
		<?php endif; ?>

		<?php if ( 'email' === $tab ) : ?>
			<div class="ordsync-field">
				<label for="ordsync-subject-<?php echo esc_attr( $ordsync_id ); ?>">
					<?php esc_html_e( 'Subject', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</label>
				<input type="text" class="large-text"
					id="ordsync-subject-<?php echo esc_attr( $ordsync_id ); ?>"
					name="<?php echo esc_attr( $ordsync_n ); ?>[subject]"
					value="<?php echo esc_attr( $ordsync_slot['subject'] ); ?>" />
			</div>
			<div class="ordsync-field">
				<label for="ordsync-body-<?php echo esc_attr( $ordsync_id ); ?>">
					<?php esc_html_e( 'Message', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</label>
				<textarea class="large-text" rows="6"
					id="ordsync-body-<?php echo esc_attr( $ordsync_id ); ?>"
					name="<?php echo esc_attr( $ordsync_n ); ?>[body]"><?php echo esc_textarea( $ordsync_slot['body'] ); ?></textarea>
				<p class="description">
					<?php esc_html_e( 'Available variables:', 'ordercarry-order-automation-for-woocommerce' ); ?>
					<code><?php echo esc_html( implode( '  ', Ordsync_Dest_Email::variables() ) ); ?></code>
				</p>
			</div>
		<?php endif; ?>

		<?php if ( 'pdf' === $tab ) : ?>
			<div class="ordsync-field">
				<label for="ordsync-title-<?php echo esc_attr( $ordsync_id ); ?>">
					<?php esc_html_e( 'Invoice heading', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</label>
				<input type="text" class="regular-text"
					id="ordsync-title-<?php echo esc_attr( $ordsync_id ); ?>"
					name="<?php echo esc_attr( $ordsync_n ); ?>[title]"
					value="<?php echo esc_attr( $ordsync_slot['title'] ); ?>" placeholder="INVOICE" />
				<p class="description">
					<?php esc_html_e( 'For example RECHNUNG for a German shop.', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</p>
			</div>
			<div class="ordsync-field">
				<label for="ordsync-footer-<?php echo esc_attr( $ordsync_id ); ?>">
					<?php esc_html_e( 'Footer line', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</label>
				<input type="text" class="large-text"
					id="ordsync-footer-<?php echo esc_attr( $ordsync_id ); ?>"
					name="<?php echo esc_attr( $ordsync_n ); ?>[footer]"
					value="<?php echo esc_attr( $ordsync_slot['footer'] ); ?>" />
			</div>
		<?php endif; ?>

		<div class="ordsync-field">
			<label for="ordsync-trigger-<?php echo esc_attr( $ordsync_id ); ?>">
				<?php esc_html_e( 'Send orders when they become', 'ordercarry-order-automation-for-woocommerce' ); ?>
			</label>
			<select id="ordsync-trigger-<?php echo esc_attr( $ordsync_id ); ?>"
				name="<?php echo esc_attr( $ordsync_n ); ?>[trigger]">
				<?php foreach ( Ordsync_Settings::trigger_choices() as $ordsync_trigger => $ordsync_trigger_label ) : ?>
					<option value="<?php echo esc_attr( $ordsync_trigger ); ?>"
						<?php selected( $ordsync_trigger, $ordsync_slot['trigger'] ); ?>>
						<?php echo esc_html( $ordsync_trigger_label ); ?>
					</option>
				<?php endforeach; ?>
			</select>
			<?php if ( Ordsync_Settings::TRIGGER_ANY === $ordsync_slot['trigger'] ) : ?>
				<p class="description">
					<?php esc_html_e( 'Every order is sent once, at its first status change — which may be before payment clears.', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</p>
			<?php else : ?>
				<p class="description">
					<?php esc_html_e( 'Orders that never reach this status are never sent. Pick "Any status" if you take bank transfers or create orders by hand.', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</p>
			<?php endif; ?>
		</div>

		<?php require ORDSYNC_PATH . 'admin/views/partial-conditions.php'; ?>

	</div>

	<?php
	/*
	 * Actions, not settings. The test is first and primary because it is the
	 * moment that proves the whole thing works; importing is rare and
	 * one-off, so it stays folded away rather than occupying a permanent
	 * section of every card.
	 */
	?>
	<div class="ordsync-slot-foot">

		<button type="button" class="button button-primary ordsync-test" data-dest="<?php echo esc_attr( $ordsync_id ); ?>">
			<?php esc_html_e( 'Send test order', 'ordercarry-order-automation-for-woocommerce' ); ?>
		</button>
		<span class="ordsync-test-result" aria-live="polite"></span>

		<span class="ordsync-foot-spacer"></span>

		<?php if ( $ordsync_slot_i > 0 ) : ?>
			<button type="button" class="button-link ordsync-remove-slot">
				<?php esc_html_e( 'Delete', 'ordercarry-order-automation-for-woocommerce' ); ?>
			</button>
		<?php endif; ?>
	</div>

	<details class="ordsync-disclosure ordsync-import-disclosure">
		<summary>
			<?php esc_html_e( 'Import past orders', 'ordercarry-order-automation-for-woocommerce' ); ?>
			<?php if ( ! class_exists( 'Ordsync_Import' ) || ! $ordsync_slot_premium ) : ?>
				<span class="ordsync-pro-badge"><?php esc_html_e( 'Pro', 'ordercarry-order-automation-for-woocommerce' ); ?></span>
			<?php endif; ?>
		</summary>

		<div class="ordsync-disclosure-body">
			<?php if ( class_exists( 'Ordsync_Import' ) && $ordsync_slot_premium ) : ?>

				<p class="ordsync-import">
					<select class="ordsync-import-limit" aria-label="<?php esc_attr_e( 'How many orders', 'ordercarry-order-automation-for-woocommerce' ); ?>">
						<?php foreach ( Ordsync_Import::sizes() as $ordsync_size => $ordsync_size_label ) : ?>
							<option value="<?php echo esc_attr( $ordsync_size ); ?>" <?php selected( 100, $ordsync_size ); ?>>
								<?php echo esc_html( $ordsync_size_label ); ?>
							</option>
						<?php endforeach; ?>
					</select>

					<select class="ordsync-import-status" aria-label="<?php esc_attr_e( 'Which status', 'ordercarry-order-automation-for-woocommerce' ); ?>">
						<option value="any"><?php esc_html_e( 'Any status', 'ordercarry-order-automation-for-woocommerce' ); ?></option>
						<?php foreach ( $statuses as $ordsync_status => $ordsync_status_label ) : ?>
							<option value="<?php echo esc_attr( $ordsync_status ); ?>">
								<?php echo esc_html( $ordsync_status_label ); ?>
							</option>
						<?php endforeach; ?>
					</select>

					<button type="button" class="button ordsync-import-run" data-dest="<?php echo esc_attr( $ordsync_id ); ?>">
						<?php esc_html_e( 'Import now', 'ordercarry-order-automation-for-woocommerce' ); ?>
					</button>

					<span class="ordsync-import-result" aria-live="polite"></span>
				</p>
				<p class="description">
					<?php esc_html_e( 'Turn this on and save first. Orders already sent here are skipped, so you can never get duplicates. Your filters still apply.', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</p>

			<?php else : ?>

				<p class="description">
					<?php esc_html_e( 'A new destination starts empty. Pro can send the orders you already have — the last 50, 100 or 1000 — so it is useful from the first minute instead of waiting for the next sale.', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</p>

			<?php endif; ?>
		</div>
	</details>

</div>
