<?php
/**
 * Template: Banner Designer
 *
 * Full native banner designer rendered locally in PHP. Exchanges only data
 * (JSON) with the Biscotti Cloud API via the authenticated admin-ajax proxy
 * (proxy_action "get-banner" / "save-banner"). No remote markup, no iframe,
 * no remotely-loaded JavaScript — all assets are local (WordPress.org
 * Guideline 8 compliant).
 *
 * Field/data model mirrors the Cloud banner schema exactly so the saved
 * banner stays compatible with the client engine and dashboard (frozen API):
 *   theme: position, layout, primaryColor, backgroundColor, textColor,
 *          buttonStyle, fontFamily, fontSize, showLogo, showFloatingButton,
 *          showGranularView, ethicalUiMode, customCss
 *   texts: title, text, accept, reject, settings, privacyLink
 *   top-level: type, isActive, forceConsent, consentDuration
 *
 * @var array $data JSON data from Cloud API (get-banner response).
 * @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.

// --- Extract banner data with documented defaults (usable editor even when no banner saved yet). ---
$banner   = ( isset( $data['banner'] ) && is_array( $data['banner'] ) ) ? $data['banner'] : array();
$theme    = ( isset( $banner['theme'] ) && is_array( $banner['theme'] ) ) ? $banner['theme'] : array();
$texts_in = ( isset( $banner['texts'] ) && is_array( $banner['texts'] ) ) ? $banner['texts'] : array();

// Texts may be stored localized ({ de:{...}, en:{...} }) or flat ({ title, ... }).
$current_lang = class_exists( 'Biscotti_Language_Bridge' ) ? Biscotti_Language_Bridge::get_current_language() : 'de';
if ( isset( $texts_in[ $current_lang ] ) && is_array( $texts_in[ $current_lang ] ) ) {
	$texts           = $texts_in[ $current_lang ];
	$texts_localized = true;
} elseif ( isset( $texts_in['de'] ) && is_array( $texts_in['de'] ) ) {
	$texts           = $texts_in['de'];
	$texts_localized = true;
} else {
	$texts           = $texts_in;
	$texts_localized = false;
}

$banner_id        = $banner['id'] ?? '';
$banner_type      = $banner['type'] ?? 'OPT_IN';
$is_active        = array_key_exists( 'isActive', $banner ) ? (bool) $banner['isActive'] : true;
$force_consent    = ! empty( $banner['forceConsent'] );
$consent_duration = isset( $banner['consentDuration'] ) ? (string) $banner['consentDuration'] : '180';
// Website-level TCF flag (from get-banner). TCF is per-website, not per-banner.
$tcf_enabled      = ! empty( $data['tcfEnabled'] );

// Theme values.
$primary_color = $theme['primaryColor'] ?? '#9B6B3C';
$bg_color      = $theme['backgroundColor'] ?? '#FFFFFF';
$text_color    = $theme['textColor'] ?? '#333333';
$position      = $theme['position'] ?? 'bottom-center';
$layout        = $theme['layout'] ?? 'box';
$button_style  = $theme['buttonStyle'] ?? 'rounded';
$font_family   = $theme['fontFamily'] ?? '';
$font_size     = isset( $theme['fontSize'] ) ? (string) $theme['fontSize'] : '';
$show_logo            = array_key_exists( 'showLogo', $theme ) ? (bool) $theme['showLogo'] : true;
$show_floating_button = array_key_exists( 'showFloatingButton', $theme ) ? (bool) $theme['showFloatingButton'] : true;
$show_granular_view   = ! empty( $theme['showGranularView'] );
$ethical_ui_mode      = ! empty( $theme['ethicalUiMode'] );
$custom_css           = $theme['customCss'] ?? '';

// Text values.
$txt_title        = $texts['title'] ?? '';
$txt_text         = $texts['text'] ?? ( $texts['description'] ?? '' );
$txt_accept       = $texts['accept'] ?? ( $texts['acceptButton'] ?? '' );
$txt_reject       = $texts['reject'] ?? ( $texts['rejectButton'] ?? '' );
$txt_settings     = $texts['settings'] ?? ( $texts['settingsButton'] ?? '' );
$txt_privacy_link = $texts['privacyLink'] ?? '';

$R = 'Biscotti_Template_Renderer';
?>

<div class="biscotti-page biscotti-page-banner">
	<?php
	$page_title = __( 'Banner Designer', 'biscotti-cmp' );
	include __DIR__ . '/partials/page-header.php';
	?>

	<form id="biscotti-banner-form" class="biscotti-form" data-lang="<?php echo esc_attr( $current_lang ); ?>" data-texts-localized="<?php echo $texts_localized ? '1' : '0'; ?>">

		<!-- Status -->
		<div class="biscotti-banner-status">
			<label class="biscotti-status-toggle">
				<input type="checkbox" id="biscotti-field-banner_active" <?php checked( $is_active ); ?> />
				<strong><?php esc_html_e( 'Banner active', 'biscotti-cmp' ); ?></strong>
			</label>
			<span class="biscotti-status-hint"><?php esc_html_e( 'Enable or disable the consent banner on your site.', 'biscotti-cmp' ); ?></span>
		</div>

		<!-- ============================ DESIGN ============================ -->
		<h2><?php esc_html_e( 'Design', 'biscotti-cmp' ); ?></h2>

		<h3><?php esc_html_e( 'Colors & Style', 'biscotti-cmp' ); ?></h3>
		<table class="form-table" role="presentation">
			<?php
			$R::form_field( 'color', 'banner_primary_color', $primary_color, array( 'label' => __( 'Primary / Accent Color', 'biscotti-cmp' ) ) );
			$R::form_field( 'color', 'banner_bg_color', $bg_color, array( 'label' => __( 'Background Color', 'biscotti-cmp' ) ) );
			$R::form_field( 'color', 'banner_text_color', $text_color, array( 'label' => __( 'Text Color', 'biscotti-cmp' ) ) );
			?>
		</table>

		<h3><?php esc_html_e( 'Position & Layout', 'biscotti-cmp' ); ?></h3>
		<table class="form-table" role="presentation">
			<?php
			$R::form_field(
				'select',
				'banner_position',
				$position,
				array(
					'label'   => __( 'Position', 'biscotti-cmp' ),
					'choices' => array(
						'bottom-center' => __( 'Bottom Center', 'biscotti-cmp' ),
						'bottom-left'   => __( 'Bottom Left', 'biscotti-cmp' ),
						'bottom-right'  => __( 'Bottom Right', 'biscotti-cmp' ),
						'top-center'    => __( 'Top Center', 'biscotti-cmp' ),
						'center'        => __( 'Center (Modal)', 'biscotti-cmp' ),
					),
				)
			);
			$R::form_field(
				'select',
				'banner_layout',
				$layout,
				array(
					'label'   => __( 'Layout', 'biscotti-cmp' ),
					'choices' => array(
						'box'   => __( 'Box', 'biscotti-cmp' ),
						'bar'   => __( 'Bar', 'biscotti-cmp' ),
						'popup' => __( 'Popup', 'biscotti-cmp' ),
					),
				)
			);
			$R::form_field(
				'select',
				'banner_button_style',
				$button_style,
				array(
					'label'   => __( 'Button Style', 'biscotti-cmp' ),
					'choices' => array(
						'rounded' => __( 'Rounded', 'biscotti-cmp' ),
						'pill'    => __( 'Pill', 'biscotti-cmp' ),
						'square'  => __( 'Square', 'biscotti-cmp' ),
					),
				)
			);
			$R::form_field( 'toggle', 'banner_show_logo', $show_logo, array( 'label' => __( 'Show Logo', 'biscotti-cmp' ) ) );
			?>
		</table>

		<h3><?php esc_html_e( 'Typography', 'biscotti-cmp' ); ?></h3>
		<table class="form-table" role="presentation">
			<?php
			$R::form_field(
				'select',
				'banner_font_family',
				$font_family,
				array(
					'label'   => __( 'Font Family', 'biscotti-cmp' ),
					'choices' => array(
						''                                 => __( 'Default (theme font)', 'biscotti-cmp' ),
						'Arial, Helvetica, sans-serif'     => 'Arial',
						'Georgia, serif'                   => 'Georgia',
						'Verdana, Geneva, sans-serif'      => 'Verdana',
						'Tahoma, Geneva, sans-serif'       => 'Tahoma',
						"'Trebuchet MS', sans-serif"       => 'Trebuchet MS',
						"'Times New Roman', serif"         => 'Times New Roman',
						'Inter'                            => 'Inter',
						'Roboto'                           => 'Roboto',
						'Open Sans'                        => 'Open Sans',
						'Lato'                             => 'Lato',
						'Montserrat'                       => 'Montserrat',
						'Poppins'                          => 'Poppins',
						'Nunito'                           => 'Nunito',
						'Source Sans 3'                    => 'Source Sans 3',
						'DM Sans'                          => 'DM Sans',
						'Playfair Display'                 => 'Playfair Display',
					),
				)
			);
			$R::form_field(
				'select',
				'banner_font_size',
				$font_size,
				array(
					'label'   => __( 'Font Size', 'biscotti-cmp' ),
					'choices' => array(
						''   => __( 'Default (14px)', 'biscotti-cmp' ),
						'12' => '12px',
						'13' => '13px',
						'14' => '14px',
						'15' => '15px',
						'16' => '16px',
					),
				)
			);
			?>
		</table>

		<h3><?php esc_html_e( 'Advanced', 'biscotti-cmp' ); ?></h3>
		<table class="form-table" role="presentation">
			<?php
			$R::form_field( 'toggle', 'banner_floating_button', $show_floating_button, array( 'label' => __( 'Floating Button', 'biscotti-cmp' ), 'description' => __( 'Show a persistent button to reopen consent settings.', 'biscotti-cmp' ) ) );
			$R::form_field( 'toggle', 'banner_granular_view', $show_granular_view, array( 'label' => __( 'Granular View', 'biscotti-cmp' ), 'description' => __( 'Show category-level consent options by default.', 'biscotti-cmp' ) ) );
			$R::form_field( 'toggle', 'banner_ethical_ui', $ethical_ui_mode, array( 'label' => __( 'Ethical UI Mode', 'biscotti-cmp' ), 'description' => __( 'Give Accept and Reject equal visual weight.', 'biscotti-cmp' ) ) );
			$R::form_field( 'textarea', 'banner_custom_css', $custom_css, array( 'label' => __( 'Custom CSS', 'biscotti-cmp' ), 'placeholder' => '.biscotti-banner { }' ) );
			?>
		</table>

		<!-- ============================ TEXTS ============================ -->
		<h2><?php esc_html_e( 'Texts', 'biscotti-cmp' ); ?></h2>
		<table class="form-table" role="presentation">
			<?php
			$R::form_field( 'text', 'banner_title', $txt_title, array( 'label' => __( 'Heading', 'biscotti-cmp' ), 'placeholder' => __( 'We value your privacy', 'biscotti-cmp' ) ) );
			$R::form_field( 'textarea', 'banner_text', $txt_text, array( 'label' => __( 'Description', 'biscotti-cmp' ), 'placeholder' => __( 'We use cookies to improve your experience...', 'biscotti-cmp' ) ) );
			$R::form_field( 'text', 'banner_accept', $txt_accept, array( 'label' => __( 'Accept Button', 'biscotti-cmp' ), 'placeholder' => __( 'Accept All', 'biscotti-cmp' ) ) );
			$R::form_field( 'text', 'banner_reject', $txt_reject, array( 'label' => __( 'Reject Button', 'biscotti-cmp' ), 'placeholder' => __( 'Reject All', 'biscotti-cmp' ) ) );
			$R::form_field( 'text', 'banner_settings', $txt_settings, array( 'label' => __( 'Settings Button', 'biscotti-cmp' ), 'placeholder' => __( 'Cookie Settings', 'biscotti-cmp' ) ) );
			$R::form_field( 'text', 'banner_privacy_link', $txt_privacy_link, array( 'label' => __( 'Privacy Policy Link Text', 'biscotti-cmp' ), 'placeholder' => __( 'Privacy Policy', 'biscotti-cmp' ) ) );
			?>
		</table>

		<!-- ============================ BEHAVIOR ============================ -->
		<h2><?php esc_html_e( 'Behavior', 'biscotti-cmp' ); ?></h2>
		<table class="form-table" role="presentation">
			<?php
			$R::form_field(
				'select',
				'banner_type',
				$banner_type,
				array(
					'label'   => __( 'Consent Type', 'biscotti-cmp' ),
					'choices' => array(
						'OPT_IN'  => __( 'Opt-In (GDPR)', 'biscotti-cmp' ),
						'OPT_OUT' => __( 'Opt-Out (CCPA)', 'biscotti-cmp' ),
					),
				)
			);
			$R::form_field(
				'select',
				'banner_consent_duration',
				$consent_duration,
				array(
					'label'   => __( 'Consent Duration', 'biscotti-cmp' ),
					'choices' => array(
						'30'  => __( '30 days', 'biscotti-cmp' ),
						'90'  => __( '90 days', 'biscotti-cmp' ),
						'180' => __( '180 days (standard)', 'biscotti-cmp' ),
						'365' => __( '365 days', 'biscotti-cmp' ),
					),
				)
			);
			$R::form_field( 'toggle', 'banner_force_consent', $force_consent, array( 'label' => __( 'Force Consent', 'biscotti-cmp' ), 'description' => __( 'Block interaction with the site until a choice is made.', 'biscotti-cmp' ) ) );
			$R::form_field( 'toggle', 'banner_tcf_enabled', $tcf_enabled, array( 'label' => __( 'TCF 2.3 (IAB Transparency & Consent Framework)', 'biscotti-cmp' ), 'description' => __( 'Show IAB purposes and the vendor list to visitors. Forces a modal layout and uses the IAB-standard banner texts. Applies to this entire website.', 'biscotti-cmp' ) ) );
			?>
		</table>

		<!-- ============================ PREVIEW ============================ -->
		<h2><?php esc_html_e( 'Live Preview', 'biscotti-cmp' ); ?></h2>
		<div id="biscotti-banner-preview" class="biscotti-banner-preview" aria-live="polite"></div>

		<!-- Save -->
		<p class="submit biscotti-banner-save-row">
			<button type="button" id="biscotti-save-banner" class="button button-primary" data-label="<?php esc_attr_e( 'Save Banner Settings', 'biscotti-cmp' ); ?>">
				<?php esc_html_e( 'Save Banner Settings', 'biscotti-cmp' ); ?>
			</button>
			<span id="biscotti-banner-save-status" class="biscotti-save-status" role="status"></span>
		</p>

		<input type="hidden" id="biscotti-field-banner_id" value="<?php echo esc_attr( $banner_id ); ?>" />
	</form>
</div>
