<?php
/**
 * Settings page.
 *
 * Structure C: one card per destination, setup help folded into the field
 * that raises the question, and everything one-time or reference-only under
 * a single Advanced disclosure at the foot of the page.
 *
 * @package Ordsync
 *
 * @var array  $settings       Current settings, type => list of slots.
 * @var string $secret         Apps Script secret.
 * @var string $webhook_secret Webhook signing key.
 * @var array  $statuses       Order statuses.
 * @var string $tab            Active tab.
 */

defined( 'ABSPATH' ) || exit;

$ordsync_tabs = array(
	'sheets'  => __( 'Google Sheets', 'ordercarry-order-automation-for-woocommerce' ),
	'webhook' => __( 'Webhook', 'ordercarry-order-automation-for-woocommerce' ),
	'email'   => __( 'Custom Email', 'ordercarry-order-automation-for-woocommerce' ),
);

/*
 * Gate on the LICENCE, not on whether the class happens to be loaded.
 * class_exists() is true for anyone running the Pro build, licensed or not.
 *
 * This governs the PDF tab only. Adding destinations is NOT gated: every
 * build runs as many of each type as it is configured with. A free plugin
 * that carried the machinery for extra destinations and then refused to run
 * them would be limiting a built-in feature, which wordpress.org guideline 5
 * forbids outright.
 */
$ordsync_premium = function_exists( 'ordsync_is_premium' ) && ordsync_is_premium();

if ( $ordsync_premium ) {
	$ordsync_tabs['pdf'] = __( 'PDF Invoice', 'ordercarry-order-automation-for-woocommerce' );
}

$ordsync_tabs['logs'] = __( 'Logs', 'ordercarry-order-automation-for-woocommerce' );

if ( ! isset( $ordsync_tabs[ $tab ] ) ) {
	$tab = 'sheets';
}

$ordsync_intro = array(
	'sheets'  => __( 'One row per order in your own Google Sheet. No Google Cloud Console, no API keys.', 'ordercarry-order-automation-for-woocommerce' ),
	'webhook' => __( 'Full order data as JSON. Works with Make, n8n, Airtable, or your own backend.', 'ordercarry-order-automation-for-woocommerce' ),
	'email'   => __( 'Your own subject and message, with {variables} filled in from the order.', 'ordercarry-order-automation-for-woocommerce' ),
	'pdf'     => __( 'Generates a real invoice and attaches it to an email. No heavy PDF library, so it works on cheap hosting too.', 'ordercarry-order-automation-for-woocommerce' ),
);

// What one of these is called when you are talking about adding another.
$ordsync_add_label = array(
	'sheets'  => __( '+ Add sheet', 'ordercarry-order-automation-for-woocommerce' ),
	'webhook' => __( '+ Add webhook', 'ordercarry-order-automation-for-woocommerce' ),
	'email'   => __( '+ Add email', 'ordercarry-order-automation-for-woocommerce' ),
	'pdf'     => __( '+ Add invoice', 'ordercarry-order-automation-for-woocommerce' ),
);
?>
<div class="wrap ordsync-wrap">

	<h1><?php esc_html_e( 'OrderCarry', 'ordercarry-order-automation-for-woocommerce' ); ?></h1>
	<p class="ordsync-tagline">
		<?php esc_html_e( 'Unlimited orders. Runs on your own server. No tasks, no credits, no monthly fee.', 'ordercarry-order-automation-for-woocommerce' ); ?>
	</p>

	<?php if ( isset( $_GET['updated'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
		<div class="notice notice-success is-dismissible">
			<p><?php esc_html_e( 'Settings saved.', 'ordercarry-order-automation-for-woocommerce' ); ?></p>
		</div>
	<?php endif; ?>

	<?php if ( isset( $_GET['secret_reset'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
		<div class="notice notice-warning is-dismissible">
			<p><?php esc_html_e( 'A new secret was created. Paste it into your Apps Script again, or the sync will stop.', 'ordercarry-order-automation-for-woocommerce' ); ?></p>
		</div>
	<?php endif; ?>

	<?php if ( isset( $_GET['webhook_secret_reset'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
		<div class="notice notice-warning is-dismissible">
			<p><?php esc_html_e( 'A new signing key was created. Update it wherever you verify the signature, or your receiver will start rejecting requests.', 'ordercarry-order-automation-for-woocommerce' ); ?></p>
		</div>
	<?php endif; ?>

	<nav class="nav-tab-wrapper">
		<?php foreach ( $ordsync_tabs as $ordsync_key => $ordsync_label ) : ?>
			<a class="nav-tab <?php echo esc_attr( $tab === $ordsync_key ? 'nav-tab-active' : '' ); ?>"
				href="<?php echo esc_url( admin_url( 'admin.php?page=ordsync&tab=' . $ordsync_key ) ); ?>">
				<?php echo esc_html( $ordsync_label ); ?>
			</a>
		<?php endforeach; ?>
	</nav>

	<?php if ( 'logs' === $tab ) : ?>

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

		<div class="ordsync-card">
			<h2><?php esc_html_e( 'Automation logs', 'ordercarry-order-automation-for-woocommerce' ); ?></h2>
			<p><?php esc_html_e( 'Every send, retry and failure is written to the WooCommerce log under the source "order-sync".', 'ordercarry-order-automation-for-woocommerce' ); ?></p>
			<p>
				<a class="button button-primary" href="<?php echo esc_url( Ordsync_Logger::admin_url() ); ?>">
					<?php esc_html_e( 'View logs', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</a>
			</p>
			<p class="description">
				<?php esc_html_e( 'If something is not arriving, open the logs and read the last red line. It almost always names the exact problem.', 'ordercarry-order-automation-for-woocommerce' ); ?>
			</p>
		</div>

	<?php else : ?>

		<?php $ordsync_slots = isset( $settings[ $tab ] ) ? $settings[ $tab ] : array(); ?>

		<p class="ordsync-intro description">
			<?php echo esc_html( isset( $ordsync_intro[ $tab ] ) ? $ordsync_intro[ $tab ] : '' ); ?>
		</p>

		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="ordsync_save" />
			<input type="hidden" name="tab" value="<?php echo esc_attr( $tab ); ?>" />
			<?php wp_nonce_field( 'ordsync_save' ); ?>

			<?php
			/*
			 * Adding sits at the top, where you look for it, rather than
			 * after a screen of settings belonging to the previous card.
			 */
			?>
			<p class="ordsync-add-slot-row">
				<button type="button" class="button ordsync-add-slot"
					data-next="<?php echo esc_attr( count( $ordsync_slots ) ); ?>">
					<?php echo esc_html( isset( $ordsync_add_label[ $tab ] ) ? $ordsync_add_label[ $tab ] : __( '+ Add', 'ordercarry-order-automation-for-woocommerce' ) ); ?>
				</button>
				<span class="description">
					<?php esc_html_e( 'Saves first, then adds an empty one.', 'ordercarry-order-automation-for-woocommerce' ); ?>
				</span>
			</p>

			<div class="ordsync-slots">
				<?php
				foreach ( array_values( $ordsync_slots ) as $ordsync_slot_i => $ordsync_slot ) {
					require ORDSYNC_PATH . 'admin/views/partial-slot.php';
				}
				?>
			</div>

			<?php
			/*
			 * The only upgrade LINK on the screen. The filters and import
			 * upsells inside each card are descriptive text with no link, so
			 * removing this one would leave no route to the checkout at all.
			 *
			 * It names what Pro actually adds. It used to pitch "up to 20
			 * destinations", which stopped being true when extra destinations
			 * became part of the free plugin.
			 */
			?>
			<?php if ( ! $ordsync_premium && function_exists( 'ordsync_fs' ) && ordsync_fs() ) : ?>
				<p class="ordsync-quiet-upsell">
					<?php esc_html_e( 'Pro adds conditional filters, PDF invoices and bulk import of past orders.', 'ordercarry-order-automation-for-woocommerce' ); ?>
					<a href="<?php echo esc_url( ordsync_fs()->get_upgrade_url() ); ?>">
						<?php esc_html_e( 'See Pro', 'ordercarry-order-automation-for-woocommerce' ); ?>
					</a>
				</p>
			<?php endif; ?>

			<?php submit_button( __( 'Save changes', 'ordercarry-order-automation-for-woocommerce' ) ); ?>

		</form>

		<?php
		/*
		 * Reference material and one-time actions. Outside the settings form
		 * on purpose -- the secret forms post to their own endpoints, and
		 * nested forms do not submit.
		 */
		?>
		<details class="ordsync-disclosure ordsync-advanced">
			<summary><?php esc_html_e( 'Advanced', 'ordercarry-order-automation-for-woocommerce' ); ?></summary>

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

				<p class="ordsync-timing">
					<strong><?php esc_html_e( 'When do real orders arrive?', 'ordercarry-order-automation-for-woocommerce' ); ?></strong>
					<?php
					esc_html_e(
						'Usually within a minute or two. WordPress runs background jobs when visitors arrive, so a busy shop syncs almost immediately and a quiet one can take longer. Nothing is lost — orders wait in the queue. The test button skips the queue, so it answers straight away.',
						'ordercarry-order-automation-for-woocommerce'
					);
					?>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=wc-status&tab=action-scheduler&s=ordsync' ) ); ?>">
						<?php esc_html_e( 'View the queue', 'ordercarry-order-automation-for-woocommerce' ); ?>
					</a>
				</p>

				<?php if ( 'sheets' === $tab ) : ?>
					<h3><?php esc_html_e( 'Your Apps Script secret', 'ordercarry-order-automation-for-woocommerce' ); ?></h3>
					<p>
						<code class="ordsync-secret"><?php echo esc_html( $secret ); ?></code>
					</p>
					<p class="description">
						<?php esc_html_e( 'Already built into the script above. The web app URL is public, so this secret is what stops anyone else writing rows into your sheet.', 'ordercarry-order-automation-for-woocommerce' ); ?>
					</p>

					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="ordsync-danger">
						<input type="hidden" name="action" value="ordsync_regenerate_secret" />
						<?php wp_nonce_field( 'ordsync_regenerate_secret' ); ?>
						<button type="submit" class="button-link ordsync-link-danger">
							<?php esc_html_e( 'Generate a new secret', 'ordercarry-order-automation-for-woocommerce' ); ?>
						</button>
						<span class="description">
							<?php esc_html_e( 'You will have to update every Apps Script afterwards.', 'ordercarry-order-automation-for-woocommerce' ); ?>
						</span>
					</form>
				<?php endif; ?>

				<?php if ( 'webhook' === $tab ) : ?>
					<h3><?php esc_html_e( 'Verifying that a request really came from your shop', 'ordercarry-order-automation-for-woocommerce' ); ?></h3>
					<p>
						<?php esc_html_e( 'Every webhook carries an X-Ordsync-Signature header. It is the SHA-256 HMAC of the exact JSON body, using the key below. Recalculate it on your side and compare — if it matches, the request is genuine.', 'ordercarry-order-automation-for-woocommerce' ); ?>
					</p>
					<p><?php esc_html_e( 'Your signing key:', 'ordercarry-order-automation-for-woocommerce' ); ?>
						<code class="ordsync-secret"><?php echo esc_html( $webhook_secret ); ?></code>
					</p>
					<p class="description">
						<?php esc_html_e( 'This key is never sent anywhere — only the signature is. Keep it to yourself; anyone who has it can produce requests that look like yours. It is deliberately not the same as the Google Sheets secret, which travels to Google inside every row.', 'ordercarry-order-automation-for-woocommerce' ); ?>
					</p>

					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" class="ordsync-danger">
						<input type="hidden" name="action" value="ordsync_regenerate_webhook_secret" />
						<?php wp_nonce_field( 'ordsync_regenerate_webhook_secret' ); ?>
						<button type="submit" class="button-link ordsync-link-danger">
							<?php esc_html_e( 'Generate a new signing key', 'ordercarry-order-automation-for-woocommerce' ); ?>
						</button>
						<span class="description">
							<?php esc_html_e( 'Anything already verifying the old key will start rejecting requests until you update it.', 'ordercarry-order-automation-for-woocommerce' ); ?>
						</span>
					</form>
				<?php endif; ?>

			</div>
		</details>

	<?php endif; ?>

</div>
