<?php
/**
 * PS Checkout — Widget injection PHP layers 1-4 + helper functions.
 *
 * Layer 1: woocommerce_after_shipping_rate
 * Layer 2: woocommerce_review_order_after_shipping
 * Layer 3: woocommerce_cart_totals_after_shipping
 * Layer 4: woocommerce_update_order_review_fragments (AJAX)
 *
 * @package ParcelSelector
 */

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

// ===========================================================================
// Hooks — PHP Layers 1-4
// ===========================================================================

add_action( 'woocommerce_after_shipping_rate',           'parcselect_render_checkout_widget', 10, 2 );
add_action( 'woocommerce_review_order_after_shipping',   'parcselect_render_checkout_widget_fallback' );
add_action( 'woocommerce_cart_totals_after_shipping',    'parcselect_render_checkout_widget_fallback' );
add_filter( 'woocommerce_update_order_review_fragments', 'parcselect_inject_widget_fragment' );
add_action( 'wp_footer',                                 'parcselect_inject_widget_config_json' );
add_action( 'wp_footer',                                 'parcselect_render_popup_container' );

// ===========================================================================
// Helper: reset rendered flag (used by fragment layer)
// ===========================================================================
if ( ! function_exists( 'parcselect_reset_widget_flag' ) ) {
function parcselect_reset_widget_flag() {
	parcselect_render_checkout_widget( null, null, true );
	parcselect_widget_already_rendered( 'reset' );
}
}

// ===========================================================================
// parcselect_build_widget_html() — builds widget HTML as a string
// Used by PHP layers AND injected as JSON for JS layers 5-8
// ===========================================================================
if ( ! function_exists( 'parcselect_build_widget_html' ) ) {
function parcselect_build_widget_html( $locker_name = '', $locker_city = '', $locker_address = '', $country = '', $context = 'checkout' ) {

	if ( empty( $country ) ) {
		$country = get_option( 'parcselect_default_country', 'pl' );
	}

	$engine = function_exists( 'parcselect_map_engine' ) ? parcselect_map_engine() : 'classic';
	$nonce  = wp_create_nonce( 'parcselect_ajax_nonce' );
	$html   = '<div class="ps-selector-widget ps-widget-' . esc_attr( $context ) . '" data-ps-widget="1" data-ps-nonce="' . esc_attr( $nonce ) . '" style="margin-top:10px;">';

	if ( ! empty( $locker_name ) ) {
		// ── Locker selected — show confirmation card ───────────────────────
		$flag = function_exists( 'parcselect_get_country_flag' ) ? parcselect_get_country_flag( $country ) : '';
		$map  = function_exists( 'parcselect_get_country_names_map' ) ? parcselect_get_country_names_map() : array();
		$cn   = isset( $map[ strtolower( $country ) ] ) ? $map[ strtolower( $country ) ] : strtoupper( $country );

		$html .= '<div class="ps-selected-locker" style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;padding:14px 16px;">';
		$html .= '<p style="margin:0 0 4px;font-weight:700;color:#166534;font-size:14px;">&#x2705; ' . esc_html( $locker_name ) . '</p>';

		if ( $locker_address ) {
			$html .= '<p style="margin:1px 0;font-size:12px;color:#444;">' . esc_html( $locker_address ) . '</p>';
		}
		if ( $locker_city ) {
			$html .= '<p style="margin:1px 0;font-size:12px;color:#444;">' . esc_html( $locker_city ) . '</p>';
		}
		if ( $cn ) {
			$html .= '<p style="margin:4px 0 0;font-size:11px;color:#666;">' . $flag . ' ' . esc_html( $cn ) . '</p>';
		}

		$html .= '<button type="button" class="ps-open-map ps-change-locker button"'
			. ' data-engine="' . esc_attr( $engine ) . '"'
			. ' data-country="' . esc_attr( strtolower( $country ) ) . '"'
			. ' aria-label="' . esc_attr__( 'Change selected parcel locker', 'parcel-selector' ) . '"'
			. ' style="margin-top:8px;width:100%;height:36px;font-size:12px;">'
			. '&#x1F504; ' . esc_html__( 'Change locker', 'parcel-selector' )
			. '</button>';
		$html .= '</div>';

	} else {
		// ── No locker yet — show primary "Select" button ──────────────────
		$html .= '<button type="button" class="ps-open-map button alt ps-select-btn"'
			. ' data-engine="' . esc_attr( $engine ) . '"'
			. ' data-country="' . esc_attr( strtolower( $country ) ) . '"'
			. ' aria-label="' . esc_attr__( 'Open map to select a parcel locker or pickup point', 'parcel-selector' ) . '"'
			. ' style="width:100%;height:44px;font-size:14px;font-weight:600;">'
			. '&#x1F4CD; ' . esc_html__( 'Select locker', 'parcel-selector' )
			. '</button>';
	}

	// ── Manual ID fallback ─────────────────────────────────────────────────
	$label_show = esc_attr__( "Can't see the map? Enter locker ID manually", 'parcel-selector' );
	$label_hide = esc_attr__( 'Hide manual entry', 'parcel-selector' );
	$html .= '<div class="ps-manual-fallback" style="margin-top:8px;font-size:12px;text-align:center;">';
	$html .= '<a href="#" class="ps-toggle-manual"'
		. ' data-label-show="' . $label_show . '"'
		. ' data-label-hide="' . $label_hide . '"'
		. ' style="color:#888;text-decoration:underline;cursor:pointer;">'
		. esc_html__( "Can't see the map? Enter locker ID manually", 'parcel-selector' ) . '</a>';
	$html .= '<div class="ps-manual-input-wrapper" style="display:none;margin-top:10px;padding:12px;background:#f9fafb;border-radius:8px;border:1px solid #e5e7eb;text-align:left;">';
	$html .= '<label style="display:block;margin-bottom:5px;font-size:11px;color:#555;font-weight:600;">'
		. esc_html__( 'Locker ID (e.g. WAW01A, KRA02B)', 'parcel-selector' ) . '</label>';
	$html .= '<div style="display:flex;gap:6px;">';
	$html .= '<input type="search" class="ps-manual-id" autocomplete="off" autocorrect="off" autocapitalize="characters" spellcheck="false"'
		. ' placeholder="' . esc_attr__( 'e.g. WAW01A', 'parcel-selector' ) . '"'
		. ' style="flex:1;min-width:0;height:38px;padding:0 10px;border:1px solid #d1d5db;border-radius:6px;font-size:14px;font-family:monospace;letter-spacing:1px;text-transform:uppercase;">';
	$html .= '<button type="button" class="ps-save-manual button alt"'
		. ' style="height:38px;padding:0 14px;font-size:13px;font-weight:600;white-space:nowrap;flex-shrink:0;">'
		. esc_html__( 'Confirm', 'parcel-selector' ) . '</button>';
	$html .= '</div>';
	$html .= '<div class="ps-manual-msg" style="display:none;margin-top:6px;font-size:11px;"></div>';
	$html .= '<p style="margin:6px 0 0;font-size:10px;color:#999;">'
		. esc_html__( 'You can find the locker ID on the InPost website or on the locker door.', 'parcel-selector' )
		. '</p>';
	$html .= '</div></div>';

	$html .= '</div>'; // .ps-selector-widget

	return $html;
}
}

// ===========================================================================
// PHP LAYER 1 — woocommerce_after_shipping_rate
// ===========================================================================
if ( ! function_exists( 'parcselect_render_checkout_widget' ) ) {
function parcselect_render_checkout_widget( $rate, $index, $reset = false ) {
	static $rendered = false;

	if ( $reset ) { $rendered = false; return; }
	if ( $rendered ) { return; }

	if ( ! function_exists( 'WC' ) || ! WC()->session ) { return; }

	if ( ! is_object( $rate ) || false === strpos( $rate->get_method_id(), 'parcselect_inpost_paczkomat' ) ) {
		return;
	}

	$rendered = true;
	parcselect_echo_widget();
}
}

// ===========================================================================
// PHP LAYERS 2 + 3 — Fallback hooks
// ===========================================================================
if ( ! function_exists( 'parcselect_render_checkout_widget_fallback' ) ) {
function parcselect_render_checkout_widget_fallback() {
	if ( ! function_exists( 'WC' ) || ! WC()->session ) { return; }

	$chosen = WC()->session->get( 'chosen_shipping_methods', array() );
	if ( ! is_array( $chosen ) ) { return; }

	$is_ps = false;
	foreach ( $chosen as $m ) {
		if ( false !== strpos( $m, 'parcselect_inpost_paczkomat' ) ) {
			$is_ps = true;
			break;
		}
	}

	if ( ! $is_ps ) { return; }
	if ( parcselect_widget_already_rendered() ) { return; }

	parcselect_echo_widget();
}
}

if ( ! function_exists( 'parcselect_widget_already_rendered' ) ) {
function parcselect_widget_already_rendered( $mark = false ) {
	static $done = false;
	if ( 'reset' === $mark ) { $done = false; }
	elseif ( $mark ) { $done = true; }
	return $done;
}
}

if ( ! function_exists( 'parcselect_echo_widget' ) ) {
function parcselect_echo_widget() {
	if ( ! function_exists( 'WC' ) || ! WC()->session ) { return; }
	parcselect_widget_already_rendered( true ); // Mark rendered so fallback layers (2+3) skip

	$locker_name    = (string) WC()->session->get( 'parcselect_locker_name',    '' );
	$locker_city    = (string) WC()->session->get( 'parcselect_locker_city',    '' );
	$locker_address = (string) WC()->session->get( 'parcselect_locker_address', '' );
	$country        = (string) WC()->session->get( 'parcselect_locker_country', get_option( 'parcselect_default_country', 'pl' ) );

	echo wp_kses_post( parcselect_build_widget_html( $locker_name, $locker_city, $locker_address, $country ) );
}
}

// ===========================================================================
// PHP LAYER 4 — AJAX fragment (woocommerce_update_order_review_fragments)
// ===========================================================================
if ( ! function_exists( 'parcselect_inject_widget_fragment' ) ) {
function parcselect_inject_widget_fragment( $fragments ) {
	if ( ! function_exists( 'WC' ) || ! WC()->session ) { return $fragments; }

	$chosen = WC()->session->get( 'chosen_shipping_methods', array() );
	$is_ps  = false;
	if ( is_array( $chosen ) ) {
		foreach ( $chosen as $m ) {
			if ( false !== strpos( $m, 'parcselect_inpost_paczkomat' ) ) {
				$is_ps = true;
				break;
			}
		}
	}

	parcselect_reset_widget_flag();

	if ( $is_ps ) {
		$locker_name    = (string) WC()->session->get( 'parcselect_locker_name',    '' );
		$locker_city    = (string) WC()->session->get( 'parcselect_locker_city',    '' );
		$locker_address = (string) WC()->session->get( 'parcselect_locker_address', '' );
		$country        = (string) WC()->session->get( 'parcselect_locker_country', get_option( 'parcselect_default_country', 'pl' ) );

		$fragments['div.ps-selector-widget'] = parcselect_build_widget_html( $locker_name, $locker_city, $locker_address, $country );
	}

	return $fragments;
}
}

// ===========================================================================
// JSON config for JS layers 5-8 (injected to footer)
// Contains pre-rendered button HTML so JS can inject without PHP callback
// ===========================================================================
if ( ! function_exists( 'parcselect_inject_widget_config_json' ) ) {
function parcselect_inject_widget_config_json() {
	if ( ! function_exists( 'parcselect_is_checkout_or_cart' ) || ! parcselect_is_checkout_or_cart() ) { return; }

	$country = '';
	if ( function_exists( 'WC' ) && WC()->session ) {
		$country = (string) WC()->session->get( 'parcselect_locker_country', '' );
	}
	if ( empty( $country ) ) {
		$country = get_option( 'parcselect_default_country', 'pl' );
	}

	$btn_html = parcselect_build_widget_html( '', '', '', $country );

	$config = array(
		'methodId' => 'parcselect_inpost_paczkomat',
		'btnHtml'  => $btn_html,
		'engine'   => function_exists( 'parcselect_map_engine' ) ? parcselect_map_engine() : 'classic',
		'country'  => strtolower( $country ),
		'ajaxUrl'  => admin_url( 'admin-ajax.php' ),
		'nonce'    => wp_create_nonce( 'parcselect_ajax_nonce' ),
	);

	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- wp_json_encode() inside JSON script tag, not HTML context.
	echo '<script id="ps-widget-config" type="application/json">'
		. wp_json_encode( $config )
		. '</script>' . "\n";
}
}

// ===========================================================================
// Popup root — required in footer for both map engines
// ===========================================================================
if ( ! function_exists( 'parcselect_render_popup_container' ) ) {
function parcselect_render_popup_container() {
	if ( ! function_exists( 'parcselect_is_checkout_or_cart' ) || ! parcselect_is_checkout_or_cart() ) { return; }
	echo '<div id="ps-popup-root"></div>' . "\n";
}
}
