<?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', 'wp-powersuite' );
$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', 'wp-powersuite' );
		$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', 'wp-powersuite' ), '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', 'wp-powersuite' );
$updated_msg    = ! empty( $page['updated_message'] ) ? $page['updated_message'] : __( 'Settings saved.', 'wp-powersuite' );
$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', 'wp-powersuite' );
$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.', 'wp-powersuite' ) ),
			'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', 'wp-powersuite' ) . '">' . $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', 'wp-powersuite' ); ?></h2>
				<button type="button" class="wpps-opb-modal-close" aria-label="<?php esc_attr_e( 'Close', 'wp-powersuite' ); ?>">&times;</button>
			</div>
			<div class="wpps-opb-modal-tabs" role="tablist" aria-label="<?php esc_attr_e( 'How to use sections', 'wp-powersuite' ); ?>">
				<button type="button" class="wpps-opb-modal-tab is-active" role="tab" aria-selected="true" data-tab="php"><?php esc_html_e( 'PHP & Theme', 'wp-powersuite' ); ?></button>
				<button type="button" class="wpps-opb-modal-tab" role="tab" aria-selected="false" data-tab="integrations"><?php esc_html_e( 'Integrations', 'wp-powersuite' ); ?></button>
				<button type="button" class="wpps-opb-modal-tab" role="tab" aria-selected="false" data-tab="fields"><?php esc_html_e( 'Fields', 'wp-powersuite' ); ?></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.', 'wp-powersuite' ); ?></p>

					<h3><?php esc_html_e( 'Built-in helper', 'wp-powersuite' ); ?></h3>
					<p><?php esc_html_e( 'Use wpps_opb_get() anywhere PHP runs. Pass the page slug, field ID, and an optional default.', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></button>
					</div>

					<h3><?php esc_html_e( 'Theme helper function (recommended)', 'wp-powersuite' ); ?></h3>
					<p><?php esc_html_e( 'Add this wrapper to functions.php for shorter template code:', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></button>
					</div>

					<h3><?php esc_html_e( 'Retrieve all values', 'wp-powersuite' ); ?></h3>
					<p><?php esc_html_e( 'Values are stored in a single WordPress option array:', 'wp-powersuite' ); ?> <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', 'wp-powersuite' ); ?></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.', 'wp-powersuite' ); ?></p>

					<div class="wpps-opb-modal-integration">
						<div class="wpps-opb-modal-integration__head">
							<h3><?php esc_html_e( 'Elementor', 'wp-powersuite' ); ?></h3>
							<span class="wpps-opb-modal-badge <?php echo $has_elementor ? 'is-active' : 'is-inactive'; ?>">
								<?php echo $has_elementor ? esc_html__( 'Active', 'wp-powersuite' ) : esc_html__( 'Not installed', 'wp-powersuite' ); ?>
							</span>
						</div>
						<ol class="wpps-opb-modal-list">
							<li><?php esc_html_e( 'Edit a template or page with Elementor.', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Click the dynamic tags icon on a heading, text, or HTML widget.', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Open the WP PowerSuite group and choose PowerSuite Option.', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Select this page and field from the Option Field dropdown.', 'wp-powersuite' ); ?></li>
						</ol>
						<p class="description"><?php esc_html_e( 'Field key for this example:', 'wp-powersuite' ); ?> <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', 'wp-powersuite' ); ?></h3>
							<span class="wpps-opb-modal-badge <?php echo $has_bricks ? 'is-active' : 'is-inactive'; ?>">
								<?php echo $has_bricks ? esc_html__( 'Active', 'wp-powersuite' ) : esc_html__( 'Not installed', 'wp-powersuite' ); ?>
							</span>
						</div>
						<ol class="wpps-opb-modal-list">
							<li><?php esc_html_e( 'Edit a Bricks template and select any text element.', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Use the dynamic data picker or paste a dynamic tag into the content field.', 'wp-powersuite' ); ?></li>
							<li><?php esc_html_e( 'Browse WP PowerSuite tags or paste the tag below.', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></button>
						</div>
						<p class="description"><?php esc_html_e( 'Format: {wp_powersuite_opb:page_slug:field_id}', 'wp-powersuite' ); ?></p>
					</div>

					<div class="wpps-opb-modal-integration">
						<div class="wpps-opb-modal-integration__head">
							<h3><?php esc_html_e( 'Shortcode & Gutenberg', 'wp-powersuite' ); ?></h3>
						</div>
						<p><?php esc_html_e( 'Use the shortcode in any content area, HTML module, or the Shortcode block.', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></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.', 'wp-powersuite' ); ?></p>
						<p class="description"><?php esc_html_e( 'Universal tag format (also works in Bricks, Oxygen, and HTML areas):', 'wp-powersuite' ); ?> <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', 'wp-powersuite' ); ?></h3>
						</div>
						<p><?php esc_html_e( 'Read field values over REST. Requires the same admin capability as this settings page.', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></button>
						</div>
						<p class="description"><?php esc_html_e( 'List pages: GET /wp-json/wp-powersuite/v1/opb/pages', 'wp-powersuite' ); ?></p>
					</div>

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

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

					<div class="wpps-opb-modal-tip">
						<strong><?php esc_html_e( 'Image & URL fields', 'wp-powersuite' ); ?></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.', 'wp-powersuite' ); ?></p>
					</div>
				</div>
				<div class="wpps-opb-modal-panel" data-panel="fields" hidden>
					<h3><?php esc_html_e( 'Fields on this page', 'wp-powersuite' ); ?></h3>
					<?php if ( empty( $field_list ) ) : ?>
						<p class="description"><?php esc_html_e( 'No fields configured yet.', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></th>
									<th><?php esc_html_e( 'Field ID', 'wp-powersuite' ); ?></th>
									<th><?php esc_html_e( 'Type', 'wp-powersuite' ); ?></th>
									<th><?php esc_html_e( 'PHP', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?>"><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.', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?>">
						<p class="wpps-opb-sidebar-nav__title"><?php esc_html_e( 'Sections', 'wp-powersuite' ); ?></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', 'wp-powersuite' ); ?></button>
					<button type="submit" class="button button-primary"><?php echo esc_html( $save_label ); ?></button>
				</p>
			</form>
		<?php endif; ?>
	</div>
</div>
