<?php
/**
 * Warstwa 13: Geolocation Preload (Ochrona Pustego Koszyka w Multistep Checkout)
 *
 * @package ParcelSelector
 */

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

if ( ! class_exists( 'Parcselect_Geo_Preload' ) ) {
class Parcselect_Geo_Preload {

	public function __construct() {
		add_action( 'template_redirect', array( $this, 'force_default_country_on_checkout' ), 10 );
		add_filter( 'parcselect_frontend_config', array( $this, 'inject_geo_flag' ) );
	}

	public function force_default_country_on_checkout() {
		if ( ! function_exists( 'is_checkout' ) || ! function_exists( 'WC' ) ) {
			return;
		}

		if ( ! is_checkout() || is_wc_endpoint_url( 'order-pay' ) || is_wc_endpoint_url( 'order-received' ) ) {
			return;
		}

		$customer = WC()->customer;
		if ( ! $customer ) {
			return;
		}

		$shipping_country = $customer->get_shipping_country();
		$billing_country  = $customer->get_billing_country();

		// Guard: only force once per session to avoid repeated DB writes
		$already_forced = WC()->session ? WC()->session->get( 'parcselect_geo_forced', false ) : false;

		if ( empty( $shipping_country ) && empty( $billing_country ) && ! $already_forced ) {
			$default_country = strtoupper( get_option( 'parcselect_default_country', 'pl' ) );

			$customer->set_shipping_country( $default_country );
			$customer->set_billing_country( $default_country );
			$customer->save();

			if ( WC()->session ) {
				WC()->session->set( 'parcselect_geo_forced', true );
				WC()->session->set( 'parcselect_layer13_triggered', true );
			}
		}
	}

	public function inject_geo_flag( $config ) {
		if ( function_exists( 'WC' ) && WC()->session ) {
			$geoForced = WC()->session->get( 'parcselect_layer13_triggered', false );

			if ( $geoForced ) {
				WC()->session->set( 'parcselect_layer13_triggered', false );
			}

			if ( ! isset( $config['diagnostics'] ) ) {
				$config['diagnostics'] = array();
			}

			$config['diagnostics']['geoPreloadTriggered'] = $geoForced;
		}

		return $config;
	}
}

new Parcselect_Geo_Preload();
}
