<?php

class WDPOP_Public {

	private $plugin_name;
	private $version;
	
	public function __construct() {

		$this->plugin_name = WDPOP_NAME;
		$this->version = WDPOP_VER;
		
		$this->run_public_actions();

	}
	function run_public_actions(){
		add_action( 'wp_enqueue_scripts', [$this,'enqueue_styles'] );
		add_action( 'wp_enqueue_scripts', [$this,'enqueue_scripts'] );
		add_action( 'wp_footer', [$this,'add_popup_markup'] );
		
		add_shortcode( 'wing-popup-mc-form', [$this,'wing_popup_mc_form_shortcode'] );		

		
		add_action( 'wp_ajax_wing_popup_mc_subscribe', [$this, 'wing_popup_mc_subscribe'] );
		add_action( 'wp_ajax_nopriv_wing_popup_mc_subscribe', [$this, 'wing_popup_mc_subscribe'] );
		
		
	}
	
function wing_popup_mc_subscribe() {
	// Sanitize inputs
	$form_id   = absint( $_POST['form_id'] ?? 0 );
	$email     = sanitize_email( $_POST['email'] ?? '' );
	$first     = sanitize_text_field( $_POST['first_name'] ?? '' );
	$last      = sanitize_text_field( $_POST['last_name'] ?? '' );

	if ( ! $form_id || empty( $email ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Invalid form data.', 'wing-popup' ) ) );
	}

	// Get form settings
	$mc_form = WDPOP_Helper::get_mc_form_by_id( $form_id );
	if ( empty( $mc_form ) || empty( $mc_form['mc_form_tab'] ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Mailchimp form not found.', 'wing-popup' ) ) );
	}

	$tab = (array) $mc_form['mc_form_tab'];

	$list_id         = sanitize_text_field( $tab['mailchimp_list'] ?? '' );
	$update_existing = ! empty( $tab['update_existing'] );
	$double_optin    = ! empty( $tab['double_optin'] );

	// Messages
	$success_msg     = sanitize_text_field( $tab['mcm_success'] ?? esc_html__( 'Thank you for joining our mailing list.', 'wing-popup' ) );
	$fail_msg        = sanitize_text_field( $tab['mcm_fail'] ?? esc_html__( 'There was a problem processing your submission.', 'wing-popup' ) );
	$invalid_msg     = sanitize_text_field( $tab['mcm_invalid_email'] ?? esc_html__( 'Please enter a valid email address.', 'wing-popup' ) );

	if ( ! is_email( $email ) ) {
		wp_send_json_error( array( 'message' => $invalid_msg ) );
	}

	$api_key = WDPOP_Helper::get_mc_api_key();
	if ( empty( $api_key ) ) {
		wp_send_json_error( array( 'message' => esc_html__( 'Mailchimp API key is missing.', 'wing-popup' ) ) );
	}

	list( , $dc ) = explode( '-', $api_key ); // datacenter part from API key

	// Mailchimp requires subscriber_hash for update requests
	$subscriber_hash = md5( strtolower( $email ) );
	$member_url      = "https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}/members/{$subscriber_hash}";

	$status = $double_optin ? 'pending' : 'subscribed';

	$data = array(
		'email_address' => $email,
		'status_if_new' => $status,
		'status'        => $status,
		'merge_fields'  => array(
			'FNAME' => $first,
			'LNAME' => $last,
		),
	);

	$args = array(
		'headers' => array(
			'Authorization' => 'apikey ' . $api_key,
			'Content-Type'  => 'application/json',
		),
		'body'    => wp_json_encode( $data ),
		'method'  => 'PUT', // Important: wp_remote_request with PUT
	);

	$response = wp_remote_request( $member_url, $args );

	$code = wp_remote_retrieve_response_code( $response );
	$body = json_decode( wp_remote_retrieve_body( $response ), true );

	if ( $code >= 200 && $code < 300 ) {
		wp_send_json_success( array( 'message' => $success_msg ) );
	} else {
		$error = $body['detail'] ?? $fail_msg;
		wp_send_json_error( array( 'message' => $error ) );
	}
}

	
	
	function wing_popup_mc_subscribeY() {
		// Verify nonce if you add one (recommended).
		// check_ajax_referer( 'wing__nonce', 'nonce' );

		// Sanitize inputs
		$form_id = absint( $_POST['form_id'] ?? 0 );
		$email   = sanitize_email( $_POST['email'] ?? '' );
		$first   = sanitize_text_field( $_POST['first_name'] ?? '' );
		$last    = sanitize_text_field( $_POST['last_name'] ?? '' );

		if ( ! $form_id ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid Mailchimp Form ID.', 'wing-popup' ) ) );
		}

		if ( empty( $email ) || ! is_email( $email ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Please provide a valid email address.', 'wing-popup' ) ) );
		}

		$mc_form = WDPOP_Helper::get_mc_form_by_id( $form_id );
		if ( empty( $mc_form ) || empty( $mc_form['mc_form_tab'] ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Mailchimp form not found.', 'wing-popup' ) ) );
		}

		$tab = (array) $mc_form['mc_form_tab'];

		
		$update_existing = ! empty( $tab['update_existing'] );
		$double_optin    = ! empty( $tab['duoble_optin'] );

		// Messages with fallbacks
		$success_msg = $tab['mcm_success']        ?? esc_html__( 'Thank you, your sign-up request was successful!', 'wing-popup' );
		$fail_msg    = $tab['mcm_fail']           ?? esc_html__( 'Oops. Something went wrong. Please try again later.', 'wing-popup' );
		$invalid_msg = $tab['mcm_invalid_email']  ?? esc_html__( 'Please provide a valid email address.', 'wing-popup' );

		$api_key = WDPOP_Helper::get_mc_api_key();
		if ( empty( $api_key ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Mailchimp API key is missing.', 'wing-popup' ) ) );
		}
		$list_id         = sanitize_text_field( $tab['mailchimp_list'] ?? '' );
		if ( empty( $list_id ) ) {
			wp_send_json_error( array( 'message' => 'Mailchimp Audiance List is not Selected.' ) );
		}
		
		// Extract datacenter from API key
		if ( strpos( $api_key, '-' ) === false ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid Mailchimp API key format.', 'wing-popup' ) ) );
		}
		list( , $dc ) = explode( '-', $api_key );

		$subscriber_hash = md5( strtolower( $email ) );
		$url             = "https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}/members/{$subscriber_hash}";

		$data = array(
			'email_address'   => $email,
			'status_if_new'   => $double_optin ? 'pending' : 'subscribed',
			'status'          => $double_optin ? 'pending' : 'subscribed',
			'merge_fields'    => array(
				'FNAME' => $first,
				'LNAME' => $last,
			),
		);

		$response = wp_remote_put( $url, array(
			'headers' => array(
				'Authorization' => 'apikey ' . $api_key,
				'Content-Type'  => 'application/json',
			),
			'body' => wp_json_encode( $data ),
		));

		$code = wp_remote_retrieve_response_code( $response );
		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( $code >= 200 && $code < 300 ) {
			wp_send_json_success( array( 'message' => $success_msg ) );
		}

		// Handle email already exists
		if ( isset( $body['title'] ) && $body['title'] === 'Member Exists' && $update_existing ) {
			wp_send_json_success( array( 'message' => $success_msg ) );
		}

		// Invalid email error
		if ( isset( $body['title'] ) && $body['title'] === 'Invalid Resource' ) {
			wp_send_json_error( array( 'message' => $invalid_msg ) );
		}

		// Fallback
		$error = $body['detail'] ?? $fail_msg;
		wp_send_json_error( array( 'message' => $error ) );
	}


	function wing_popup_mc_subscribeX() {
		// You can sanitize your inputs here
		$form_id   = sanitize_text_field( $_POST['form_id'] );
		$email     = sanitize_email( $_POST['email'] );
		$first     = sanitize_text_field( $_POST['first_name'] ?? '' );
		$last      = sanitize_text_field( $_POST['last_name'] ?? '' );

		
		$form_id = absint( $form_id );
		if ( ! $form_id ) {
			return '<p>' . esc_html__( 'Invalid Mailchimp Form ID.', 'wing-popup' ) . '</p>';
		}

		$mc_form = WDPOP_Helper::get_mc_form_by_id( $form_id );
		
		if ( empty( $mc_form ) || empty( $mc_form['mc_form_tab'] ) ) {
			return '<p>' . esc_html__( 'Mailchimp form not found.', 'wing-popup' ) . '</p>';
		}

		$tab = (array) $mc_form['mc_form_tab'];
		
		$list_id   = $tab['mailchimp_list'];
		
		$update_existing = $tab['update_existing'];
		$duoble_optin = $tab['duoble_optin'];
		// Messages
		$success = $tab['mailchimp_list'];
		$fail = $tab['mcm_fail'];
		$invalid_mail = $tab['mcm_invalid_email'];
		
		
		
		$api_key = WDPOP_Helper::get_mc_api_key();
		
		list( , $dc ) = explode( '-', $api_key );
		$url = "https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}/members";

		$data = array(
			'email_address' => $email,
			'status'        => 'subscribed',
			'merge_fields'  => array(
				'FNAME' => $first,
				'LNAME' => $last,
			),
		);

		$response = wp_remote_post( $url, array(
			'headers' => array(
				'Authorization' => 'apikey ' . $api_key,
				'Content-Type'  => 'application/json',
			),
			'body' => wp_json_encode( $data ),
		));

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( wp_remote_retrieve_response_code( $response ) == 200 ) {
			wp_send_json_success( array( 'message' => 'Thank you for joining our mailing list.' ) );
		} else {
			$error = $body['detail'] ?? 'There was a problem processing your submission.';
			wp_send_json_error( array( 'message' => $error ) );
		}
	}
	


	function wing_popup_mc_subscribeTRY() {
		$list_id   = sanitize_text_field( $_POST['list_id'] ?? '' );
		$email     = sanitize_email( $_POST['email'] ?? '' );
		$first     = sanitize_text_field( $_POST['first_name'] ?? '' );
		$last      = sanitize_text_field( $_POST['last_name'] ?? '' );
		$double_optin = ! empty( $_POST['double_optin'] ) ? true : false;
		$update_existing = ! empty( $_POST['update_existing'] ) ? true : false;

		if ( empty( $list_id ) || empty( $email ) ) {
			wp_send_json_error( array( 'message' => 'Invalid request.' ) );
		}

		$api_key   = get_option( 'wing_popup_mc_api_key' ); // your saved API key
		if ( ! $api_key || ! strpos( $api_key, '-' ) ) {
			wp_send_json_error( array( 'message' => 'Invalid API key.' ) );
		}

		list( , $dc ) = explode( '-', $api_key );
		$url = "https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}/members";

		// status: subscribed = immediate, pending = double opt-in
		$status = $double_optin ? 'pending' : 'subscribed';

		$data = array(
			'email_address' => $email,
			'status'        => $status,
			'merge_fields'  => array(
				'FNAME' => $first,
				'LNAME' => $last,
			),
		);

		if ( $update_existing ) {
			// Use PUT with subscriber hash to update existing
			$subscriber_hash = md5( strtolower( $email ) );
			$url = "https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}/members/{$subscriber_hash}";
			$response = wp_remote_request( $url, array(
				'method'  => 'PUT',
				'headers' => array(
					'Authorization' => 'apikey ' . $api_key,
					'Content-Type'  => 'application/json',
				),
				'body' => wp_json_encode( $data ),
			));
		} else {
			// Normal add new
			$response = wp_remote_post( $url, array(
				'headers' => array(
					'Authorization' => 'apikey ' . $api_key,
					'Content-Type'  => 'application/json',
				),
				'body' => wp_json_encode( $data ),
			));
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		$code = wp_remote_retrieve_response_code( $response );

		if ( $code >= 200 && $code < 300 ) {
			wp_send_json_success( array( 'message' => sanitize_text_field( $_POST['success'] ?? 'Subscribed successfully!' ) ) );
		} else {
			$error = $body['detail'] ?? sanitize_text_field( $_POST['failure'] ?? 'Subscription failed.' );
			wp_send_json_error( array( 'message' => $error ) );
		}
	}

	function init_shortcode(){
		add_shortcode( 'wing-popup-mc-form', [$this,'wing_popup_mc_form_shortcode'] );
	}

	function wing_popup_mc_form_shortcodeX( $atts ) {
		$atts = shortcode_atts( array(
			'id'       => '',
			// 'list'       => WDPOP_Helper::mc_get_first_list(),
			// 'button'     => 'Subscribe',
			// 'email_text' => 'Your E-mail',
			// 'firstname'   => 'false',
			// 'lastname'    => 'false',
			// 'first_name_text' => 'First Name',
			// 'last_name_text'  => 'Last Name',
			// 'placeholder' => 'true',
			// 'success'     => 'Thank you for joining our mailing list.',
			// 'failure'     => 'There was a problem processing your submission.',
		), $atts );
		
		$forms = WDPOP_Helper::get_mc_forms();
		
		echo '<pre>';
		var_export($forms);
		echo '</pre>';
		
		if(empty($atts['id'])){
			return 'Please Give the MailChimp Form Here.';
		}
		
		$mc_form = $this->get_mc_form_by_id($atts['id']); 
		
		
		ob_start(); ?>
		<form class="wing-popup-mc-form" data-list="<?php echo esc_attr( $atts['list'] ); ?>">
			<?php if ( $atts['firstname'] === 'true' ): ?>
				<input type="text" name="first_name" placeholder="<?php echo esc_attr( $atts['first_name_text'] ); ?>">
			<?php endif; ?>

			<?php if ( $atts['lastname'] === 'true' ): ?>
				<input type="text" name="last_name" placeholder="<?php echo esc_attr( $atts['last_name_text'] ); ?>">
			<?php endif; ?>

			<input type="email" name="email" class="wing-popup-mc-form-email" placeholder="<?php echo esc_attr( $atts['email_text'] ); ?>" required>
			<button type="submit" class="wing-popup-mc-form-submit"><?php echo esc_html( $atts['button'] ); ?></button>
			<div class="wing-popup-mc-message"></div>
		</form>
		<?php
		return ob_get_clean();
	}
	function wing_popup_mc_form_shortcodeY( $atts ) {
		$atts = shortcode_atts( array(
			'id'       => '',
		), $atts );
		
		
		// $forms = WDPOP_Helper::get_mc_forms();
		// echo '<pre>';
		// var_export($forms);
		// echo '</pre>';
		
		if(empty($atts['id'])){
			return 'Please Give the MailChimp Form Here.';
		}
		
		$mc_form = $this->get_mc_form_by_id($atts['id']); 
		
		
		ob_start(); ?>
		<form class="wing-popup-mc-form" data-list="<?php echo esc_attr( $atts['list'] ); ?>">
			<?php if ( $atts['firstname'] === 'true' ): ?>
				<input type="text" name="first_name" placeholder="<?php echo esc_attr( $atts['first_name_text'] ); ?>">
			<?php endif; ?>

			<?php if ( $atts['lastname'] === 'true' ): ?>
				<input type="text" name="last_name" placeholder="<?php echo esc_attr( $atts['last_name_text'] ); ?>">
			<?php endif; ?>

			<input type="email" name="email" class="wing-popup-mc-form-email" placeholder="<?php echo esc_attr( $atts['email_text'] ); ?>" required>
			<button type="submit" class="wing-popup-mc-form-submit"><?php echo esc_html( $atts['button'] ); ?></button>
			<div class="wing-popup-mc-message"></div>
		</form>
		<?php
		return ob_get_clean();
	}
	function wing_popup_mc_form_shortcodeZ( $atts ) {
		$atts = shortcode_atts( array(
			'id' => '',
		), $atts );

		if ( empty( $atts['id'] ) ) {
			return 'Please provide a Mailchimp Form ID.';
		}

		// Example: your custom function to fetch form by ID
		$mc_form = $this->get_mc_form_by_id( $atts['id'] );
		if ( empty( $mc_form ) || empty( $mc_form['mc_form_tab'] ) ) {
			return 'Mailchimp form not found.';
		}

		$form_tab = $mc_form['mc_form_tab'];

		$list_id   = $form_tab['mailchimp_list'] ?? '';
		$form_items = $form_tab['form_items'] ?? array();

		ob_start(); ?>
		<form class="wing-popup-mc-form" 
			data-list="<?php echo esc_attr( $list_id ); ?>" 
			data-success="<?php echo esc_attr( $form_tab['mcm_success'] ?? '' ); ?>" 
			data-fail="<?php echo esc_attr( $form_tab['mcm_fail'] ?? '' ); ?>" 
			data-invalid="<?php echo esc_attr( $form_tab['mcm_invalid_email'] ?? '' ); ?>" 
			data-double-optin="<?php echo esc_attr( $form_tab['duoble_optin'] ?? '' ); ?>" 
			data-update-existing="<?php echo esc_attr( $form_tab['update_existing'] ?? '' ); ?>">

			<?php if ( in_array( 'email', $form_items, true ) ) : ?>
				<input type="email" 
					name="email" 
					placeholder="<?php echo esc_attr( $form_tab['email_place'] ?? 'Enter your email' ); ?>" 
					required>
			<?php endif; ?>

			<?php if ( in_array( 'first_name', $form_items, true ) ) : ?>
				<input type="text" 
					name="first_name" 
					placeholder="<?php echo esc_attr( $form_tab['fname_place'] ?? 'First Name' ); ?>">
			<?php endif; ?>

			<?php if ( in_array( 'last_name', $form_items, true ) ) : ?>
				<input type="text" 
					name="last_name" 
					placeholder="<?php echo esc_attr( $form_tab['lname_place'] ?? 'Last Name' ); ?>">
			<?php endif; ?>

			<button type="submit" class="wing-popup-mc-form-submit">
				<?php echo esc_html( $form_tab['submit_text'] ?? 'Subscribe' ); ?>
			</button>
			<div class="wing-popup-mc-message"></div>
		</form>
		<?php
		return ob_get_clean();
	}
	public function wing_popup_mc_form_shortcodeX4( $atts ) {
		$atts = shortcode_atts( array(
			'id' => '',
		), $atts, 'wing-popup-mc-form' );

		$form_id = absint( $atts['id'] );
		if ( ! $form_id ) {
			return '<p>' . esc_html__( 'Please provide a Mailchimp Form ID.', 'wing-popup' ) . '</p>';
		}

		$mc_form = $this->get_mc_form_by_id( $form_id );
		if ( empty( $mc_form ) || empty( $mc_form['mc_form_tab'] ) ) {
			return '<p>' . esc_html__( 'Mailchimp form not found.', 'wing-popup' ) . '</p>';
		}

		$tab = (array) $mc_form['mc_form_tab'];

		// form_items should be an array. Ensure email exists and keep the order user defined.
		$form_items = is_array( $tab['form_items'] ?? null ) ? $tab['form_items'] : array();
		if ( ! in_array( 'email', $form_items, true ) ) {
			array_unshift( $form_items, 'email' );
		}

		// Labels & placeholders
		$email_label = trim( $tab['email_label'] ?? '' );
		$email_place = trim( $tab['email_place'] ?? '' );

		$fname_label = trim( $tab['fname_label'] ?? '' );
		$fname_place = trim( $tab['fname_place'] ?? '' );

		$lname_label = trim( $tab['lname_text_label'] ?? $tab['lname_label'] ?? '' );
		$lname_place = trim( $tab['lname_place'] ?? '' );

		$submit_text = trim( $tab['submit_text'] ?? '' );
		if ( $submit_text === '' ) {
			$submit_text = 'Subscribe';
		}

		ob_start();
		?>
		<form id="wing-popup-mc-form-<?php echo esc_attr( $form_id ); ?>"
			class="wing-popup-mc-form"
			data-form-id="<?php echo esc_attr( $form_id ); ?>">

			<?php
			foreach ( $form_items as $item ) :

				// EMAIL
				if ( 'email' === $item ) :
					if ( $email_label !== '' ) : ?>
						<label class="wing-popup-mc-label">
							<?php echo esc_html( $email_label ); ?>
							<input type="email"
								name="email"
								placeholder="<?php echo esc_attr( $email_place ); ?>"
								required>
						</label>
					<?php else :
						$placeholder = $email_place !== '' ? $email_place : 'Enter Your Email'; ?>
						<input type="email"
							name="email"
							class="wing-popup-mc-form-email"
							placeholder="<?php echo esc_attr( $placeholder ); ?>"
							required>
					<?php endif;

				// FIRST NAME
				elseif ( 'first_name' === $item ) :
					if ( $fname_label !== '' ) : ?>
						<label class="wing-popup-mc-label">
							<?php echo esc_html( $fname_label ); ?>
							<input type="text"
								name="first_name"
								placeholder="<?php echo esc_attr( $fname_place ); ?>">
						</label>
					<?php else :
						$placeholder = $fname_place !== '' ? $fname_place : 'Give Your First Name'; ?>
						<input type="text"
							name="first_name"
							placeholder="<?php echo esc_attr( $placeholder ); ?>">
					<?php endif;

				// LAST NAME
				elseif ( 'last_name' === $item ) :
					if ( $lname_label !== '' ) : ?>
						<label class="wing-popup-mc-label">
							<?php echo esc_html( $lname_label ); ?>
							<input type="text"
								name="last_name"
								placeholder="<?php echo esc_attr( $lname_place ); ?>">
						</label>
					<?php else :
						$placeholder = $lname_place !== '' ? $lname_place : 'Give Your Last Name'; ?>
						<input type="text"
							name="last_name"
							placeholder="<?php echo esc_attr( $placeholder ); ?>">
					<?php endif;

				endif;

			endforeach;
			?>

			<button type="submit" class="wing-popup-mc-form-submit">
				<?php echo esc_html( $submit_text ); ?>
			</button>

			<div class="wing-popup-mc-message" aria-live="polite"></div>
		</form>
		<?php
		return ob_get_clean();
	}
	public function wing_popup_mc_form_shortcodeX5( $atts ) {
		$atts = shortcode_atts( array(
			'id' => '',
		), $atts, 'wing-popup-mc-form' );

		$form_id = absint( $atts['id'] );
		if ( ! $form_id ) {
			return '<p>' . esc_html__( 'Please provide a Mailchimp Form ID.', 'wing-popup' ) . '</p>';
		}

		$mc_form = $this->get_mc_form_by_id( $form_id );
		if ( empty( $mc_form ) || empty( $mc_form['mc_form_tab'] ) ) {
			return '<p>' . esc_html__( 'Mailchimp form not found.', 'wing-popup' ) . '</p>';
		}

		$tab = (array) $mc_form['mc_form_tab'];

		// form_items should be an array. Ensure email exists and keep the order user defined.
		$form_items = is_array( $tab['form_items'] ?? null ) ? $tab['form_items'] : array();
		if ( ! in_array( 'email', $form_items, true ) ) {
			array_unshift( $form_items, 'email' );
		}

		// Labels & placeholders
		$email_label = trim( $tab['email_label'] ?? '' );
		$email_place = trim( $tab['email_place'] ?? '' );

		$fname_label = trim( $tab['fname_label'] ?? '' );
		$fname_place = trim( $tab['fname_place'] ?? '' );

		$lname_label = trim( $tab['lname_text_label'] ?? $tab['lname_label'] ?? '' );
		$lname_place = trim( $tab['lname_place'] ?? '' );

		$submit_text = trim( $tab['submit_text'] ?? '' );
		if ( $submit_text === '' ) {
			$submit_text = 'Subscribe';
		}

		ob_start();
		?>
		<form id="wing-popup-mc-form-<?php echo esc_attr( $form_id ); ?>"
			class="wing-popup-mc-form"
			data-form-id="<?php echo esc_attr( $form_id ); ?>">

			<?php
			
			foreach ( $form_items as $item ) {

				$label_text       = '';
				$placeholder_text = '';
				$input_name       = '';
				$input_type       = 'text'; // Default to text input
				$input_class      = '';

				if ( 'email' === $item ) {
					$label_text       = $email_label;
					$placeholder_text = $email_place;
					$input_name       = 'email';
					$input_type       = 'email';
					$input_class      = 'wing-popup-mc-form-email';

				} elseif ( 'first_name' === $item ) {
					$label_text       = $fname_label;
					$placeholder_text = $fname_place;
					$input_name       = 'first_name';

				} elseif ( 'last_name' === $item ) {
					$label_text       = $lname_label;
					$placeholder_text = $lname_place;
					$input_name       = 'last_name';
				}

				// Fallback placeholders if both label and placeholder are empty.
				if ( $label_text === '' && $placeholder_text === '' ) {
					switch ( $item ) {
						case 'email':
							$placeholder_text = esc_html__( 'Enter Your Email', 'wing-popup' );
							break;
						case 'first_name':
							$placeholder_text = esc_html__( 'Give Your First Name', 'wing-popup' );
							break;
						case 'last_name':
							$placeholder_text = esc_html__( 'Give Your Last Name', 'wing-popup' );
							break;
					}
				}

				$has_label = $label_text !== '';

				// Render the HTML
				if ( $has_label ) : ?>
					<label class="wing-popup-mc-label">
						<?php echo esc_html( $label_text ); ?>
				<?php endif; ?>

					<input type="<?php echo esc_attr( $input_type ); ?>"
						name="<?php echo esc_attr( $input_name ); ?>"
						class="<?php echo esc_attr( $input_class ); ?>"
						placeholder="<?php echo esc_attr( $placeholder_text ); ?>"
						<?php if ( 'email' === $item ) echo 'required'; ?>>

				<?php if ( $has_label ) : ?>
					</label>
				<?php endif;

			}


			
			?>

			<button type="submit" class="wing-popup-mc-form-submit">
				<?php echo esc_html( $submit_text ); ?>
			</button>

			<div class="wing-popup-mc-message" aria-live="polite"></div>
		</form>
		<?php
		return ob_get_clean();
	}
	
	public function wing_popup_mc_form_shortcode( $atts ) {
		$atts = shortcode_atts( array(
			'id' => '',
		), $atts, 'wing-popup-mc-form' );

		$form_id = absint( $atts['id'] );
		if ( ! $form_id ) {
			return '<p>' . esc_html__( 'Please provide a Mailchimp Form ID.', 'wing-popup' ) . '</p>';
		}

		$mc_form = WDPOP_Helper::get_mc_form_by_id( $form_id );
		
		$status = $mc_form['mc_form_status'] ?? false;
		if ( ! $status ) {
			return '<p>' . esc_html__( 'Please, Enable the MailChimp form.', 'wing-popup' ) . '</p>';
		}
		
		// echo '<pre>';
		// var_export($mc_form);
		// echo '</pre>';
		
		if ( empty( $mc_form ) || empty( $mc_form['mc_form_tab'] ) ) {
			return '<p>' . esc_html__( 'Mailchimp form not found.', 'wing-popup' ) . '</p>';
		}

		$tab = (array) $mc_form['mc_form_tab'];
		
		$invalid_mail = $tab['mcm_invalid_email'] ?? 'Please, Enter a valid Email';
		
		// Initialize form structure
		$form_config = $this->prepare_form_config( $tab );
		
		ob_start();
		
		$form_class = 'wing-popup-mc-form wing-popup-mc-form-'. $form_id;
		
		?>
		<form class="<?php echo esc_attr( $form_class ); ?>"
			data-form-id="<?php echo esc_attr( $form_id ); ?>"
			data-invalid-mail="<?php echo esc_attr( $invalid_mail ); ?>">

			<?php foreach ( $form_config['items'] as $item ) {
				echo $this->render_form_field( $item, $form_id );
			} ?>

			<button type="submit" class="wing-popup-mc-form-submit">
				<?php echo esc_html( $form_config['submit_text'] ); ?>
			</button>

			<div class="wing-popup-mc-message" aria-live="polite"></div>
		</form>
		<?php
		return ob_get_clean();
	}

	/**
	 * Prepare form configuration from tab data.
	 *
	 * @param array $tab Form tab configuration.
	 * @return array Prepared form configuration.
	 */
	private function prepare_form_config( array $tab ) {
		// Ensure form_items is array and email is included
		$form_items = is_array( $tab['form_items'] ?? null ) ? $tab['form_items'] : array();
		if ( ! in_array( 'email', $form_items, true ) ) {
			array_unshift( $form_items, 'email' );
		}

		// Field definitions
		$field_definitions = array(
			'email' => array(
				'type'        => 'email',
				'class'       => 'wing-popup-mc-form-email',
				'required'    => true,
				'fallback'    => __( 'Enter Your Email', 'wing-popup' ),
				'label_key'   => 'email_label',
				'place_key'   => 'email_place',
			),
			'first_name' => array(
				'type'        => 'text',
				'class'       => 'wing-popup-mc-form-fname',
				'required'    => false,
				'fallback'    => __( 'Give Your First Name', 'wing-popup' ),
				'label_key'   => 'fname_label',
				'place_key'   => 'fname_place',
			),
			'last_name' => array(
				'type'        => 'text',
				'class'       => 'wing-popup-mc-form-lname',
				'required'    => false,
				'fallback'    => __( 'Give Your Last Name', 'wing-popup' ),
				'label_key'   => 'lname_text_label',
				'alt_label_key' => 'lname_label',
				'place_key'   => 'lname_place',
			),
		);

		// Build form items configuration
		$items = array();
		foreach ( $form_items as $item_name ) {
			if ( ! isset( $field_definitions[ $item_name ] ) ) {
				continue; // Skip unknown fields
			}

			$field = $field_definitions[ $item_name ];
			$label_text = trim( $tab[ $field['label_key'] ] ?? 
							$tab[ $field['alt_label_key'] ?? '' ] ?? '' );
			$placeholder_text = trim( $tab[ $field['place_key'] ] ?? '' );

			// Use fallback if both label and placeholder are empty
			if ( empty( $label_text ) && empty( $placeholder_text ) ) {
				$placeholder_text = $field['fallback'];
			}

			$items[] = array(
				'name'        => $item_name,
				'type'        => $field['type'],
				'class'       => $field['class'],
				'required'    => $field['required'],
				'label'       => $label_text,
				'placeholder' => $placeholder_text,
			);
		}

		return array(
			'items'       => $items,
			'submit_text' => trim( $tab['submit_text'] ?? '' ) ?: 'Subscribe',
		);
	}

	/**
	 * Render a single form field.
	 *
	 * @param array $field Field configuration.
	 * @return string HTML for the field.
	 */
	private function render_form_field( array $field, $form_id ) {
		$has_label = ! empty( $field['label'] );
		$unique = random_int(100, 9999);
		$wrapper = true;
		
		$field_id = 'wing-popup-mc-'.'-'.$field['name'].$form_id.$unique;
		
		ob_start();
		
		if ( $wrapper ) : ?>
			<div class="wing-popup-mc-field field-<?php echo esc_attr( $field['name'] ); ?>">
		<?php endif;
		
		if ( $has_label ) : ?>
			<label class="wing-popup-mc-label" for="<?php echo esc_attr( $field_id ); ?>"><?php echo esc_html( $field['label'] ); ?></label>
		<?php endif; ?>

			<input type="<?php echo esc_attr( $field['type'] ); ?>"
				name="<?php echo esc_attr( $field['name'] ); ?>"
				id="<?php echo esc_attr( $field_id ); ?>"
				class="<?php echo esc_attr( $field['class'] ); ?>"
				placeholder="<?php echo esc_attr( $field['placeholder'] ); ?>"
				<?php if ( $field['required'] ) echo 'required'; ?>>

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

		
		return ob_get_clean();
	}	
	private function render_form_fieldX( array $field ) {
		$has_label = ! empty( $field['label'] );
		
		ob_start();
		
		if ( $has_label ) : ?>
			<label class="wing-popup-mc-label">
				<?php echo esc_html( $field['label'] ); ?>
		<?php endif; ?>

				<input type="<?php echo esc_attr( $field['type'] ); ?>"
					name="<?php echo esc_attr( $field['name'] ); ?>"
					class="<?php echo esc_attr( $field['class'] ); ?>"
					placeholder="<?php echo esc_attr( $field['placeholder'] ); ?>"
					<?php if ( $field['required'] ) echo 'required'; ?>>

		<?php if ( $has_label ) : ?>
			</label>
		<?php endif;
		
		return ob_get_clean();
	}	
	
	public function add_popup_markup(){
		include_once WDPOP_DIR . 'public/partials/popup-default.php';
		// include_once WDPOP_DIR . 'public/partials/popup-default-x.php';
		// include_once WDPOP_DIR . 'public/partials/trigger-btn.php';
	}

	public function enqueue_styles() {
		
		if(!WDPOP_Helper::if_popups_active()) return;
		
		// WDPOP_Helper::wing_add_dynamic_style($this->plugin_name.'-bs', 'public/css/bootstrap.min.css');
		WDPOP_Helper::wing_add_dynamic_style($this->plugin_name.'-bs', 'public/css/bs-modal.css');
		WDPOP_Helper::wing_add_dynamic_style($this->plugin_name, 'public/css/wing-popup-styles.css');
		WDPOP_Helper::wing_add_dynamic_style($this->plugin_name. 'mc-form', 'public/css/mc-form.css');
		
		$this->add_popup_inline_styles();

	}
	
	function add_popup_inline_styles(){
		$wdpops = WDPOP_Helper::get_all_active_popups();
		$styles ='';
		
		foreach ($wdpops as $key => $this_popup) {
			$acc = $this_popup['wdpop_item_tab']['popup_style_accordions'];
			
			$color = $acc['close_btn_color']['color'];
			$hover = $acc['close_btn_color']['hover'];
			$bg_color = $acc['close_btn_bg_color']['color'];
			$bg_hover_color = $acc['close_btn_bg_color']['hover'];
			$border_color = $acc['close_btn_border_color']['color'];
			$border_hover_color = $acc['close_btn_border_color']['hover'];
			
			$styles .= "
			.wing-modal--$key .wing--popup-close-btn {
				color: {$color};
				background-color: {$bg_color};
				border-color: {$border_color};
			}
			.wing-modal--$key .wing--popup-close-btn:hover {
				color: {$hover};
				background-color: {$bg_hover_color};
				border-color: {$border_hover_color};
			}
			";
		}
		wp_add_inline_style( $this->plugin_name, $styles );
		
	}

	public function enqueue_scripts() {
		
		if(!WDPOP_Helper::if_popups_active()) return;
		
		// Helper, public and bs scripts are in this file
		WDPOP_Helper::wing_add_dynamic_script($this->plugin_name.'-modal', 'public/js/bs-modal.min.js');
		// WDPOP_Helper::wing_add_dynamic_script($this->plugin_name.'-modal', 'public/js/bootstrap.bundle.min.js');
		WDPOP_Helper::wing_add_dynamic_script($this->plugin_name.'-scripts', 'public/js/wing-popup-scripts.js');
		
		$dataFront = array(
			'popups' => $this->get_public_data_for_popups(),
			'site_url' => get_option('siteurl'),
			'ajax_url' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce( 'wing__nonce' ),
		);
		wp_localize_script($this->plugin_name.'-scripts', 'wdpop__cred', $dataFront );
		
		
	}
	function get_public_data_for_popups(){
		$wdpops = WDPOP_Helper::get_all_active_popups();
		$items = [];
		foreach ($wdpops as $key => $this_popup) {
			$items[] = array(
				'id' => 	$key,
				'on_click_events' => 	$this_popup['wdpop_item_tab']['on_click_events'],
				'page_load_events' => 	$this_popup['wdpop_item_tab']['page_load_events'],
			);
			
		}
		return $items;
	}
	
}
