<?php

$clean_data = array();

if ( ! empty( $input ) ) foreach( $input as $key => $value ) {

	$clean_key = sanitize_key( $key );

	if( ! empty( $value ) ) {

		switch ($clean_key) {
			case 'tag_affiliate':

				$clean_val = [];

				if ( is_array( $value ) ){

					foreach( $value as $i => $section ){
						if ( empty( $section['sel'] ) ) continue;
						$clean_val[$i]['sel'] = trim( sanitize_text_field( $section['sel'] ) );
						if ( ! empty( $section['val'] ) ) $clean_val[$i]['val'] = trim( sanitize_text_field( $section['val'] ) );
					}
				};
				break;

			case 'tag_elems':
			case 'tag_forms':
			case 'tag_views':

				$clean_val = [];

				if ( is_array( $value ) ){

					foreach( $value as $i => $section ){
						if ( empty( $section['sel'] ) || empty( $section['val'] ) ) continue;
						$clean_val[$i]['sel'] = trim( sanitize_text_field( $section['sel'] ) );
						$clean_val[$i]['val'] = trim( sanitize_text_field( $section['val'] ) );
					}
				};
				break;
			case 'custom_events':

				$clean_val = [];

				if ( is_array( $value ) ){

					foreach( $value as $i => $section ){
						// Require both atrig_id and tag_name
						if ( empty( $section['atrig_id'] ) || empty( $section['tag_name'] ) ) continue;
						
						$clean_val[$i]['atrig_id'] = sanitize_key( $section['atrig_id'] );
						$clean_val[$i]['tag_name'] = trim( sanitize_text_field( $section['tag_name'] ) );
						
						// Sanitize repeat option (default to 'no' if not set)
						$clean_val[$i]['repeat'] = isset( $section['repeat'] ) && $section['repeat'] === 'yes' ? 'yes' : 'no';
					}
				};
				break;


			case 'id':
			case 'tag_file_downl':
				$clean_val = trim( sanitize_text_field( $value )) ;
				break;
			case 'user_attr':
			case 'tag_woo_purchases_data':
			case 'tag_woo_checkouts_data':
			case 'tag_woo_addtocart_data':
			case 'tag_woo_removefromcart_data':
			case 'tag_woo_addtowishlist_data':
				$clean_val = array_map( 'sanitize_key', $value );
				break;
			case 'limit_country':

				$clean_val = [];

				if ( is_array( $value ) && ! empty( $value['method'] ) && ! empty( $value['countries'] ) ) {
					$clean_val['method'] = sanitize_key( $value['method'] );
					$clean_val['countries'] = trim( sanitize_text_field( $value['countries'] ) );
				};

				break;
			default:
				$clean_val = is_bool ( $value ) || is_string ( $value ) ? strip_tags( stripslashes( $value ) ) : false;
				break;
		}

		// error_log('sanitized ' . $clean_key . ' value: ' . json_encode($clean_val) );

		if ( ! empty( $clean_val ) && ! empty ( $clean_key ) ) $clean_data[$clean_key] = $clean_val;
	}
}
?>
