<?php
/**
 * Options Page Builder - Render Options Page
 *
 * @package OptionsPageBuilder
 * @since 1.0.0
 */

use WP_PowerSuite\Admin\PageHero;

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

/** @var array $page */
/** @var array $values */
/** @var array $fields */
/** @var string $option_name */

$page_slug = $page['slug'] ?? '';
$groups    = [];
$current_gid   = 'general';
$current_label = __( 'General', 'wppowersuite-lite' );
$current_desc  = '';
$has_initial_group = false;

foreach ( $fields as $f ) {
	if ( ! is_array( $f ) || empty( $f['type'] ) ) {
		continue;
	}
	if ( ( $f['type'] ?? '' ) === 'group' ) {
		$has_initial_group = true;
		$current_gid   = sanitize_key( $f['field_id'] ?? $f['name'] ?? $f['id'] ?? 'group_' . count( $groups ) );
		$current_label = $f['label'] ?? __( 'Section', 'wppowersuite-lite' );
		$current_desc  = $f['description'] ?? '';
		$groups[ $current_gid ] = [ 'label' => $current_label, 'description' => $current_desc, 'fields' => [] ];
	} else {
		if ( ! $has_initial_group && empty( $groups ) ) {
			$groups['general'] = [ 'label' => __( 'General', 'wppowersuite-lite' ), 'description' => '', 'fields' => [] ];
			$has_initial_group = true;
		}
		if ( ! isset( $groups[ $current_gid ] ) ) {
			$groups[ $current_gid ] = [ 'label' => $current_label, 'description' => $current_desc, 'fields' => [] ];
		}
		$groups[ $current_gid ]['fields'][] = $f;
	}
}

$groups = array_filter( $groups, fn( $g ) => ! empty( $g['fields'] ) );
$use_section_nav = count( $groups ) >= 2;
$first_section_id = $use_section_nav ? (string) array_key_first( $groups ) : '';

$field_list = [];
foreach ( $groups as $g ) {
	foreach ( $g['fields'] ?? [] as $f ) {
		$fid = $f['field_id'] ?? $f['name'] ?? $f['id'] ?? '';
		if ( $fid ) {
			$ftype = sanitize_key( (string) ( $f['type'] ?? 'text' ) );
			if ( $ftype === 'group' ) {
				continue;
			}
			$field_list[] = [
				'label'    => $f['label'] ?? ucfirst( str_replace( '_', ' ', $fid ) ),
				'id'       => $fid,
				'type'     => $ftype,
				'required' => ! empty( $f['required'] ),
			];
		}
	}
}
$first_field_id = $field_list[0]['id'] ?? 'field_id';
$save_label     = ! empty( $page['save_button'] ) ? $page['save_button'] : __( 'Save Changes', 'wppowersuite-lite' );
$updated_msg    = ! empty( $page['updated_message'] ) ? $page['updated_message'] : __( 'Settings saved.', 'wppowersuite-lite' );
$helper_name    = 'get_' . preg_replace( '/[^a-z0-9_]/', '_', str_replace( '-', '_', $page_slug ) ) . '_option';
$page_icon      = ! empty( $page['icon'] ) ? (string) $page['icon'] : 'dashicons-admin-generic';
$how_to_label   = esc_html__( 'How to use', 'wppowersuite-lite' );
$has_elementor  = defined( 'ELEMENTOR_VERSION' );
$has_bricks     = defined( 'BRICKS_VERSION' );
$has_divi       = defined( 'ET_BUILDER_VERSION' );
$has_beaver     = class_exists( 'FLPageData' );
$shortcode      = '[wpps_opb page="' . $page_slug . '" field="' . $first_field_id . '"]';
$rest_field_url = rest_url( 'wp-powersuite/v1/opb/' . $page_slug . '/' . $first_field_id );
$helper_code    = 'function ' . $helper_name . "( \$key, \$default = '' ) {\n\treturn wpps_opb_get( '" . $page_slug . "', \$key, \$default );\n}\n\n// Usage:\n\$value = " . $helper_name . "( '" . $first_field_id . "' );";
$builtin_code   = "\$value = wpps_opb_get( '" . $page_slug . "', '" . $first_field_id . "' );";
$retrieve_code  = '$values = get_option( \'' . $option_name . '\', [] );' . "\n" . '$my_field = $values[\'' . $first_field_id . '\'] ?? \'\';';
$bricks_tag     = '{wp_powersuite_opb:' . $page_slug . ':' . $first_field_id . '}';
$elementor_key  = $page_slug . ':' . $first_field_id;
?>
<div class="wrap wpps-opb-live-page">
	<hr class="wp-header-end" style="margin:0;padding:0;border:none;height:0;overflow:hidden;">
	<?php
	PageHero::render_for_module(
		[
			'icon'      => $page_icon,
			'title'     => (string) ( $page['page_title'] ?? '' ),
			'tagline'   => (string) ( $page['page_description'] ?? __( 'Configure settings for this page.', 'wppowersuite-lite' ) ),
			'meta_html' => '<button type="button" class="button button-secondary" id="wpps-opb-how-to-use-btn" aria-label="' . esc_attr__( 'How to use these options', 'wppowersuite-lite' ) . '">' . $how_to_label . '</button>',
		]
	);
	?>

	<!-- How to use modal -->
	<div id="wpps-opb-how-to-modal" class="wpps-opb-modal" role="dialog" aria-labelledby="wpps-opb-how-to-modal-title" aria-hidden="true">
		<div class="wpps-opb-modal-backdrop"></div>
		<div class="wpps-opb-modal-content wpps-opb-modal-content-wide">
			<div class="wpps-opb-modal-header">
				<h2 id="wpps-opb-how-to-modal-title"><?php esc_html_e( 'How to use these options', 'wppowersuite-lite' ); ?></h2>
				<button type="button" class="wpps-opb-modal-close" aria-label="<?php esc_attr_e( 'Close', 'wppowersuite-lite' ); ?>">&times;</button>
			</div>
			<div class="wpps-opb-modal-tabs" role="tablist" aria-label="<?php esc_attr_e( 'How to use sections', 'wppowersuite-lite' ); ?>">
				<button type="button" class="wpps-opb-modal-tab is-active" role="tab" aria-selected="true" data-tab="php"><?php esc_html_e( 'PHP & Theme', 'wppowersuite-lite' ); ?></button>
				<button type="button" class="wpps-opb-modal-tab" role="tab" aria-selected="false" data-tab="integrations"><?php esc_html_e( 'Integrations', 'wppowersuite-lite' ); ?></button>
				<button type="button" class="wpps-opb-modal-tab" role="tab" aria-selected="false" data-tab="fields"><?php esc_html_e( 'Fields', 'wppowersuite-lite' ); ?></button>
			</div>
			<div class="wpps-opb-modal-body">
				<div class="wpps-opb-modal-panel" data-panel="php">
					<p class="description wpps-opb-modal-intro"><?php esc_html_e( 'Read saved values in themes, child themes, or custom plugins using the helpers below.', 'wppowersuite-lite' ); ?></p>

					<h3><?php esc_html_e( 'Built-in helper', 'wppowersuite-lite' ); ?></h3>
					<p><?php esc_html_e( 'Use wpps_opb_get() anywhere PHP runs. Pass the page slug, field ID, and an optional default.', 'wppowersuite-lite' ); ?></p>
					<div class="wpps-opb-modal-code-wrap">
						<pre class="wpps-opb-modal-code"><code><?php echo esc_html( $builtin_code ); ?></code></pre>
						<button type="button" class="button button-secondary button-small wpps-opb-modal-copy"><?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?></button>
					</div>

					<h3><?php esc_html_e( 'Theme helper function (recommended)', 'wppowersuite-lite' ); ?></h3>
					<p><?php esc_html_e( 'Add this wrapper to functions.php for shorter template code:', 'wppowersuite-lite' ); ?></p>
					<div class="wpps-opb-modal-code-wrap">
						<pre class="wpps-opb-modal-code"><code><?php echo esc_html( $helper_code ); ?></code></pre>
						<button type="button" class="button button-secondary button-small wpps-opb-modal-copy"><?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?></button>
					</div>

					<h3><?php esc_html_e( 'Retrieve all values', 'wppowersuite-lite' ); ?></h3>
					<p><?php esc_html_e( 'Values are stored in a single WordPress option array:', 'wppowersuite-lite' ); ?> <code><?php echo esc_html( $option_name ); ?></code></p>
					<div class="wpps-opb-modal-code-wrap">
						<pre class="wpps-opb-modal-code"><code><?php echo esc_html( $retrieve_code ); ?></code></pre>
						<button type="button" class="button button-secondary button-small wpps-opb-modal-copy"><?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?></button>
					</div>
				</div>
				<div class="wpps-opb-modal-panel" data-panel="integrations" hidden>
					<p class="description wpps-opb-modal-intro"><?php esc_html_e( 'Output field values in page builders without writing PHP.', 'wppowersuite-lite' ); ?></p>

					<div class="wpps-opb-modal-integration">
						<div class="wpps-opb-modal-integration__head">
							<h3><?php esc_html_e( 'Elementor', 'wppowersuite-lite' ); ?></h3>
							<span class="wpps-opb-modal-badge <?php echo $has_elementor ? 'is-active' : 'is-inactive'; ?>">
								<?php echo $has_elementor ? esc_html__( 'Active', 'wppowersuite-lite' ) : esc_html__( 'Not installed', 'wppowersuite-lite' ); ?>
							</span>
						</div>
						<ol class="wpps-opb-modal-list">
							<li><?php esc_html_e( 'Edit a template or page with Elementor.', 'wppowersuite-lite' ); ?></li>
							<li><?php esc_html_e( 'Click the dynamic tags icon on a heading, text, or HTML widget.', 'wppowersuite-lite' ); ?></li>
							<li><?php esc_html_e( 'Open the WP PowerSuite group and choose PowerSuite Option.', 'wppowersuite-lite' ); ?></li>
							<li><?php esc_html_e( 'Select this page and field from the Option Field dropdown.', 'wppowersuite-lite' ); ?></li>
						</ol>
						<p class="description"><?php esc_html_e( 'Field key for this example:', 'wppowersuite-lite' ); ?> <code><?php echo esc_html( $elementor_key ); ?></code></p>
					</div>

					<div class="wpps-opb-modal-integration">
						<div class="wpps-opb-modal-integration__head">
							<h3><?php esc_html_e( 'Bricks Builder', 'wppowersuite-lite' ); ?></h3>
							<span class="wpps-opb-modal-badge <?php echo $has_bricks ? 'is-active' : 'is-inactive'; ?>">
								<?php echo $has_bricks ? esc_html__( 'Active', 'wppowersuite-lite' ) : esc_html__( 'Not installed', 'wppowersuite-lite' ); ?>
							</span>
						</div>
						<ol class="wpps-opb-modal-list">
							<li><?php esc_html_e( 'Edit a Bricks template and select any text element.', 'wppowersuite-lite' ); ?></li>
							<li><?php esc_html_e( 'Use the dynamic data picker or paste a dynamic tag into the content field.', 'wppowersuite-lite' ); ?></li>
							<li><?php esc_html_e( 'Browse WP PowerSuite tags or paste the tag below.', 'wppowersuite-lite' ); ?></li>
						</ol>
						<div class="wpps-opb-modal-code-wrap">
							<pre class="wpps-opb-modal-code"><code><?php echo esc_html( $bricks_tag ); ?></code></pre>
							<button type="button" class="button button-secondary button-small wpps-opb-modal-copy"><?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?></button>
						</div>
						<p class="description"><?php esc_html_e( 'Format: {wp_powersuite_opb:page_slug:field_id}', 'wppowersuite-lite' ); ?></p>
					</div>

					<div class="wpps-opb-modal-integration">
						<div class="wpps-opb-modal-integration__head">
							<h3><?php esc_html_e( 'Shortcode & Gutenberg', 'wppowersuite-lite' ); ?></h3>
						</div>
						<p><?php esc_html_e( 'Use the shortcode in any content area, HTML module, or the Shortcode block.', 'wppowersuite-lite' ); ?></p>
						<div class="wpps-opb-modal-code-wrap">
							<pre class="wpps-opb-modal-code"><code><?php echo esc_html( $shortcode ); ?></code></pre>
							<button type="button" class="button button-secondary button-small wpps-opb-modal-copy"><?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?></button>
						</div>
						<p class="description"><?php esc_html_e( 'In the block editor, add the PowerSuite Option block and pick a field from the sidebar.', 'wppowersuite-lite' ); ?></p>
						<p class="description"><?php esc_html_e( 'Universal tag format (also works in Bricks, Oxygen, and HTML areas):', 'wppowersuite-lite' ); ?> <code><?php echo esc_html( $bricks_tag ); ?></code></p>
					</div>

					<div class="wpps-opb-modal-integration">
						<div class="wpps-opb-modal-integration__head">
							<h3><?php esc_html_e( 'REST API', 'wppowersuite-lite' ); ?></h3>
						</div>
						<p><?php esc_html_e( 'Read field values over REST. Requires the same admin capability as this settings page.', 'wppowersuite-lite' ); ?></p>
						<div class="wpps-opb-modal-code-wrap">
							<pre class="wpps-opb-modal-code"><code><?php echo esc_html( $rest_field_url ); ?></code></pre>
							<button type="button" class="button button-secondary button-small wpps-opb-modal-copy"><?php esc_html_e( 'Copy', 'wppowersuite-lite' ); ?></button>
						</div>
						<p class="description"><?php esc_html_e( 'List pages: GET /wp-json/wp-powersuite/v1/opb/pages', 'wppowersuite-lite' ); ?></p>
					</div>

					<div class="wpps-opb-modal-integration">
						<div class="wpps-opb-modal-integration__head">
							<h3><?php esc_html_e( 'Divi', 'wppowersuite-lite' ); ?></h3>
							<span class="wpps-opb-modal-badge <?php echo $has_divi ? 'is-active' : 'is-inactive'; ?>">
								<?php echo $has_divi ? esc_html__( 'Active', 'wppowersuite-lite' ) : esc_html__( 'Not installed', 'wppowersuite-lite' ); ?>
							</span>
						</div>
						<p><?php esc_html_e( 'Open dynamic content on any text or URL field and choose WP PowerSuite under custom fields.', 'wppowersuite-lite' ); ?></p>
					</div>

					<div class="wpps-opb-modal-integration">
						<div class="wpps-opb-modal-integration__head">
							<h3><?php esc_html_e( 'Beaver Themer', 'wppowersuite-lite' ); ?></h3>
							<span class="wpps-opb-modal-badge <?php echo $has_beaver ? 'is-active' : 'is-inactive'; ?>">
								<?php echo $has_beaver ? esc_html__( 'Active', 'wppowersuite-lite' ) : esc_html__( 'Not installed', 'wppowersuite-lite' ); ?>
							</span>
						</div>
						<p><?php esc_html_e( 'Use Field Connections and choose WP PowerSuite Options → PowerSuite Option.', 'wppowersuite-lite' ); ?></p>
					</div>

					<div class="wpps-opb-modal-tip">
						<strong><?php esc_html_e( 'Image & URL fields', 'wppowersuite-lite' ); ?></strong>
						<p><?php esc_html_e( 'Set Return Format to URL in the field builder for image/file fields when builders need a direct link.', 'wppowersuite-lite' ); ?></p>
					</div>
				</div>
				<div class="wpps-opb-modal-panel" data-panel="fields" hidden>
					<h3><?php esc_html_e( 'Fields on this page', 'wppowersuite-lite' ); ?></h3>
					<?php if ( empty( $field_list ) ) : ?>
						<p class="description"><?php esc_html_e( 'No fields configured yet.', 'wppowersuite-lite' ); ?></p>
					<?php else : ?>
						<div class="wpps-opb-modal-fields-table-wrap">
						<table class="wpps-opb-modal-fields-table widefat striped">
							<thead>
								<tr>
									<th><?php esc_html_e( 'Label', 'wppowersuite-lite' ); ?></th>
									<th><?php esc_html_e( 'Field ID', 'wppowersuite-lite' ); ?></th>
									<th><?php esc_html_e( 'Type', 'wppowersuite-lite' ); ?></th>
									<th><?php esc_html_e( 'PHP', 'wppowersuite-lite' ); ?></th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $field_list as $fl ) : ?>
									<?php
									$snippet = "wpps_opb_get( '" . $page_slug . "', '" . $fl['id'] . "' )";
									if ( ( $fl['type'] ?? '' ) === 'message' ) {
										$snippet = '—';
									}
									?>
									<tr>
										<td><?php echo esc_html( $fl['label'] ); ?><?php echo ! empty( $fl['required'] ) ? ' <span class="required">*</span>' : ''; ?></td>
										<td><code><?php echo esc_html( $fl['id'] ); ?></code></td>
										<td><?php echo esc_html( ucfirst( (string) ( $fl['type'] ?? 'text' ) ) ); ?></td>
										<td>
											<?php if ( $snippet === '—' ) : ?>
												<?php echo esc_html( $snippet ); ?>
											<?php else : ?>
												<div class="wpps-opb-modal-code-wrap wpps-opb-modal-code-wrap--table">
													<code class="wpps-opb-snippet-code"><?php echo esc_html( $snippet ); ?></code>
													<button type="button" class="button button-link button-small wpps-opb-modal-copy" aria-label="<?php esc_attr_e( 'Copy', 'wppowersuite-lite' ); ?>"><span class="dashicons dashicons-clipboard" aria-hidden="true"></span></button>
												</div>
											<?php endif; ?>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>
	</div>

	<?php if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] === 'true' ) : ?>
		<div class="notice notice-success is-dismissible"><p><?php echo esc_html( $updated_msg ); ?></p></div>
	<?php endif; ?>

	<?php settings_errors( 'wpps_opb_' . sanitize_key( $page_slug ) ); ?>

	<div class="wp-powersuite-settings wpps-opb-live-settings">
		<?php if ( empty( $fields ) ) : ?>
			<div class="wp-powersuite-settings__card card wpps-settings-card--section">
				<p class="description"><?php esc_html_e( 'No fields configured. Go to WP PowerSuite → Options Page Builder to add fields.', 'wppowersuite-lite' ); ?></p>
			</div>
		<?php else : ?>
			<form method="post" action="options.php" class="wpps-opb-page-form">
				<?php settings_fields( 'wpps_opb_' . sanitize_key( $page_slug ) ); ?>

				<?php if ( $use_section_nav ) : ?>
				<div class="wpps-opb-page-layout">
					<nav class="wpps-opb-sidebar-nav" aria-label="<?php esc_attr_e( 'Settings sections', 'wppowersuite-lite' ); ?>">
						<p class="wpps-opb-sidebar-nav__title"><?php esc_html_e( 'Sections', 'wppowersuite-lite' ); ?></p>
						<ul>
							<?php foreach ( $groups as $gid => $g ) : ?>
								<li>
									<a href="#opb-section-<?php echo esc_attr( $gid ); ?>" class="wpps-opb-nav-link<?php echo $gid === $first_section_id ? ' is-active' : ''; ?>" data-section="<?php echo esc_attr( $gid ); ?>">
										<?php echo esc_html( $g['label'] ); ?>
									</a>
								</li>
							<?php endforeach; ?>
						</ul>
					</nav>
					<div class="wpps-opb-page-content">
				<?php endif; ?>

				<?php foreach ( $groups as $gid => $g ) : ?>
					<?php if ( empty( $g['fields'] ) ) {
						continue;
					} ?>
					<div class="wp-powersuite-settings__card card wpps-settings-card--section wpps-opb-section-card<?php echo $use_section_nav && $gid === $first_section_id ? ' is-active' : ( $use_section_nav ? '' : '' ); ?>" id="opb-section-<?php echo esc_attr( $gid ); ?>">
						<h2 class="wp-powersuite-settings__card-title wpps-settings-section-title"><?php echo esc_html( $g['label'] ); ?></h2>
						<?php if ( ! empty( $g['description'] ) ) : ?>
							<p class="wpps-settings-section-desc"><?php echo esc_html( $g['description'] ); ?></p>
						<?php endif; ?>
						<div class="wpps-opb-live-fields">
							<?php foreach ( $g['fields'] as $field ) : ?>
								<?php
								$fid = $field['field_id'] ?? $field['name'] ?? $field['id'] ?? '';
								if ( empty( $fid ) ) {
									continue;
								}
								$ftype  = sanitize_key( $field['type'] ?? 'text' );
								$fname  = $option_name . '[' . esc_attr( $fid ) . ']';
								$fval   = array_key_exists( $fid, $values ) ? $values[ $fid ] : ( $field['default'] ?? '' );
								$flabel = $field['label'] ?? ucfirst( str_replace( '_', ' ', $fid ) );
								$width  = sanitize_key( $field['width'] ?? 'full' );
								if ( ! in_array( $width, [ 'full', '1-2', '1-3', '2-3' ], true ) ) {
									$width = 'full';
								}
								if ( in_array( $ftype, [ 'wysiwyg', 'image', 'file', 'gallery', 'message', 'link', 'repeater' ], true ) ) {
									$width = 'full';
								}
								$cb_label       = trim( (string) ( $field['checkbox_label'] ?? '' ) );
								$hide_top_label = $ftype === 'checkbox' && $cb_label !== '';
								$is_visible     = wpps_opb_field_is_visible( $field, $values, $fields );
								$cond_attrs     = wpps_opb_field_conditional_attrs( $field, $fields );
								$extra_class    = ! empty( $field['css_class'] ) ? (string) $field['css_class'] : '';
								$field_classes  = 'wpps-opb-live-field wpps-opb-live-field--' . $width
									. ( $hide_top_label ? ' wpps-opb-live-field--checkbox-inline' : '' )
									. ( ! $is_visible ? ' wpps-opb-live-field--hidden' : '' )
									. ( $extra_class !== '' ? ' ' . $extra_class : '' );
								?>
								<div class="<?php echo esc_attr( $field_classes ); ?>"<?php
								foreach ( $cond_attrs as $attr_key => $attr_val ) {
									echo ' ' . esc_attr( $attr_key ) . '="' . esc_attr( $attr_val ) . '"';
								}
								?>>
									<?php if ( ! $hide_top_label ) : ?>
									<div class="wpps-opb-live-field__label">
										<label for="<?php echo esc_attr( $fid ); ?>" id="<?php echo esc_attr( $fid ); ?>-label">
											<?php echo esc_html( $flabel ); ?>
											<?php if ( ! empty( $field['required'] ) ) : ?>
												<span class="required">*</span>
											<?php endif; ?>
											<?php $this->renderFieldDescriptionTooltip( $field['description'] ?? '' ); ?>
										</label>
									</div>
									<?php endif; ?>
									<div class="wpps-opb-live-field__control">
										<?php
										if ( $ftype === 'message' ) {
											$this->renderField( $field, '', '' );
										} else {
											$this->renderField( $field, $fname, $fval );
										}
										?>
										<?php if ( $hide_top_label ) : ?>
											<?php $this->renderFieldDescriptionTooltip( $field['description'] ?? '' ); ?>
										<?php endif; ?>
									</div>
								</div>
							<?php endforeach; ?>
						</div>
					</div>
				<?php endforeach; ?>

				<?php if ( $use_section_nav ) : ?>
					</div>
				</div>
				<?php endif; ?>

				<p class="submit wpps-opb-page-actions">
					<button type="reset" class="button button-secondary"><?php esc_html_e( 'Discard changes', 'wppowersuite-lite' ); ?></button>
					<button type="submit" class="button button-primary"><?php echo esc_html( $save_label ); ?></button>
				</p>
			</form>
		<?php endif; ?>
	</div>
</div>
