<?php

// includes/shortcodes.php

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

class AFB_Shortcodes {

	/* ---------------------------------------------------------------------
	 * Boot
	 * ------------------------------------------------------------------ */
	public static function init() : void {
		add_shortcode( 'asana_form',        [ self::class, 'render_asana_form' ] );
		add_shortcode( 'asana_unique_form', [ self::class, 'render_unique_asana_form' ] );
	}

	/* ---------------------------------------------------------------------
	 * Helper – emit the JS once per page (autogrow only)
	 * ------------------------------------------------------------------ */
	private static function emit_inline_autogrow_script() : void {
		static $printed = false;
		if ( $printed ) return;
		$printed = true;
		?>
		<script>
		document.addEventListener('DOMContentLoaded', () => {
		  const fit = (ta) => { ta.style.height='auto'; ta.style.height = ta.scrollHeight+'px'; };
		  const autogrow = (ta) => { if (ta.dataset.autogrow) return; fit(ta); ta.addEventListener('input',()=>fit(ta)); ta.dataset.autogrow='1'; };
		  const scanTree = (root) => root.querySelectorAll('textarea').forEach(autogrow);
		  scanTree(document);

		  const target = document.querySelector('.asana-dynamic-form') || document.body;
		  new MutationObserver((muts) => {
		    muts.forEach((m) =>
		      m.addedNodes.forEach((n) => {
		        if (n.nodeType !== 1) return;
		        if (n.tagName === 'TEXTAREA') autogrow(n);
		        else scanTree(n);
		      })
		    );
		  }).observe(target, { childList: true, subtree: true });
		});
		</script>
		<?php
	}

	/* ---------------------------------------------------------------------
	 * Shortcode: [asana_form]
	 * ------------------------------------------------------------------ */
	public static function render_asana_form( $atts ) : string {
		global $wpdb;

		$atts = shortcode_atts( [ 'pat_account' => '' ], $atts, 'asana_form' );

		$account_label     = sanitize_text_field( $atts['pat_account'] );
		$allowed_projects  = get_option( 'afb_allowed_projects', [] );
		$form_id           = uniqid( 'asana_form_' );
		$all_projects      = [];

		if ( $account_label === 'all' ) {
			$all_projects = afb_get_all_projects();
		} elseif ( $account_label ) {
			$table   = $wpdb->prefix . 'asana_accounts';
			$account = $wpdb->get_row(
				$wpdb->prepare( "SELECT * FROM $table WHERE label = %s", $account_label ),
				ARRAY_A
			);
			if ( $account && ! empty( $account['pat'] ) ) {
				$decrypted_pat = afb_decrypt( $account['pat'] );
				$all_projects  = afb_get_all_projects( $decrypted_pat, $account['portfolio_gid'] );
			}
		} else {
			$all_projects = afb_get_all_projects();
		}

		$all_projects = array_filter(
			$all_projects,
			fn( $proj ) => in_array( $proj['gid'], $allowed_projects, true )
		);

		ob_start(); ?>
		<div class="asana-form-container">
			<div class="asana-title-wrap">
				<h1 class="js-project-title">Submit a Request</h1>
			</div>

			<div id="<?php echo esc_attr( $form_id ); ?>" class="asana-form-wrapper">
				<form method="post" class="asana-dynamic-form">
					<input type="hidden" name="submitter_email" id="submitter_email" />

					<label class="block mb-6">
						<span class="text-gray-700">Select Project</span>
						<select name="project_id" class="project-picker mt-1 block w-full">
							<option value="">-- Choose a project --</option>
							<?php foreach ( $all_projects as $project ) : ?>
								<option value="<?php echo esc_attr( $project['gid'] ); ?>">
									<?php echo esc_html( $project['name'] ); ?>
								</option>
							<?php endforeach; ?>
						</select>
					</label>

					<!-- Fields render here (client-side) -->
					<div class="asana-fields"></div>

					<div class="header-and-submit hidden">
						<button type="submit">
							Submit your request
						</button>
					</div>
				</form>
			</div>
		</div>
		<?php
		self::emit_inline_autogrow_script();

		return ob_get_clean();
	}

	/* ---------------------------------------------------------------------
	 * Shortcode: [asana_unique_form]
	 * ------------------------------------------------------------------ */
	public static function render_unique_asana_form( $atts ) : string {
		global $wpdb;

		$atts = shortcode_atts(
			[
				'project_id'  => get_query_var( 'afb_form_project', '' ),
				'pat_account' => '',
			],
			$atts,
			'asana_unique_form'
		);

		$project_id    = sanitize_text_field( $atts['project_id'] );
		$account_label = sanitize_text_field( $atts['pat_account'] );

		if ( ! $project_id ) {
			return '<p style="color:red;">Error: No project specified.</p>';
		}

		$project = null;

		if ( $account_label ) {
			$table   = $wpdb->prefix . 'asana_accounts';
			$account = $wpdb->get_row(
				$wpdb->prepare( "SELECT * FROM $table WHERE label = %s", $account_label ),
				ARRAY_A
			);
			if ( $account && ! empty( $account['pat'] ) ) {
				$decrypted_pat = afb_decrypt( $account['pat'] );
				$projects      = afb_get_all_projects( $decrypted_pat, $account['portfolio_gid'] );

				foreach ( $projects as $proj ) {
					if ( ($proj['gid'] ?? '') === $project_id ) {
						$project = $proj;
						break;
					}
				}
			}
		} else {
			$project = afb_get_project( $project_id );
		}

		// Read optional custom form title from Field Flow Config
		$field_cfg     = get_option( 'afb_project_field_config', [] );
		$config_for_id = $field_cfg[ $project_id ] ?? [];
		$custom_title  = $config_for_id['form_title'] ?? '';

		$project_name = $project['name'] ?? '';
		$title        = trim( (string) ( $custom_title ?: $project_name ) );
		if ( $title === '' ) { $title = 'Submit a Request'; }

		$form_id = uniqid( 'asana_unique_form_' );

		ob_start(); ?>
		<div class="asana-form-container">
			<div class="asana-title-wrap">
				<h1 class="js-project-title"><?php echo esc_html( $title ); ?></h1>
			</div>

			<div id="<?php echo esc_attr( $form_id ); ?>" class="asana-form-wrapper">
				<form method="post" class="asana-dynamic-form">
					<select name="project_id" class="project-picker" style="display:none;">
						<option value="<?php echo esc_attr( $project_id ); ?>" selected>
							<?php echo esc_html( $project_name ?: $title ); ?>
						</option>
					</select>

					<!-- Fields render here (client-side) -->
					<div class="asana-fields"></div>

					<div class="header-and-submit hidden">
						<button type="submit">
							Submit Request
						</button>
					</div>
				</form>
			</div>
		</div>
		<?php
		self::emit_inline_autogrow_script();

		return ob_get_clean();
	}
}

AFB_Shortcodes::init();
