<?php

class WDPOP_Public {

	private $plugin_name = WDPOP_NAME;
	private $version = WDPOP_VER;
	
	private $settings;
	private $enable_mc;
	private $enable_templates;
	
	private $dynamic_form_styles = [];
	
	public function __construct() {

		$this->settings = WDPOP_Helper::get_settings();
        $this->enable_mc = !empty($this->settings['enable_mailchimp']) ?? false;
        $this->enable_templates = !empty($this->settings['enable_templates']) ?? false;
		
		$this->run_public_actions();

	}
	function init_variables(){
		$this->settings = WDPOP_Helper::get_settings();
        $this->enable_mc = !empty($this->settings['enable_mailchimp']) ?? false;
        $this->enable_templates = !empty($this->settings['enable_templates']) ?? false;		
	}
	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'] );
		
		if($this->enable_mc){	
			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() {
		
		check_ajax_referer( 'wing__nonce', 'nonce' );
		
		$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' ) ) );
		}

		$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'] ); // true = update or create
		$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 );
		$base_url = "https://{$dc}.api.mailchimp.com/3.0/lists/{$list_id}/members";

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

		$data = array(
			'email_address' => $email,
			'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 ),
		);

		// If update existing is enabled, use PUT (create or update)
		if ( $update_existing ) {
			$subscriber_hash = md5( strtolower( $email ) );
			$url = "{$base_url}/{$subscriber_hash}";
			$args['method'] = 'PUT';
		} else {
			// Create only (will fail if user exists)
			$url = $base_url;
			$args['method'] = 'POST';
		}

		$response = wp_remote_request( $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 init_shortcode(){
		add_shortcode( 'wing-popup-mc-form', [$this,'wing_popup_mc_form_shortcode'] );
	}
	
	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 );
		if ( empty( $mc_form ) || empty( $mc_form['mc_form_tab'] ) ) {
			return '<p>' . esc_html__( 'Mailchimp form not found.', 'wing-popup' ) . '</p>';
		}

		$status = $mc_form['mc_form_status'] ?? false;
		if ( ! $status ) {
			return '<p>' . esc_html__( 'Please, Enable the MailChimp form.', 'wing-popup' ) . '</p>';
		}

		$tab = (array) $mc_form['mc_form_tab'];
		$invalid_mail = $tab['mcm_invalid_email'] ?? 'Please, Enter a valid Email';
		$redirect_url = $tab['redirect_url'] ?? '';
		$hide_form = $tab['hide_form'] ?? false;
		
		// 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-redirect_url="<?php echo esc_attr( $redirect_url ); ?>"
			data-hide_form="<?php echo esc_attr( $hide_form ); ?>"
			data-invalid-mail="<?php echo esc_attr( $invalid_mail ); ?>">

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

			<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 ) {
		$has_label = ! empty( $field['label'] );
		$unique = random_int(100, 9999);
		$wrapper = true;
		
		$field_id = 'wing-popup-mc-'.'-'.$field['name'].$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_field_nested_tag( 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');
		
		if($this->enable_mc){
			WDPOP_Helper::wing_add_dynamic_style($this->plugin_name. 'mc-form', 'public/css/mc-form.css');
		}
		
		$this->add_popup_inline_styles();

	}

	function get_mc_form_styles($style){
		
		$active_mc_forms = WDPOP_Helper::get_active_mc_form_ids();
		
		foreach ($active_mc_forms as $form_id) {
			$mc_form = WDPOP_Helper::get_mc_form_by_id( $form_id );
			$tab = (array) $mc_form['mc_form_tab'];
			$bg_color = $tab['mc_form_pcolor'] ?? '';
			$style .= ".wing-popup-mc-form-{$form_id} .wing-popup-mc-form-submit { background-color: {$bg_color} !important; }";
		}
		return $style;
		
	}
	
	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 );
		
		if($this->enable_mc){
			$mc_styles = '';
			$mc_styles .= $this->get_mc_form_styles($mc_styles);
			wp_add_inline_style( $this->plugin_name. 'mc-form', $mc_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;
	}
	
}
