<?php
/**
 * Template: Jurisdiction & Targeting (native)
 *
 * Lets the operator set the primary jurisdiction, target audience, target region
 * and document language. Jurisdiction/audience/language persist on the legal
 * entity (save-legal-entity); the target region persists on the website
 * (save-settings). A banner-model hint is derived from the selected jurisdiction.
 *
 * @var array $data get-legal-wizard-data response: { legalEntity:{...}|null, jurisdictions:[...], targetRegion }
 * @package Biscotti_CMP
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template is included inside Biscotti_Admin::render_dynamic_page(); these are function-scoped locals, not globals.

$page_title = __( 'Jurisdiction & Targeting', 'biscotti-cmp' );
include __DIR__ . '/partials/page-header.php';

if ( null === $data ) :
	include __DIR__ . '/partials/loading-state.php';
	return;
endif;

$e             = ( isset( $data['legalEntity'] ) && is_array( $data['legalEntity'] ) ) ? $data['legalEntity'] : array();
$jurisdictions = ( isset( $data['jurisdictions'] ) && is_array( $data['jurisdictions'] ) ) ? $data['jurisdictions'] : array();
$cur_jur       = isset( $e['jurisdiction'] ) ? (string) $e['jurisdiction'] : '';
$cur_audience  = isset( $e['targetAudience'] ) ? (string) $e['targetAudience'] : '';
$cur_doc_lang  = isset( $e['documentLanguageOverride'] ) ? (string) $e['documentLanguageOverride'] : '';
$cur_region    = isset( $data['targetRegion'] ) ? (string) $data['targetRegion'] : '';

$region_labels = array(
	'europe'        => __( 'Europe & UK', 'biscotti-cmp' ),
	'north_america' => __( 'North America', 'biscotti-cmp' ),
	'south_america' => __( 'Latin America', 'biscotti-cmp' ),
	'asia'          => __( 'Asia-Pacific', 'biscotti-cmp' ),
	'africa'        => __( 'Africa', 'biscotti-cmp' ),
	'middle_east'   => __( 'Middle East', 'biscotti-cmp' ),
	'oceania'       => __( 'Oceania', 'biscotti-cmp' ),
	'eurasia'       => __( 'Eurasia', 'biscotti-cmp' ),
	'other'         => __( 'Other', 'biscotti-cmp' ),
);
$region_order = array( 'europe', 'north_america', 'south_america', 'asia', 'africa', 'middle_east', 'oceania', 'eurasia', 'other' );

$grouped   = array();
$jur_models = array();
foreach ( $jurisdictions as $j ) {
	$r = isset( $j['region'] ) ? $j['region'] : 'other';
	$grouped[ $r ][] = $j;
	if ( isset( $j['code'] ) ) {
		$jur_models[ $j['code'] ] = isset( $j['consentModel'] ) ? $j['consentModel'] : '';
	}
}

$doc_languages = array( '' => '— ' . __( 'Auto', 'biscotti-cmp' ) . ' —' );
if ( class_exists( 'Biscotti_Languages' ) ) {
	foreach ( Biscotti_Languages::endonyms() as $bsc_dl_code => $bsc_dl_name ) {
		$doc_languages[ $bsc_dl_code ] = $bsc_dl_name;
	}
} else {
	$doc_languages['de'] = 'Deutsch';
	$doc_languages['en'] = 'English';
}

// Target region now uses the SAME server-provided jurisdiction list as the
// primary jurisdiction (real jurisdiction_configs codes, e.g. DE / US_TX), so
// US states like Texas are selectable and the saved value always resolves on
// the server. No more hand-maintained 5-item list with codes the API rejected.
?>

<div class="biscotti-page biscotti-page-jurisdiction" id="biscotti-jt">
	<div class="biscotti-card">
		<h3>🌍 <?php esc_html_e( 'Jurisdiction & Targeting', 'biscotti-cmp' ); ?></h3>
		<p class="description"><?php echo esc_html( sprintf( /* translators: %d count */ __( 'Set your primary legal jurisdiction and audience. %d jurisdictions available.', 'biscotti-cmp' ), count( $jurisdictions ) ) ); ?></p>

		<div class="biscotti-lw-grid-2">
			<p class="biscotti-form-row"><label for="jt-jurisdiction"><?php esc_html_e( 'Primary Jurisdiction', 'biscotti-cmp' ); ?> *</label>
				<select id="jt-jurisdiction" class="biscotti-svc-input">
					<option value="">— <?php esc_html_e( 'Select', 'biscotti-cmp' ); ?> —</option>
					<?php
					foreach ( $region_order as $rk ) :
						if ( empty( $grouped[ $rk ] ) ) {
							continue;
						}
						$rl = isset( $region_labels[ $rk ] ) ? $region_labels[ $rk ] : $rk;
						?>
						<optgroup label="<?php echo esc_attr( $rl . ' (' . count( $grouped[ $rk ] ) . ')' ); ?>">
							<?php foreach ( $grouped[ $rk ] as $j ) :
								$suffix = ! empty( $j['framework'] ) ? ' (' . $j['framework'] . ')' : '';
								?>
								<option value="<?php echo esc_attr( $j['code'] ); ?>" <?php selected( $cur_jur, $j['code'] ); ?>><?php echo esc_html( $j['name'] . $suffix ); ?></option>
							<?php endforeach; ?>
						</optgroup>
					<?php endforeach; ?>
				</select>
			</p>
			<p class="biscotti-form-row"><label for="jt-targetAudience"><?php esc_html_e( 'Target Audience', 'biscotti-cmp' ); ?></label>
				<select id="jt-targetAudience" class="biscotti-svc-input">
					<option value="">— <?php esc_html_e( 'Select', 'biscotti-cmp' ); ?> —</option>
					<option value="B2C" <?php selected( $cur_audience, 'B2C' ); ?>><?php esc_html_e( 'Consumers (B2C)', 'biscotti-cmp' ); ?></option>
					<option value="B2B" <?php selected( $cur_audience, 'B2B' ); ?>><?php esc_html_e( 'Businesses (B2B)', 'biscotti-cmp' ); ?></option>
					<option value="B2B2C" <?php selected( $cur_audience, 'B2B2C' ); ?>><?php esc_html_e( 'Both (B2C + B2B)', 'biscotti-cmp' ); ?></option>
				</select>
			</p>
		</div>

		<div class="biscotti-lw-grid-2">
			<p class="biscotti-form-row"><label for="jt-targetRegion"><?php esc_html_e( 'Target Region', 'biscotti-cmp' ); ?></label>
				<select id="jt-targetRegion" class="biscotti-svc-input">
					<option value=""><?php esc_html_e( 'Auto-detect', 'biscotti-cmp' ); ?></option>
					<?php
					foreach ( $region_order as $rk ) :
						if ( empty( $grouped[ $rk ] ) ) {
							continue;
						}
						$rl = isset( $region_labels[ $rk ] ) ? $region_labels[ $rk ] : $rk;
						?>
						<optgroup label="<?php echo esc_attr( $rl . ' (' . count( $grouped[ $rk ] ) . ')' ); ?>">
							<?php foreach ( $grouped[ $rk ] as $j ) :
								$suffix = ! empty( $j['framework'] ) ? ' (' . $j['framework'] . ')' : '';
								?>
								<option value="<?php echo esc_attr( $j['code'] ); ?>" <?php selected( $cur_region, $j['code'] ); ?>><?php echo esc_html( $j['name'] . $suffix ); ?></option>
							<?php endforeach; ?>
						</optgroup>
					<?php endforeach; ?>
				</select>
			</p>
			<p class="biscotti-form-row"><label for="jt-documentLang"><?php esc_html_e( 'Document Language', 'biscotti-cmp' ); ?></label>
				<select id="jt-documentLang" class="biscotti-svc-input">
					<?php foreach ( $doc_languages as $lv => $ll ) : ?>
						<option value="<?php echo esc_attr( $lv ); ?>" <?php selected( $cur_doc_lang, $lv ); ?>><?php echo esc_html( $ll ); ?></option>
					<?php endforeach; ?>
				</select>
			</p>
		</div>

		<div class="biscotti-jt-hint">
			<?php esc_html_e( 'Consent model for the selected jurisdiction:', 'biscotti-cmp' ); ?>
			<span id="jt-banner-model" class="biscotti-pill biscotti-pill-gray">—</span>
		</div>

		<p class="submit">
			<button type="button" id="jt-save" class="button button-primary"><?php esc_html_e( 'Save', 'biscotti-cmp' ); ?></button>
			<span id="jt-status" class="biscotti-save-status" role="status"></span>
		</p>
	</div>

	<script type="application/json" id="biscotti-jt-models"><?php echo wp_json_encode( $jur_models ); ?></script>
</div>
