<?php
/**
 * ETYKIETOWNIK admin settings — adds tab to ParcelSelector admin panel.
 *
 * @package ParcelSelector
 * @since   3.4.0
 */

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

// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- $_sd/$_ss are pre-built sanitized data attribute strings via esc_attr() in builder above

// Register tab via filter (added in panel-init.php).
add_filter( 'parcselect_tabs', 'parcselect_label_register_tab' );

/**
 * Add Etykietownik tab to the PS admin panel.
 *
 * @param array $tabs Existing tabs.
 * @return array Modified tabs.
 */
function parcselect_label_register_tab( $tabs ) {
	$tabs['etykietownik'] = array(
		'label'    => __( 'Label tool', 'parcel-selector' ),
		'icon'     => "\xF0\x9F\x8F\xB7",
		'callback' => 'parcselect_tab_etykietownik',
	);
	return $tabs;
}

// Handle form save.
add_action( 'admin_init', 'parcselect_label_save_settings' );

/**
 * Save settings when form is submitted.
 */
function parcselect_label_save_settings() {
	if ( ! isset( $_POST['parcselect_label_save'] ) ) {
		return;
	}
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	if ( ! check_admin_referer( 'parcselect_label_settings', 'parcselect_label_nonce' ) ) {
		return;
	}

	$fields = array(
		'parcselect_label_client_id',
		'parcselect_label_client_secret',
		'parcselect_label_username',
		'parcselect_label_password',
		'parcselect_label_service_id',
		'parcselect_label_sender_name',
		'parcselect_label_sender_company',
		'parcselect_label_sender_street',
		'parcselect_label_sender_city',
		'parcselect_label_sender_postcode',
		'parcselect_label_sender_phone',
		'parcselect_label_sender_email',
		'parcselect_label_default_size',
		'parcselect_label_default_weight',
		'parcselect_label_notify_email',
		'parcselect_label_pickup_inpost',
	);

	foreach ( $fields as $field ) {
		if ( isset( $_POST[ $field ] ) ) {
			update_option( $field, sanitize_text_field( wp_unslash( $_POST[ $field ] ) ) );
		}
	}

	// Margin — save as float.
	if ( isset( $_POST['parcselect_label_margin'] ) ) {
		update_option( 'parcselect_label_margin', floatval( wp_unslash( $_POST['parcselect_label_margin'] ) ) );
	}

	// Sandbox toggle.
	update_option( 'parcselect_label_sandbox', isset( $_POST['parcselect_label_sandbox'] ) ? '1' : '0' );

	// Clear token cache when credentials change.
	delete_transient( Parcselect_Label_API::TOKEN_CACHE );

	add_settings_error( 'etykietownik', 'saved', __( 'Settings saved.', 'parcel-selector' ), 'success' );
}

/**
 * Render the Etykietownik settings tab.
 */
function parcselect_tab_etykietownik() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	settings_errors( 'etykietownik' );

	$client_id      = get_option( 'parcselect_label_client_id', '' );
	$client_secret  = get_option( 'parcselect_label_client_secret', '' );
	$api_username   = get_option( 'parcselect_label_username', '' );
	$api_password   = get_option( 'parcselect_label_password', '' );
	$service_id     = get_option( 'parcselect_label_service_id', '' );
	$sender_name    = get_option( 'parcselect_label_sender_name', '' );
	$sender_company = get_option( 'parcselect_label_sender_company', '' );
	$sender_street  = get_option( 'parcselect_label_sender_street', '' );
	$sender_city    = get_option( 'parcselect_label_sender_city', '' );
	$sender_post    = get_option( 'parcselect_label_sender_postcode', '' );
	$sender_phone   = get_option( 'parcselect_label_sender_phone', '' );
	$sender_email   = get_option( 'parcselect_label_sender_email', '' );
	$_sender_saved  = ! empty( $sender_name ) || ! empty( $sender_phone );
	$default_size   = get_option( 'parcselect_label_default_size', 'A' );
	$default_weight = get_option( 'parcselect_label_default_weight', '1.0' );
	$margin         = get_option( 'parcselect_label_margin', 1.00 );
	$sandbox        = get_option( 'parcselect_label_sandbox', '0' );
	$notify_email   = get_option( 'parcselect_label_notify_email', get_option( 'admin_email' ) );
	$sol_wallet     = Parcselect_Label_Pricing::get_sol_wallet();
	?>

	<form method="post" action="">
		<?php wp_nonce_field( 'parcselect_label_settings', 'parcselect_label_nonce' ); ?>
		<input type="hidden" name="parcselect_label_save" value="1">

		<!-- LABEL SERVICE — auto-configured via VPS, hidden from user -->
		<input type="hidden" name="parcselect_label_client_id" value="<?php echo esc_attr( $client_id ); ?>" />
		<input type="hidden" name="parcselect_label_client_secret" value="<?php echo esc_attr( $client_secret ); ?>" />
		<input type="hidden" name="parcselect_label_service_id" value="<?php echo esc_attr( $service_id ); ?>" />

		<!-- ═══ 1. DROP-OFF POINTS (TOP — most important for the user) ═══ -->
		<h3 id="etyk-dropoff"><?php esc_html_e( 'Sender locker (where you ship from)', 'parcel-selector' ); ?></h3>
		<div style="background:#fff7ed;border:1px solid #fed7aa;border-left:4px solid #f97316;border-radius:6px;padding:12px 16px;margin-bottom:14px;">
			<p style="margin:0 0 6px;font-weight:700;color:#9a3412;font-size:13px;">&#x26A0; <?php esc_html_e( 'Important — this setting is used automatically!', 'parcel-selector' ); ?></p>
			<p style="margin:0;color:#78350f;font-size:12px;line-height:1.5;">
				<?php esc_html_e( 'Define the InPost locker you drop packages off at. It will be used automatically every time you generate a label — until you change it. Leave empty to use courier pickup at your address.', 'parcel-selector' ); ?>
			</p>
		</div>
		<?php
		$_dropoff_fields = array(
			array(
				'key'   => 'parcselect_label_pickup_inpost',
				'icon'  => '&#x1F4E6;',
				'label' => 'InPost ' . __( 'sender locker', 'parcel-selector' ),
				'ph'    => 'KRA01A, WAW123M',
				'desc'  => __( 'InPost locker where YOU drop off packages. Any locker in Poland.', 'parcel-selector' ),
				'bold'  => true,
			),
		);
		?>
		<table class="form-table">
			<?php foreach ( $_dropoff_fields as $_df ) :
				$_df_val  = get_option( $_df['key'], '' );
				$_df_set  = ! empty( $_df_val );
				$_df_bold = ! empty( $_df['bold'] );
			?>
			<tr>
				<th><?php echo $_df['icon']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> <?php echo esc_html( $_df['label'] ); ?></th>
				<td>
					<div class="etyk-dropoff-row" data-key="<?php echo esc_attr( $_df['key'] ); ?>">
						<input type="text" name="<?php echo esc_attr( $_df['key'] ); ?>"
							value="<?php echo esc_attr( $_df_val ); ?>"
							class="regular-text etyk-dropoff-input"
							placeholder="<?php echo esc_attr( $_df['ph'] ); ?>"
							<?php echo $_df_set ? 'disabled="disabled"' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static string, no user data ?>
							style="<?php echo esc_attr( ( $_df_bold ? 'font-weight:700;font-size:14px;' : '' ) . ( $_df_set ? 'background:#f0f0f1;color:#50575e;' : '' ) ); ?>" />
						<?php if ( $_df_set ) : ?>
							<button type="button" class="button etyk-dropoff-change" style="margin-left:6px;">&#x270F; <?php esc_html_e( 'Change', 'parcel-selector' ); ?></button>
						<?php else : ?>
							<button type="button" class="button button-primary etyk-dropoff-save" style="margin-left:6px;">&#x2714; <?php esc_html_e( 'Save', 'parcel-selector' ); ?></button>
						<?php endif; ?>
						<span class="etyk-dropoff-status" style="margin-left:8px;font-size:12px;"></span>
					</div>
					<p class="description"><?php echo esc_html( $_df['desc'] ); ?></p>
				</td>
			</tr>
			<?php endforeach; ?>
		</table>

		<!-- ═══ 2. SENDER ADDRESS ═══ -->
		<h3 id="etyk-sender"><?php esc_html_e( 'Sender address', 'parcel-selector' ); ?></h3>
		<div style="background:#eff6ff;border:1px solid #bfdbfe;border-left:4px solid #3b82f6;border-radius:6px;padding:12px 16px;margin-bottom:14px;">
			<p style="margin:0;color:#1e40af;font-size:12px;line-height:1.5;">
				<?php esc_html_e( 'Your sender details appear on every shipping label. For InPost Paczkomaty only your name and phone are required.', 'parcel-selector' ); ?>
			</p>
		</div>
		<?php $_sd = $_sender_saved ? 'disabled="disabled"' : ''; $_ss = $_sender_saved ? 'background:#f0f0f1;color:#50575e;' : ''; ?>
		<div id="etyk-sender-block">
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Name', 'parcel-selector' ); ?></th>
				<td><input type="text" name="parcselect_label_sender_name" value="<?php echo esc_attr( $sender_name ); ?>" class="regular-text etyk-sender-field" placeholder="Jan Kowalski" <?php echo $_sd; ?> style="<?php echo $_ss; ?>" /></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Company', 'parcel-selector' ); ?></th>
				<td><input type="text" name="parcselect_label_sender_company" value="<?php echo esc_attr( $sender_company ); ?>" class="regular-text etyk-sender-field" placeholder="Moja Firma Sp. z o.o." <?php echo $_sd; ?> style="<?php echo $_ss; ?>" /></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Street', 'parcel-selector' ); ?></th>
				<td><input type="text" name="parcselect_label_sender_street" value="<?php echo esc_attr( $sender_street ); ?>" class="regular-text etyk-sender-field" placeholder="ul. Szeroka 5" <?php echo $_sd; ?> style="<?php echo $_ss; ?>" /></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'City', 'parcel-selector' ); ?></th>
				<td><input type="text" name="parcselect_label_sender_city" value="<?php echo esc_attr( $sender_city ); ?>" class="regular-text etyk-sender-field" placeholder="Warszawa" <?php echo $_sd; ?> style="<?php echo $_ss; ?>" /></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Post code', 'parcel-selector' ); ?></th>
				<td><input type="text" name="parcselect_label_sender_postcode" value="<?php echo esc_attr( $sender_post ); ?>" class="regular-text etyk-sender-field" placeholder="00-001" <?php echo $_sd; ?> style="<?php echo $_ss; ?>" /></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Phone', 'parcel-selector' ); ?></th>
				<td>
					<?php $_ps_phone_disp = function_exists( 'parcselect_phone_strip_pl_prefix' ) ? parcselect_phone_strip_pl_prefix( $sender_phone ) : $sender_phone; ?>
					<div style="display:inline-flex;align-items:stretch;border:1px solid #8c8f94;border-radius:4px;overflow:hidden;background:#fff;max-width:25em;">
						<span style="background:#f1f5f9;padding:0 10px;display:flex;align-items:center;font-weight:700;color:#475569;font-size:14px;border-right:1px solid #8c8f94;flex-shrink:0;letter-spacing:0.3px;" aria-hidden="true">+48</span>
						<input type="tel" name="parcselect_label_sender_phone" value="<?php echo esc_attr( $_ps_phone_disp ); ?>" class="etyk-sender-field" placeholder="500 100 200" maxlength="11" inputmode="numeric" autocomplete="tel-national" <?php echo $_sd; ?> style="border:0;outline:0;padding:4px 8px;flex:1;font-size:14px;background:transparent;min-width:0;<?php echo $_ss; ?>" />
					</div>
				</td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Email', 'parcel-selector' ); ?></th>
				<td><input type="email" name="parcselect_label_sender_email" value="<?php echo esc_attr( $sender_email ); ?>" class="regular-text etyk-sender-field" placeholder="office@example.com" <?php echo $_sd; ?> style="<?php echo $_ss; ?>" /></td>
			</tr>
		</table>
		<div style="padding:0 0 16px 200px;">
			<?php if ( $_sender_saved ) : ?>
				<button type="button" id="etyk-sender-edit" class="button">&#x270F; <?php esc_html_e( 'Change', 'parcel-selector' ); ?></button>
				<button type="button" id="etyk-sender-clear" class="button" style="color:#d63638;border-color:#d63638;margin-left:6px;">&#x1F5D1; <?php esc_html_e( 'Clear all', 'parcel-selector' ); ?></button>
			<?php else : ?>
				<button type="button" id="etyk-sender-save" class="button button-primary">&#x2714; <?php esc_html_e( 'Save sender', 'parcel-selector' ); ?></button>
			<?php endif; ?>
			<span id="etyk-sender-status" style="margin-left:10px;font-size:12px;"></span>
		</div>
		</div>

		<!-- DEFAULTS -->
		<h3><?php esc_html_e( 'Default shipment settings', 'parcel-selector' ); ?></h3>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Default parcel size', 'parcel-selector' ); ?></th>
				<td>
					<?php foreach ( Parcselect_Label_API::SIZES as $key => $info ) : ?>
						<label style="display:block;margin-bottom:4px;">
							<input type="radio" name="parcselect_label_default_size" value="<?php echo esc_attr( $key ); ?>" <?php checked( $default_size, $key ); ?> />
							<?php echo esc_html( $info['label'] ); ?>
						</label>
					<?php endforeach; ?>
				</td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Default weight (kg)', 'parcel-selector' ); ?></th>
				<td><input type="number" name="parcselect_label_default_weight" value="<?php echo esc_attr( $default_weight ); ?>" step="0.1" min="0.1" max="25" style="width:80px;" /></td>
			</tr>
		</table>

		<!-- NOTIFICATIONS -->
		<h3><?php esc_html_e( 'Notifications', 'parcel-selector' ); ?></h3>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Send label to email', 'parcel-selector' ); ?></th>
				<td>
					<input type="email" name="parcselect_label_notify_email" value="<?php echo esc_attr( $notify_email ); ?>" class="regular-text" />
					<p class="description"><?php esc_html_e( 'Label PDF + packing list will be sent here after generation.', 'parcel-selector' ); ?></p>
				</td>
			</tr>
		</table>

		<!-- PAYMENT -->
		<h3><?php esc_html_e( 'Payment', 'parcel-selector' ); ?></h3>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Margin (PLN)', 'parcel-selector' ); ?></th>
				<td>
					<input type="number" name="parcselect_label_margin" value="<?php echo esc_attr( $margin ); ?>" step="0.01" min="0" style="width:80px;" />
					<p class="description"><?php esc_html_e( 'Added to base label price, total rounded to .99', 'parcel-selector' ); ?></p>
				</td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Solana wallet', 'parcel-selector' ); ?></th>
				<td>
					<?php if ( ! empty( $sol_wallet ) ) : ?>
						<code><?php echo esc_html( $sol_wallet ); ?></code>
						<p class="description"><?php esc_html_e( 'Read from PS CryptoPay settings.', 'parcel-selector' ); ?></p>
					<?php else : ?>
						<span style="color:#d63638;"><?php esc_html_e( 'Not configured. Set wallet in WooCommerce → Settings → Payments → PS CryptoPay.', 'parcel-selector' ); ?></span>
					<?php endif; ?>
				</td>
			</tr>
		</table>

		<?php submit_button( __( 'Save settings', 'parcel-selector' ) ); ?>
	</form>

	<!-- DIAGNOSTICS -->
	<h3><?php esc_html_e( 'Diagnostics', 'parcel-selector' ); ?></h3>
	<p>
		<button type="button" id="etyk-test-shipping provider" class="button button-secondary"><?php esc_html_e( 'Test Label Service', 'parcel-selector' ); ?></button>
	</p>
	<pre id="etyk-test-results" style="background:#f6f7f7;padding:12px;border:1px solid #ddd;border-radius:4px;max-height:400px;overflow:auto;display:none;font-size:12px;"></pre>

	<?php
	wp_register_script( 'parcselect-label-settings', '', array( 'jquery' ), PARCSELECT_VERSION, true );
	wp_enqueue_script( 'parcselect-label-settings' );
	wp_localize_script( 'parcselect-label-settings', 'parcselectLabelSettings', array(
		'nonce'            => wp_create_nonce( 'parcselect_label_nonce' ),
		'i18n_test_label'  => __( 'Test Label Service', 'parcel-selector' ),
		'i18n_change'      => __( 'Change', 'parcel-selector' ),
		'i18n_saved'       => __( 'Saved', 'parcel-selector' ),
		'i18n_save'        => __( 'Save', 'parcel-selector' ),
		'i18n_save_sender' => __( 'Save sender', 'parcel-selector' ),
		'i18n_clear_all'   => __( 'Clear all', 'parcel-selector' ),
		'i18n_clear_confirm' => __( 'Clear all sender data?', 'parcel-selector' ),
	) );
	wp_add_inline_script( 'parcselect-label-settings', 'jQuery(function($) {
		var L = parcselectLabelSettings;
		$("#etyk-test-shipping provider").on("click", function() {
			var $btn = $(this);
			var $out = $("#etyk-test-results");
			$btn.prop("disabled", true).text("Testing...");
			$out.show().text("Running diagnostics...\n");
			$.post(ajaxurl, {
				action: "ps_label_test_shipping provider",
				nonce: L.nonce
			}, function(res) {
				$btn.prop("disabled", false).text(L.i18n_test_label);
				if (!res.success) { $out.text("ERROR: " + JSON.stringify(res.data)); return; }
				var text = "";
				var data = res.data;
				for (var key in data) {
					if (!data.hasOwnProperty(key)) continue;
					var t = data[key];
					var icon = t.ok ? "\u2705" : "\u274C";
					text += icon + " " + key.toUpperCase() + ": " + t.message + "\n";
					if (t.data && key === "services") { text += "   Services: " + JSON.stringify(t.data, null, 2).substring(0, 500) + "\n"; }
				}
				$out.text(text);
			}).fail(function() {
				$btn.prop("disabled", false).text("Test Label Service");
				$out.text("Request failed \u2014 check browser console.");
			});
		});
		$(document).on("click", ".etyk-dropoff-save", function() {
			var $row = $(this).closest(".etyk-dropoff-row");
			var $input = $row.find(".etyk-dropoff-input");
			var $btn = $(this);
			var $status = $row.find(".etyk-dropoff-status");
			var key = $row.data("key");
			var val = $input.val().trim();
			if (!val) { $input.focus(); return; }
			$btn.prop("disabled", true).text("...");
			$status.text("").css("color", "");
			$.post(ajaxurl, {
				action: "parcselect_label_save_inline",
				nonce: L.nonce,
				options: JSON.stringify({ [key]: val })
			}, function(res) {
				if (res.success) {
					$input.prop("disabled", true).css({ background: "#f0f0f1", color: "#50575e" });
					$btn.replaceWith("<button type=\"button\" class=\"button etyk-dropoff-change\" style=\"margin-left:6px;\">&#x270F; " + L.i18n_change + "</button>");
					$status.text("\u2705 " + L.i18n_saved).css("color", "#00a32a");
					setTimeout(function() { $status.text(""); }, 3000);
				} else {
					$btn.prop("disabled", false).html("&#x2714; " + L.i18n_save);
					$status.text("\u274C " + (res.data || "Error")).css("color", "#d63638");
				}
			}).fail(function() {
				$btn.prop("disabled", false).html("&#x2714; " + L.i18n_save);
				$status.text("\u274C Request failed").css("color", "#d63638");
			});
		});
		$(document).on("click", ".etyk-dropoff-change", function() {
			var $row = $(this).closest(".etyk-dropoff-row");
			var $input = $row.find(".etyk-dropoff-input");
			$input.prop("disabled", false).css({ background: "", color: "" }).focus();
			$(this).replaceWith("<button type=\"button\" class=\"button button-primary etyk-dropoff-save\" style=\"margin-left:6px;\">&#x2714; " + L.i18n_save + "</button>");
		});
		function senderFields() { return $("#etyk-sender-block .etyk-sender-field"); }
		$(document).on("click", "#etyk-sender-save", function() {
			var $btn = $(this), $st = $("#etyk-sender-status");
			var opts = {};
			senderFields().each(function() { var n = $(this).attr("name"), v = $(this).val().trim(); if (n && v) opts[n] = v; });
			if (!opts.ps_label_sender_name) { $("[name=ps_label_sender_name]").focus(); return; }
			$btn.prop("disabled", true).text("...");
			$.post(ajaxurl, {
				action: "parcselect_label_save_inline",
				nonce: L.nonce,
				options: JSON.stringify(opts)
			}, function(res) {
				if (res.success) {
					senderFields().prop("disabled", true).css({ background: "#f0f0f1", color: "#50575e" });
					$btn.replaceWith(
						"<button type=\"button\" id=\"etyk-sender-edit\" class=\"button\">&#x270F; " + L.i18n_change + "</button>"
						+ "<button type=\"button\" id=\"etyk-sender-clear\" class=\"button\" style=\"color:#d63638;border-color:#d63638;margin-left:6px;\">&#x1F5D1; " + L.i18n_clear_all + "</button>"
					);
					$st.text("\u2705 " + L.i18n_saved).css("color", "#00a32a");
					setTimeout(function() { $st.text(""); }, 3000);
				} else {
					$btn.prop("disabled", false).html("&#x2714; " + L.i18n_save_sender);
					$st.text("\u274C " + (res.data || "Error")).css("color", "#d63638");
				}
			});
		});
		$(document).on("click", "#etyk-sender-edit", function() {
			senderFields().prop("disabled", false).css({ background: "", color: "" }).first().focus();
			$(this).replaceWith("<button type=\"button\" id=\"etyk-sender-save\" class=\"button button-primary\">&#x2714; " + L.i18n_save_sender + "</button>");
			$("#etyk-sender-clear").remove();
		});
		$(document).on("click", "#etyk-sender-clear", function() {
			if (!confirm(L.i18n_clear_confirm)) return;
			var keys = {};
			senderFields().each(function() { keys[$(this).attr("name")] = ""; });
			$.post(ajaxurl, {
				action: "parcselect_label_save_inline",
				nonce: L.nonce,
				options: JSON.stringify(keys)
			}, function() { location.reload(); });
		});
	});' );
	?>
	<?php
}
