<?php
/**
 * Update calculator
 *
 * @param array|mixed $data
 * @return boolean
 */
function ccb_update_calc_new_values( $data ) {
	if ( isset( $data['id'] ) ) {
		$title = ! empty( $data['title'] ) ? sanitize_text_field( $data['title'] ) : __( 'empty name', 'cost-calculator-builder' );
		wp_update_post(
			array(
				'ID'         => $data['id'],
				'post_title' => $title,
			)
		);

		\cBuilder\Classes\CCBSettingsData::update_calc_single_settings( $data['id'], $data['settings'] );
		update_post_meta( $data['id'], 'stm-name', $title );
		update_post_meta( $data['id'], 'stm-formula', ! empty( $data['formula'] ) ? apply_filters( 'stm_ccb_sanitize_array', $data['formula'] ) : array() );

		if ( isset( $data['builder'] ) ) {
			foreach ( $data['builder'] as $idx => $builder ) {
				if ( isset( $builder['description'] ) ) {
					$data['builder'][ $idx ]['description'] = ccb_get_sanitized_text( $builder['description'] );
				}

				if ( isset( $builder['label'] ) ) {
					$data['builder'][ $idx ]['label'] = ccb_get_sanitized_text( $builder['label'] );
				}
			}
		}

		update_post_meta( $data['id'], 'stm-fields', ! empty( $data['builder'] ) ? apply_filters( 'stm_ccb_sanitize_array', $data['builder'] ) : array() );
		update_post_meta( $data['id'], 'calc_saved', true );

		$summary_meta = isset( $data['total_summary'] ) ? $data['total_summary'] : get_post_meta( $data['id'], 'stm-total-summary', true );
		if ( empty( $summary_meta ) ) {
			$summary_meta = \cBuilder\Classes\CCBSettingsData::total_summary_settings_data( $data['settings']['general'] ?? array() );
		}
		update_post_meta( $data['id'], 'stm-total-summary', apply_filters( 'stm_ccb_sanitize_array', $summary_meta ) );

		$conditions = array(
			'nodes_v4' => $data['conditions']['nodes'],
			'links_v4' => $data['conditions']['links'],
			'spaces'   => isset( $data['conditions']['spaces'] ) ? $data['conditions']['spaces'] : array(),
		);

		update_post_meta( $data['id'], 'stm-conditions', apply_filters( 'stm_ccb_sanitize_array', $conditions ) );

		if ( isset( $data['category'] ) ) {
			update_post_meta( $data['id'], 'category', sanitize_text_field( $data['category'] ) );
		}

		if ( isset( $data['preset_idx'] ) ) {
			update_post_meta( $data['id'], 'ccb_calc_preset_idx', apply_filters( 'stm_ccb_sanitize_value', $data['preset_idx'] ) );
		}

		$woo_products_enabled = isset( $data['settings']['woo_products']['enable'] ) && filter_var( $data['settings']['woo_products']['enable'], FILTER_VALIDATE_BOOLEAN );

		if ( $data['settings']['formFields']['applyFormId'] && intval( $data['settings']['formFields']['applyFormId'] ) > 0 ) {
			$form_id = $data['settings']['formFields']['applyFormId'];
			update_post_meta( $data['id'], 'form_id', $form_id );
		}

		ccb_update_woocommerce_calcs( $data['id'], ! $woo_products_enabled );
		return true;
	}

	return false;
}

function ccb_update_calc_new_values_template_to_pagebreak( $data ) {
	$result = array(
		array(
			'type'          => 'page-break',
			'label'         => 'Page 1',
			'description'   => 'Page 1',
			'alias'         => 'page_break_field_id_0',
			'_id'           => '99',
			'groupElements' => array(
				array(
					'type'        => 'section',
					'label'       => 'Section 1',
					'description' => 'Section 1',
					'alias'       => 'section_field_id_0',
					'fields'      => array(),
					'_id'         => '98',
				),
			),
		),
	);

	foreach ( $data['builder'] as $builder ) {
		$builder['width'] = 100;
		array_push( $result[0]['groupElements'][0]['fields'], $builder );
	}

	return $result;
}

/**
 * Update calculator
 *
 * @param array|mixed $data
 * @return boolean
 */
function ccb_update_calc_old_values( $data ) {
	if ( isset( $data['id'] ) ) {
		$title = ! empty( $data['title'] ) ? sanitize_text_field( $data['title'] ) : __( 'empty name', 'cost-calculator-builder' );

		wp_update_post(
			array(
				'ID'         => $data['id'],
				'post_title' => $title,
			)
		);
		\cBuilder\Classes\CCBSettingsData::update_calc_single_settings( $data['id'], $data['settings'] );

		update_post_meta( $data['id'], 'stm-name', $title );
		update_post_meta( $data['id'], 'stm-formula', ! empty( $data['formula'] ) ? apply_filters( 'stm_ccb_sanitize_array', $data['formula'] ) : array() );
		update_post_meta( $data['id'], 'stm-fields', ! empty( $data['builder'] ) ? apply_filters( 'stm_ccb_sanitize_array', $data['builder'] ) : array() );
		update_post_meta( $data['id'], 'stm-conditions', ! empty( $data['conditions'] ) ? apply_filters( 'stm_ccb_sanitize_array', $data['conditions'] ) : array() );
		$summary_meta = isset( $data['total_summary'] ) && is_array( $data['total_summary'] ) ? $data['total_summary'] : get_post_meta( $data['id'], 'stm-total-summary', true );
		if ( empty( $summary_meta ) || ! is_array( $summary_meta ) ) {
			$summary_meta = \cBuilder\Classes\CCBSettingsData::total_summary_settings_data( $data['settings']['general'] ?? array() );
		}
		update_post_meta( $data['id'], 'stm-total-summary', apply_filters( 'stm_ccb_sanitize_array', $summary_meta ) );

		$woo_products_enabled = isset( $data['settings']['woo_products']['enable'] ) && filter_var( $data['settings']['woo_products']['enable'], FILTER_VALIDATE_BOOLEAN );
		ccb_update_woocommerce_calcs( $data['id'], ! $woo_products_enabled );

		return true;
	}

	return false;
}

function ccb_update_calc_values( $data ) {
	$status = 'publish';
	if ( isset( $data['status'] ) ) {
		$status = $data['status'];
	}
	ccb_update_post_status( $data['id'], $status );
	return ccb_update_calc_new_values( $data );
}

function ccb_update_post_status( $id, $status = 'draft' ) {
	$data = array(
		'ID'          => $id,
		'post_status' => $status,
	);

	wp_update_post( $data );
}

/**
 * @param $calc_id
 * @param boolean $delete
 */
function ccb_update_woocommerce_calcs( $calc_id, $delete = false ) {
	$woocommerce_calcs = get_option( 'stm_ccb_woocommerce_calcs', array() );
	if ( $delete ) {
		$key = array_search( $calc_id, $woocommerce_calcs, true );
		if ( false !== $key ) {
			unset( $woocommerce_calcs[ $key ] );
		}
	} elseif ( ! in_array( $calc_id, $woocommerce_calcs, true ) ) {
		$woocommerce_calcs[] = $calc_id;
	}

	update_option( 'stm_ccb_woocommerce_calcs', apply_filters( 'stm_ccb_sanitize_array', $woocommerce_calcs ) );
}

/**
 *  Get All Calculators
 *
 * @param $post_type string
 * @return mixed|array
 */
function ccb_calc_get_all_posts( $post_type, $params = array() ) {
	$args = array(
		'offset'         => isset( $params['offset'] ) ? (int) $params['offset'] : 1,
		'posts_per_page' => isset( $params['limit'] ) ? (int) $params['limit'] : -1,
		'post_type'      => $post_type,
		'post_status'    => array( 'publish' ),
		'orderby'        => isset( $params['sort_by'] ) ? sanitize_text_field( $params['sort_by'] ) : 'id',
		'order'          => isset( $params['direction'] ) ? sanitize_text_field( $params['direction'] ) : 'desc',
	);

	if ( isset( $params['search'] ) && ! empty( $params['search'] ) ) {
		$args['s'] = sanitize_text_field( $params['search'] );
	}

	if ( class_exists( 'Polylang' ) ) {
		$args['lang'] = '';
	}

	$resources      = new WP_Query( $args );
	$resources_json = array();

	if ( $resources->have_posts() ) {
		while ( $resources->have_posts() ) {
			$resources->the_post();
			$id                    = get_the_ID();
			$resources_json[ $id ] = html_entity_decode( get_the_title(), ENT_QUOTES | ENT_HTML401, 'UTF-8' );
		}
	}

	return $resources_json;
}

function clearMetaData( $post_id ) {
	global $wpdb;
	$table = $wpdb->prefix . 'postmeta'; //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'stm-name', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'stm-formula', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'stm-fields', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'stm-conditions', 'post_id' => $post_id ) ); //phpcs:ignore
}

function clearTemplatesMetaData( $post_id ) {
	global $wpdb;
	$table = $wpdb->prefix . 'postmeta'; //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'type', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'access', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'category', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'calc_id', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'title', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'description', 'post_id' => $post_id ) ); //phpcs:ignore
}

function clearCategoriesMetaData( $post_id ) {
	global $wpdb;
	$table = $wpdb->prefix . 'postmeta'; //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'type', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'slug', 'post_id' => $post_id ) ); //phpcs:ignore
	$wpdb->delete( $table, array( 'meta_key' => 'title', 'post_id' => $post_id ) ); //phpcs:ignore
}


/**
 * Parse settings by $calc_id
 *
 * @param $settings
 * @return array
 */

function ccb_parse_settings( $settings ) {
	$currency = isset( $settings['currency']['currency'] ) ? sanitize_text_field( $settings['currency']['currency'] ) : '$';

	return array(
		'currency'            => $currency,
		'num_after_integer'   => isset( $settings['currency']['num_after_integer'] ) ? (int) $settings['currency']['num_after_integer'] : 2,
		'decimal_separator'   => isset( $settings['currency']['decimal_separator'] ) ? sanitize_text_field( $settings['currency']['decimal_separator'] ) : '.',
		'thousands_separator' => isset( $settings['currency']['thousands_separator'] ) ? sanitize_text_field( $settings['currency']['thousands_separator'] ) : ',',
		'currency_position'   => isset( $settings['currency']['currencyPosition'] ) ? sanitize_text_field( $settings['currency']['currencyPosition'] ) : 'left_with_space',
	);
}

/**
 * WooCommerce Products
 *
 * @return array
 */
function ccb_woo_products( $page = 1, $per_page = 5, $search = '', $product_ids = array(), $called_by = 'woo_products' ) {
	$offset          = $page * $per_page;
	$selected_offset = $offset - count( $product_ids );
	$product_ids     = array_filter( array_map( 'absint', (array) $product_ids ) );
	$items           = array();
	$new_product_ids = array();

	if ( count( $product_ids ) > 0 ) {
		foreach ( $product_ids as $key => $product_id ) {
			if ( $key < $offset ) {
				$new_product_ids[] = $product_id;
			}
		}

		if ( ! empty( $product_ids ) ) {
			$selected_args = array(
				'post_type'      => 'product',
				'post_status'    => 'publish',
				'post__in'       => $new_product_ids,
				'orderby'        => 'post__in',
				's'              => $search,
				'posts_per_page' => $offset,
				'paged'          => 1,
			);

			if ( 'woo_checkout' === $called_by ) {
				$selected_args['tax_query'] = array(
					array(
						'taxonomy' => 'product_type',
						'field'    => 'slug',
						'terms'    => array( 'variable' ),
						'operator' => 'NOT IN',
					),
				);
			}

			$selected_query        = new WP_Query( $selected_args );
			$selected_products_all = $selected_query->posts;

			foreach ( $selected_products_all as $selected_product ) {
				$items[] = array(
					'ID'         => $selected_product->ID,
					'post_title' => $selected_product->post_title,
					'post_name'  => $selected_product->post_name,
					'guid'       => $selected_product->guid,
				);
			}
		}
	}

	if ( $selected_offset > 0 ) {
		$other_args = array(
			'post_type'      => 'product',
			'post_status'    => 'publish',
			's'              => $search,
			'post__not_in'   => $product_ids,
			'posts_per_page' => $selected_offset,
		);

		if ( 'woo_checkout' === $called_by ) {
			$other_args['tax_query'] = array(
				array(
					'taxonomy' => 'product_type',
					'field'    => 'slug',
					'terms'    => array( 'variable' ),
					'operator' => 'NOT IN',
				),
			);
		}

		$other_query    = new WP_Query( $other_args );
		$other_products = $other_query->posts;

		foreach ( $other_products as $selected_product ) {
			$items[] = array(
				'ID'         => $selected_product->ID,
				'post_title' => $selected_product->post_title,
				'post_name'  => $selected_product->post_name,
				'guid'       => $selected_product->guid,
			);
		}
	}

	$total_args = array(
		'post_type'      => 'product',
		'post_status'    => 'publish',
		'fields'         => 'all',
		'posts_per_page' => 1,
	);

	$total_query = new WP_Query( $total_args );
	$total_found = $total_query->found_posts;

	return array(
		'items' => $items,
		'total' => $total_found,
	);
}

/**
 * WooCommerce Categories
 *
 * @return array
 */
function ccb_woo_categories() {
	return get_terms(
		array(
			'taxonomy'   => 'product_cat',
			'hide_empty' => false,
		)
	);
}

function ccb_woo_categories_paginated( $page = 1, $per_page = 5, $search = '', $category_ids = array() ) {
	$offset      = ( $page - 1 ) * $per_page;
	$category_ids = array_filter( array_map( 'absint', (array) $category_ids ) );
	$items       = array();

	if ( ! empty( $category_ids ) ) {
		$selected = get_terms(
			array(
				'taxonomy'   => 'product_cat',
				'hide_empty' => false,
				'include'    => $category_ids,
			)
		);
		if ( ! is_wp_error( $selected ) ) {
			foreach ( $selected as $term ) {
				$items[] = array(
					'term_id' => $term->term_id,
					'name'    => $term->name,
					'slug'    => $term->slug,
				);
			}
		}
	}

	$args = array(
		'taxonomy'   => 'product_cat',
		'hide_empty' => false,
		'number'     => $per_page,
		'offset'     => $offset,
		'orderby'    => 'name',
		'order'      => 'ASC',
	);

	if ( ! empty( $search ) ) {
		$args['search'] = $search;
	}

	if ( ! empty( $category_ids ) ) {
		$args['exclude'] = $category_ids;
	}

	$terms = get_terms( $args );

	if ( ! is_wp_error( $terms ) ) {
		foreach ( $terms as $term ) {
			$items[] = array(
				'term_id' => $term->term_id,
				'name'    => $term->name,
				'slug'    => $term->slug,
			);
		}
	}

	$count_args = array(
		'taxonomy'   => 'product_cat',
		'hide_empty' => false,
		'fields'     => 'count',
	);
	if ( ! empty( $search ) ) {
		$count_args['search'] = $search;
	}
	$total = get_terms( $count_args );
	if ( is_wp_error( $total ) ) {
		$total = 0;
	}

	return array(
		'items'    => $items,
		'total'    => (int) $total,
		'has_more' => ( $offset + $per_page ) < (int) $total,
	);
}

/**
 * Contact Form 7 Forms
 *
 * @return array
 */
function ccb_all_available_pages( $page = 1, $per_page = 5, $search = '', $page_ids = array() ) {
	$offset          = $page * $per_page;
	$selected_offset = $offset - count( $page_ids );
	$page_ids        = array_filter( array_map( 'absint', (array) $page_ids ) );
	$items           = array();
	$new_page_ids    = array();

	if ( count( $page_ids ) > 0 ) {
		foreach ( $page_ids as $key => $page_id ) {
			if ( $key < $offset ) {
				$new_page_ids[] = $page_id;
			}
		}

		if ( ! empty( $new_page_ids ) ) {
			$selected_args = array(
				'post_type'      => 'page',
				'post_status'    => 'publish',
				'post__in'       => $new_page_ids,
				'orderby'        => 'post__in',
				's'              => $search,
				'posts_per_page' => $offset,
				'paged'          => 1,
			);

			$selected_query = new WP_Query( $selected_args );

			if ( $selected_query->have_posts() ) {
				while ( $selected_query->have_posts() ) {
					$selected_query->the_post();
					$page    = $selected_query->post;
					$items[] = array(
						'id'      => $page->ID,
						'title'   => strlen( $page->post_title ) < 21 ? $page->post_title : substr( $page->post_title, 0, 20 ) . '...',
						'link'    => get_permalink( $page->ID ),
						'tooltip' => $page->post_title,
					);
				}
				wp_reset_postdata();
			}
		}
	}

	if ( $selected_offset > 0 ) {
		$other_args = array(
			'post_type'      => 'page',
			'post_status'    => 'publish',
			's'              => $search,
			'post__not_in'   => $page_ids,
			'posts_per_page' => $selected_offset,
		);

		$other_query = new WP_Query( $other_args );

		if ( $other_query->have_posts() ) {
			while ( $other_query->have_posts() ) {
				$other_query->the_post();
				$page    = $other_query->post;
				$items[] = array(
					'id'      => $page->ID,
					'title'   => strlen( $page->post_title ) < 21 ? $page->post_title : substr( $page->post_title, 0, 20 ) . '...',
					'link'    => get_permalink( $page->ID ),
					'tooltip' => $page->post_title,
				);
			}
			wp_reset_postdata();
		}
	}

	$total_args = array(
		'post_type'      => 'page',
		'post_status'    => 'publish',
		'posts_per_page' => 1,
	);

	if ( ! empty( $search ) ) {
		$total_args['s'] = sanitize_text_field( $search );
	}

	$total_query = new WP_Query( $total_args );
	$total_found = $total_query->found_posts;

	return array(
		'items' => $items,
		'total' => $total_found,
	);
}

/**
 * Contact Form 7 Forms
 *
 * @return array
 */
function ccb_contact_forms() {
	$contact_forms = get_posts(
		array(
			'post_type'      => 'wpcf7_contact_form',
			'posts_per_page' => -1,
		)
	);

	$forms = array();
	if ( count( $contact_forms ) ) {
		foreach ( $contact_forms as $contact_form ) {
			$forms[] = array(
				'id'    => $contact_form->ID,
				'title' => $contact_form->post_title,
			);
		}
	}

	return $forms;
}

/**
 * Check active Add-on
 *
 * @return bool
 */
function ccb_pro_active() {
	return ( defined( 'CCB_PRO_VERSION' ) );
}

function ccb_is_backend_demo() {
	return defined( 'STM_COUPON_URL' );
}

function ccb_all_calculators_data() {
	$args = array(
		'post_type'      => 'cost-calc',
		'posts_per_page' => -1,
		'post_status'    => 'publish',
	);

	$data = new \WP_Query( $args );
	$data = $data->posts;

	return $data;
}

function ccb_all_calculators_data_list() {
	$lists = array();
	$data  = ccb_all_calculators_data();

	if ( count( $data ) > 0 ) {
		foreach ( $data as $value ) {
			$lists[] = array(
				'id'    => $value->ID,
				'label' => $value->post_title,
				'slug'  => $value->post_name,
			);
		}
	}

	return $lists;
}

function ccb_all_calculators() {
	$lists = array( esc_html__( 'select', 'cost-calculator-builder' ) => 'Select' );
	$data  = ccb_all_calculators_data();

	if ( count( $data ) > 0 ) {
		foreach ( $data as $value ) {
			$lists[ $value->ID ] = $value->post_title;
		}
	}

	return $lists;
}

/**
 * Write to log
 *
 * @param $log
 * @return void
 */
function ccb_write_log( $log ) {
	if ( true === WP_DEBUG ) {
		if ( is_array( $log ) || is_object( $log ) ) {
			error_log( print_r( $log, true ) ); // phpcs:ignore
		} elseif ( $log ) {
			error_log( $log ); // phpcs:ignore
		}
	}
}

/**
 * Return Support Ticket URL
 *
 * @return string
 */
function ccb_get_ticket_url() {
	$type = ccb_pro_active() ? 'support' : 'pre-sale';

	return "https://support.stylemixthemes.com/tickets/new/{$type}?item_id=29";
}

/** Base helper functions */


/**
 * @param string $json_string
 */
function is_json_string( $json_string ) {
	json_decode( $json_string );
	return ( json_last_error() === JSON_ERROR_NONE );
}


/**
 * sanitize_text_field without < replacement
 *
 * @param string $json_string
 */
function sanitize_without_tag_clean( $json_string ) {
	$result = str_replace( '<', '{less}', $json_string );
	$result = sanitize_text_field( $result );
	return str_replace( '{less}', '<', $result );
}

/**
 * @param $settings
 * @param $general_settings
 * @return array
 */
function ccb_sync_settings_from_general_settings( $settings, $general_settings, $render = false ) {
	$general_settings_cloned = $general_settings;

	if ( ! empty( $general_settings['currency']['use_in_all'] ) ) {
		$settings['currency'] = $general_settings['currency'];
	}

	if ( ! empty( $general_settings_cloned['form_fields']['use_in_all'] ) ) {
		unset( $general_settings_cloned['form_fields']['use_in_all'] );
		foreach ( $general_settings_cloned['form_fields'] as $form_field_key => $form_field_value ) {
			if ( 'terms_and_conditions' === $form_field_key ) {
				if ( ! empty( $general_settings_cloned['form_fields']['terms_use_in_all'] ) ) {
					$settings['formFields'][ $form_field_key ] = $form_field_value;
				}
			}

			if ( 'summary_display' === $form_field_key && ! empty( $settings['formFields']['summary_display']['enable'] ) ) {
				if ( ! empty( $general_settings_cloned['form_fields']['summary_display']['use_in_all'] ) ) {
					$settings['formFields'][ $form_field_key ] = $form_field_value;
					$settings['formFields']['summary_display']['enable'] = true;
				}
			}

			if ( 'openModalBtnText' === $form_field_key && ! empty( $form_field_value ) ) {
				$settings['formFields'][ $form_field_key ] = $form_field_value;
			}

			if ( 'submitBtnText' === $form_field_key && ! empty( $form_field_value ) ) {
				$settings['formFields'][ $form_field_key ] = $form_field_value;
			}

			if ( 'adminEmailAddress' === $form_field_key && ! empty( $form_field_value ) ) {
				$settings['formFields'][ $form_field_key ] = $form_field_value;
			}

			if ( 'emailSubject' === $form_field_key && ! empty( $form_field_value ) ) {
				$settings['formFields'][ $form_field_key ] = $form_field_value;
			}
		}
	}

	if ( ! empty( $general_settings['recaptcha'] ) ) {
		$enable                          = ! isset( $settings['recaptcha']['enable'] ) ? false : $settings['recaptcha']['enable'];
		$settings['recaptcha']           = $general_settings['recaptcha'];
		$settings['recaptcha']['enable'] = $enable;

		if ( empty( $settings['recaptcha'] ) ) {
			$settings['recaptcha'] = 'v2';
		}
	}

	if ( ! empty( $general_settings['paypal']['use_in_all'] ) ) {
		unset( $general_settings['use_in_all'] );
		foreach ( $general_settings['paypal'] as $paypal_field_key => $paypal_field_value ) {
			if ( 'enable' !== $paypal_field_key ) {
				$settings['paypal'][ $paypal_field_key ] = $paypal_field_value;
			}
		}
	}

	if ( ! empty( $general_settings['stripe']['use_in_all'] ) ) {
		unset( $general_settings['use_in_all'] );
		foreach ( $general_settings['stripe'] as $stripe_field_key => $stripe_field_value ) {
			if ( 'enable' !== $stripe_field_key ) {
				$settings['stripe'][ $stripe_field_key ] = $stripe_field_value;
			}
		}
	}

	if ( $render ) {
		unset( $settings['stripe']['secretKey'] );
		unset( $general_settings['stripe']['secretKey'] );
		unset( $settings['paypal']['paypal_email'] );
		unset( $general_settings['paypal']['paypal_email'] );
	}

	return array(
		'settings'         => $settings,
		'general_settings' => $general_settings,
	);
}

function ccb_invoice_logo( $settings ) {
	if ( empty( $settings['invoice']['companyLogo'] ) ) {
		return array();
	}

	$path = $settings['invoice']['companyLogo'];
	$type = pathinfo( $path, PATHINFO_EXTENSION );
	$data = file_get_contents( $path ); //phpcs:ignore
	if ( 'svg' === $type ) {
		return array(
			'key'  => 'svg',
			'data' => base64_encode( $data ), //phpcs:ignore
		);
	}

	return array(
		'key'  => 'image',
		'data' => 'data:image/' . $type . ';base64,' . base64_encode( $data ) //phpcs:ignore
	);
}

add_action( 'admin_bar_menu', 'my_admin_bar_menu', 50 );

function my_admin_bar_menu( $wp_admin_bar ) {

	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$wp_admin_bar->add_menu(
		array(
			'id'    => 'ccb-admin-menu',
			'title' => '<img class="ccb-icon-logo" src="' . CALC_URL . '/frontend/dist/img/ccb-logo.svg' . '"/>' . __( 'Cost Calculator', 'cost-calculator-builder' ), //phpcs:ignore
			'href'  => get_admin_url( null, 'admin.php?page=cost_calculator_builder' ),
		)
	);

	if ( defined( 'CCB_PRO_VERSION' ) ) {
		$wp_admin_bar->add_menu(
			array(
				'parent' => 'ccb-admin-menu',
				'id'     => 'ccb-admin-menu-items-orders',
				'title'  => __( 'Orders', 'cost-calculator-builder' ),
				'href'   => get_admin_url( null, 'admin.php?page=cost_calculator_orders' ),
				'meta'   => array(
					'class' => 'ccb-admin-menu-item',
				),
			)
		);

		$show_analytics = apply_filters( 'ccb_maybe_show_analytics_menu', true );
		if ( $show_analytics ) {
			$wp_admin_bar->add_menu(
				array(
					'parent' => 'ccb-admin-menu',
					'id'     => 'ccb-admin-menu-items-analytics',
					'title'  => __( 'Analytics', 'cost-calculator-builder' ),
					'href'   => get_admin_url( null, 'admin.php?page=cost_calculator_analytics' ),
					'meta'   => array(
						'class' => 'ccb-admin-menu-item',
					),
				)
			);
		}
	}

	$wp_admin_bar->add_menu(
		array(
			'parent' => 'ccb-admin-menu',
			'id'     => 'ccb-admin-menu-items',
			'title'  => __( 'Calculators', 'cost-calculator-builder' ),
			'href'   => get_admin_url( null, 'admin.php?page=cost_calculator_builder' ),
			'meta'   => array(
				'class' => 'ccb-admin-menu-item',
			),
		)
	);

	$wp_admin_bar->add_menu(
		array(
			'parent' => 'ccb-admin-menu',
			'id'     => 'ccb-admin-menu-items-create',
			'title'  => __( 'Create Calculator', 'cost-calculator-builder' ),
			'href'   => get_admin_url( null, 'admin.php?page=cost_calculator_builder&create-calc-from-menu=1' ),
			'meta'   => array(
				'class' => 'ccb-admin-menu-item',
			),
		)
	);

	$wp_admin_bar->add_menu(
		array(
			'parent' => 'ccb-admin-menu',
			'id'     => 'ccb-admin-menu-items-settings',
			'title'  => __( 'Global Settings', 'cost-calculator-builder' ),
			'href'   => get_admin_url( null, 'admin.php?page=cost_calculator_builder&tab=settings' ),
			'meta'   => array(
				'class' => 'ccb-admin-menu-item',
			),
		)
	);

	$wp_admin_bar->add_menu(
		array(
			'parent' => 'ccb-admin-menu',
			'id'     => 'ccb-admin-menu-items-community',
			'title'  => __( 'Community', 'cost-calculator-builder' ),
			'href'   => 'https://www.facebook.com/groups/costcalculator',
			'meta'   => array(
				'class'  => 'ccb-admin-menu-item',
				'target' => '_blank',
			),
		)
	);

	$wp_admin_bar->add_menu(
		array(
			'parent' => 'ccb-admin-menu',
			'id'     => 'ccb-admin-menu-items-documentation',
			'title'  => __( 'Documentation', 'cost-calculator-builder' ),
			'href'   => 'https://docs.stylemixthemes.com/cost-calculator-builder/',
			'meta'   => array(
				'class'  => 'ccb-admin-menu-item',
				'target' => '_blank',
			),
		)
	);

	if ( ! defined( 'CCB_PRO_VERSION' ) ) {
		$wp_admin_bar->add_menu(
			array(
				'parent' => 'ccb-admin-menu',
				'id'     => 'ccb-admin-menu-items-upgrade',
				'title'  => __( 'Upgrade', 'cost-calculator-builder' ),
				'href'   => get_admin_url( null, 'admin.php?page=cost_calculator_gopro' ),
				'meta'   => array(
					'class' => 'ccb-admin-menu-item',
				),
			)
		);
	}
}

function override_admin_bar_css() {

	if ( is_admin_bar_showing() ) { ?>

		<style type="text/css">
		#wp-admin-bar-ccb-admin-menu {
			min-width: 168px;
		}
		#wp-admin-bar-ccb-admin-menu .ab-item {
			font-size: 14px;
			padding-left: 20px !important;
			padding-right: 20px !important;
			display: flex !important;
			align-items: center;
		}

		#wp-admin-bar-ccb-admin-menu .ab-item .ccb-icon-logo {
			margin-right: 10px;
			color: #1AB163;
			width: 20px;
		}

		#wp-admin-bar-ccb-admin-menu .ab-submenu {
			padding: 0 !important;
		}

		#wp-admin-bar-ccb-admin-menu-default {
			max-width: 100%;
			overflow: hidden;
		}

		.ccb-admin-menu-item .ab-item {
			height: 100% !important;
			font-size: 14px !important;
			line-height: 17px !important;
			padding: 6px 0 !important;
			transition: 200ms ease;
			color: rgba(255, 255, 255, 0.7);
		}

		#wp-admin-bar-ccb-admin-menu-items-upgrade .ab-item{
			background-color: #1AB163 !important;
			color: #fff !important;
		}

		#wp-admin-bar-ccb-admin-menu-items-upgrade .ab-item:hover {
			background-color: #148b5d !important;
		}

		.ccb-admin-menu-item:hover {
			background-color: #1AB163 !important;
		}

		.ccb-admin-menu-item:hover a {
			background-color: #1AB163 !important;
			color: #fff !important;
		}

		</style>

		<?php
	}
}

// on backend area
add_action( 'admin_head', 'override_admin_bar_css' );

// on frontend area
add_action( 'wp_head', 'override_admin_bar_css' );

function ccb_embed_popup_text() {
	return array(
		'title'                => esc_html__( 'Calculator embed options', 'cost-calculator-builder' ),
		'subtitle'             => esc_html__( 'We can help embed your calculator with just a few clicks!', 'cost-calculator-builder' ),
		'select_page'          => esc_html__( 'Embed to existing page', 'cost-calculator-builder' ),
		'select_page_subtitle' => esc_html__( 'Embed your calculator into an existing page.', 'cost-calculator-builder' ),
		'create_page'          => esc_html__( 'Embed to new page', 'cost-calculator-builder' ),
		'create_page_subtitle' => esc_html__( 'Embed your calculator into a newly created page.', 'cost-calculator-builder' ),
		'insert'               => esc_html__( 'Embed manually', 'cost-calculator-builder' ),
		'insert_subtitle'      => esc_html__( 'Use a WordPress shortcode to embed the calculator into any place.', 'cost-calculator-builder' ),
		'create_button'        => esc_html__( 'Create Page', 'cost-calculator-builder' ),
		'create_placeholder'   => esc_html__( 'Enter page name' ),
		'apply'                => esc_html__( 'Apply', 'cost-calculator-builder' ),
		'pages_selected'       => esc_html__( 'pages selected', 'cost-calculator-builder' ),
		'page_select'          => esc_html__( 'Select Pages', 'cost-calculator-builder' ),
		'shortcode'            => esc_html__( 'Calculator Shortcode', 'cost-calculator-builder' ),
		'copyText'             => esc_html__( 'Shortcode copied successfully', 'cost-calculator-builder' ),
	);

}

function ccb_set_admin_url() {
	if ( empty( get_option( 'ccb_lock_templates_email', '' ) ) ) {
		$admin_email = get_option( 'admin_email' );
		update_option( 'ccb_lock_templates_email', sanitize_text_field( $admin_email ) );
		update_option( 'ccb_lock_templates', defined( 'CCB_PRO_VERSION' ) );
	}
}

function convertStdClassToArray( $data ) {
	if ( is_object( $data ) && get_class( $data ) === 'stdClass' ) {
		$data = json_decode( wp_json_encode( $data ), true );
	} elseif ( is_array( $data ) ) {
		foreach ( $data as &$value ) {
			$value = convertStdClassToArray( $value );
		}
	}

	return $data;
}

function ccb_array_merge_recursive_left_source( $array1, $array2 ) {
	$merged = $array1;

	foreach ( $array2 as $key => $value ) {
		if ( is_array( $value ) && isset( $merged[ $key ] ) && is_array( $merged[ $key ] ) ) {
			$merged[ $key ] = ccb_array_merge_recursive_left_source( $merged[ $key ], $value );
		} elseif ( is_numeric( $key ) ) {
			if ( ! in_array( $value, $merged, true ) ) {
				$merged[] = $value;
			}
		} else {
			$merged[ $key ] = $value;
		}
	}

	return $merged;
}

function ccb_generate_random_string( $length = 10 ) {
	$characters       = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$charactersLength = strlen( $characters );
	$randomString     = '';
	for ( $i = 0; $i < $length; $i++ ) {
		$randomString .= $characters[ random_int( 0, $charactersLength - 1 ) ];
	}

	return $randomString;
}

function ccb_format_history_created( $dateString ) {
	$now = new DateTime();

	list( $time, $date )        = explode( ' - ', $dateString );
	list( $day, $month, $year ) = sscanf( $date, '%d.%d.%d' );
	$inputDate                  = new DateTime( "$year-$month-$day $time" );
	$timeDifferenceInSeconds    = $now->getTimestamp() - $inputDate->getTimestamp();

	if ( $timeDifferenceInSeconds < 60 ) {
		return __( 'just now', 'cost-calculator-builder' );
	} elseif ( $timeDifferenceInSeconds < 3600 ) {
		$minutesAgo = floor( $timeDifferenceInSeconds / 60 );
		return $minutesAgo . ' ' . __( 'minute', 'cost-calculator-builder' ) . ( 1 === intval( $minutesAgo ) ? '' : 's' ) . ' ' . __( 'ago', 'cost-calculator-builder' );
	} elseif ( 86400 > $timeDifferenceInSeconds && $inputDate->format( 'Y-m-d' ) === $now->format( 'Y-m-d' ) ) {
		$hoursAgo = floor( $timeDifferenceInSeconds / 3600 );
		return $hoursAgo . ' ' . __( 'hour', 'cost-calculator-builder' ) . ( 1 === intval( $hoursAgo ) ? '' : 's' ) . ' ' . __( 'ago', 'cost-calculator-builder' );
	} elseif ( $timeDifferenceInSeconds < 172800 && $inputDate->format( 'Y-m-d' ) === $now->modify( '-1 day' )->format( 'Y-m-d' ) ) {
		return __( 'yesterday', 'cost-calculator-builder' );
	} else {
		$daysAgo = floor( $timeDifferenceInSeconds / 86400 );
		return $daysAgo . ' ' . __( 'day', 'cost-calculator-builder' ) . ( 1 === intval( $daysAgo ) ? '' : 's' ) . ' ' . __( 'ago', 'cost-calculator-builder' );
	}
}

function ccb_truncate_string( $input_string, $allowed_length = 40 ) {
	if ( strlen( $input_string ) > $allowed_length ) {
		return substr( $input_string, 0, $allowed_length - 3 ) . '...';
	} else {
		return $input_string;
	}
}

function ccb_pro_features_page_tab( $tabs ) {
	if ( ! defined( 'CCB_PRO_PATH' ) ) {
		$tabs['ccb_pro_features'] = __( 'Cost Calculator Pro Features', 'cost-calculator-builder' );
		wp_enqueue_style( 'ccb-admin-app-css', CALC_URL . '/frontend/dist/css/admin.css', array(), CALC_VERSION );
	}
	return $tabs;
}

add_filter( 'install_plugins_tabs', 'ccb_pro_features_page_tab' );

function ccb_pro_features_page_redirect( $tabs ) {
	if ( ! isset( $_GET['tab'] ) || 'ccb_pro_features' !== $_GET['tab'] ) {
		return;
	}
	wp_safe_redirect( admin_url( 'admin.php?page=cost_calculator_pro_features' ) );
	exit;
}

add_action( 'load-plugin-install.php', 'ccb_pro_features_page_redirect' );

function ccb_convert_from_btoa( $data, $convert_into_array = false ) {
	$jsonString = base64_decode( $data ); // phpcs:ignore
	$jsonString = urldecode( $jsonString );

	if ( $convert_into_array ) {
		$jsonString = str_replace( '\"', '"', $jsonString );
		$jsonString = str_replace( "\'", "'", $jsonString );
		$jsonString = str_replace( '\\\\', "\\", $jsonString ); //phpcs:ignore
		$jsonString = json_decode( $jsonString, true );
	}

	return $jsonString;
}

function ccb_is_convert_correct( $jsonString = '' ) {
	$data = json_decode( $jsonString, true );
	return ! empty( $data );
}

function ccb_remove_params_from_url( $url, $params_to_remove ) {
	$url_components = parse_url( $url ); // phpcs:ignore

	if ( ! isset( $url_components['query'] ) ) {
		return $url;
	}

	parse_str( $url_components['query'], $queryParams );

	foreach ( $params_to_remove as $param ) {
		unset( $queryParams[ $param ] );
	}

	$url_components['query'] = http_build_query( $queryParams );

	// Rebuild the final URL
	$finalUrl = $url_components['scheme'] . '://' . $url_components['host'];
	if ( isset( $url_components['path'] ) ) {
		$finalUrl .= $url_components['path'];
	}

	if ( $url_components['query'] ) {
		$finalUrl .= '?' . $url_components['query'];
	}

	return $finalUrl;
}

function ccb_get_sanitized_text( $text ) {
	$text = str_replace( array( '<', '>' ), array( '__lt__', '__gt__' ), $text ); //phpcs:ignore
	$text = sanitize_text_field( $text );
	return str_replace( array( '__lt__', '__gt__' ), array( '<', '>' ), $text ); //phpcs:ignore
}

function ccb_get_format_by_mime( $mime ) {
    //phpcs:disable
    $mimes = array(
        'image/jpeg' => '.jpg',
        'image/png' => '.png',
        'image/gif' => '.gif',
        'image/webp' => '.webp',
        'image/bmp' => '.bmp',
        'image/tiff' => '.tiff',
        'image/svg+xml' => '.svg',
        'audio/mpeg' => '.mp3',
        'audio/wav' => '.wav',
        'audio/ogg' => '.ogg',
        'audio/webm' => '.webm',
        'audio/flac' => '.flac',
        'video/mp4' => '.mp4',
        'video/webm' => '.webm',
        'video/ogg' => '.ogv',
        'video/avi' => '.avi',
        'video/mkv' => '.mkv',
        'video/quicktime' => '.mov',
        'text/plain' => '.txt',
        'text/html' => '.html',
        'text/css' => '.css',
        'text/javascript' => '.js',
        'application/javascript' => '.js',
        'application/json' => '.json',
        'application/xml' => '.xml',
        'text/csv' => '.csv',
        'text/rtf' => '.rtf',
        'application/pdf' => '.pdf',
        'application/msword' => '.doc',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => '.docx',
        'application/vnd.ms-excel' => '.xls',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => '.xlsx',
        'application/vnd.ms-powerpoint' => '.ppt',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation' => '.pptx',
        'application/zip' => '.zip',
        'application/x-rar-compressed' => '.rar',
        'application/x-tar' => '.tar',
        'font/woff' => '.woff',
        'font/woff2' => '.woff2',
        'application/font-woff' => '.woff',
        'application/font-woff2' => '.woff2',
        'font/otf' => '.otf',
        'font/ttf' => '.ttf',
        'application/x-font-ttf' => '.ttf',
        'application/epub+zip' => '.epub',
        'application/msaccess' => '.mdb',
        'application/x-msdownload' => '.exe',
        'application/gzip' => '.gz',
        'application/x-bzip' => '.bz2',
        'application/x-bzip2' => '.bz2',
        'application/x-shockwave-flash' => '.swf',
        'application/octet-stream' => '',  // Generic binary file, no specific extension
    );
    //phpcs:enable

	if ( isset( $mimes[ $mime ] ) ) {
		return $mimes[ $mime ];
	}

	return '';
}

function js_or( ...$args ) {
	foreach ( $args as $arg ) {
		if ( $arg ) {
			return $arg;
		}
	}
	return 0;
}

function ccb_generate_random_handle( $length = 10 ): string {
	$letters = 'abcdefghijklmnopqrstuvwxyz';
	$str     = '';

	for ( $i = 0; $i < $length; $i++ ) {
		$str .= $letters[ random_int( 0, 25 ) ];
	}

	return $str;
}

function ccb_is_valid_ip( $ip ) {
	return filter_var( $ip, FILTER_VALIDATE_IP ) !== false;
}

function ccb_get_date_range_for_period_pro( $period, $custom_date = null ) {
	$from  = null;
	$to    = null;
	$today = new \DateTimeImmutable( 'today' );

	switch ( $period ) {
		case 'today':
			$from = $today->setTime( 0, 0, 0 );
			$to   = $today->setTime( 23, 59, 59 );
			break;
		case 'yesterday':
			$from = $today->modify( '-1 day' )->setTime( 0, 0, 0 );
			$to   = $today->modify( '-1 day' )->setTime( 23, 59, 59 );
			break;
		case 'last_7_days':
			$from = $today->modify( '-6 days' )->setTime( 0, 0, 0 );
			$to   = $today->setTime( 23, 59, 59 );
			break;
		case 'last_30_days':
			$from = $today->modify( '-29 days' )->setTime( 0, 0, 0 );
			$to   = $today->setTime( 23, 59, 59 );
			break;
		case 'last_90_days':
			$from = $today->modify( '-89 days' )->setTime( 0, 0, 0 );
			$to   = $today->setTime( 23, 59, 59 );
			break;
		case 'last_year':
			$from = $today->modify( '-1 year' )->setTime( 0, 0, 0 );
			$to   = $today->setTime( 23, 59, 59 );
			break;
		case 'custom':
			$date_string = $custom_date;

			if ( ! empty( $date_string ) ) {
				if ( strpos( $date_string, ' - ' ) !== false ) {
					$dates = explode( ' - ', $date_string );
					if ( count( $dates ) === 2 ) {
						try {
							$from = \DateTimeImmutable::createFromFormat( 'd/m/Y', trim( $dates[0] ) );
							$to   = \DateTimeImmutable::createFromFormat( 'd/m/Y', trim( $dates[1] ) );

							if ( $from ) {
								$from = $from->setTime( 0, 0, 0 );
							}
							if ( $to ) {
								$to = $to->setTime( 23, 59, 59 );
							}
						} catch ( Exception $e ) {
							$from = null;
							$to   = null;
						}
					}
				} else {
					try {
						$from = \DateTimeImmutable::createFromFormat( 'd/m/Y', trim( $date_string ) );
						if ( $from ) {
							$to   = $from->setTime( 23, 59, 59 );
							$from = $from->setTime( 0, 0, 0 );
						}
					} catch ( Exception $e ) {
						$from = null;
						$to   = null;
					}
				}
			}
			break;
		case 'all':
		default:
			break;
	}

	return array(
		'from' => $from,
		'to'   => $to,
	);
}
function ccb_convert_to_k( $number ) {
	$number = (int) $number;

	if ( $number > 1000 ) {
		return ( $number / 1000 ) . 'k';
	}

	return $number;
}

function ccb_get_cart_series( $series ) {
	if ( 1 === count( $series ) ) {
		return array( $series[0], 0 );
	} elseif ( 0 === count( $series ) ) {
		return array( 0, 0 );
	}

	return $series;
}

function ccb_get_optimal_grouping_for_custom_period( $from, $to ) {
	if ( ! $from || ! $to ) {
		return 'week';
	}

	$diff      = $to->diff( $from );
	$totalDays = $diff->days;

	if ( $totalDays <= 2 ) {
		return 'hour';
	} elseif ( $totalDays <= 7 ) {
		return 'day';
	} elseif ( $totalDays <= 31 ) {
		return 'week';
	} elseif ( $totalDays <= 365 ) {
		return 'month';
	} else {
		return 'year';
	}
}

function ccb_smart_format( $value, $precision = 2 ) {
	$float = round( floatval( $value ), $precision );

	if ( 0.0 === fmod( $float, 1.0 ) ) {
		return (int) $float;
	}

	return $float;
}

function ccb_to_fixed( $number, $decimals = 2 ) {
	return number_format( $number, $decimals, '.', '' );
}

function ccb_parse_currency_format( $str ) {
	$str = $str ? $str : '';

	$result = array(
		'currency_sign'      => '',
		'currency_position'  => 'left_with_space',
		'thousand_separator' => ',',
		'decimal_separator'  => '.',
		'number_of_decimals' => 2,
	);

	$str = trim( $str );

	if ( preg_match( '/^([^\d\s]+)/', $str, $m ) ) { //phpcs:ignore
		$result['currency_sign']     = $m[1];
		$result['currency_position'] = 0 === strpos( $str, $m[1] . ' ' )
			? 'left_with_space'
			: 'left';
	} elseif ( preg_match( '/([^\d\s]+)$/', $str, $m ) ) { //phpcs:ignore
		$result['currency_sign']     = $m[1];
		$result['currency_position'] = preg_match( '/\s' . preg_quote( $m[1], '/' ) . '$/', $str ) //phpcs:ignore
			? 'right_with_space'
			: 'right';
	}

	$numericPart = trim( str_replace( $result['currency_sign'], '', $str ) );

	if ( preg_match( '/\d([.,])\d+$/', $numericPart, $m ) ) { //phpcs:ignore
		$result['decimal_separator'] = $m[1];
	}

	if ( false !== strpos( $numericPart, $result['decimal_separator'] ) ) {
		$result['number_of_decimals'] = strlen( explode( $result['decimal_separator'], $numericPart )[1] );
	}

	$integerPart = explode( $result['decimal_separator'], $numericPart )[0];
	if ( preg_match( '/\d{1,3}([.,])\d{3}/', $integerPart, $m ) ) { //phpcs:ignore
		$result['thousand_separator'] = $m[1];
	}

	return $result;
}

function ccb_slug_to_label( $slug ) {
	if ( empty( $slug ) ) {
		return '';
	}

	$label    = preg_replace( '/[-_]+/', ' ', $slug );
	$words    = explode( ' ', strtolower( $label ) );
	$acronyms = array( 'id', 'api', 'url', 'ip' );

	foreach ( $words as &$word ) {
		$word = in_array( $word, $acronyms, true ) ? strtoupper( $word ) : ucfirst( $word );
	}

	return implode( ' ', $words );
}

function ccb_totals_email_discount( $value, $currency_settings ) {
	if ( ! is_numeric( $value ) ) {
		return $value;
	}

	$decimals           = $currency_settings['number_of_decimals'] ?? 2;
	$decimal_point      = $currency_settings['decimal_separator'] ?? '.';
	$thousand_separator = $currency_settings['thousand_separator'] ?? ',';
	$position           = $currency_settings['currency_position'] ?? 'left';
	$currency_sign      = $currency_settings['currency_sign'] ?? '$';

	$formattedValue = number_format( $value, $decimals, $decimal_point, $thousand_separator );

	switch ( $position ) {
		case 'left_with_space':
			return $currency_sign . ' ' . $formattedValue;
		case 'right_with_space':
			return $formattedValue . ' ' . $currency_sign;
		case 'right':
			return $formattedValue . $currency_sign;
		case 'left':
		default:
			return $currency_sign . $formattedValue;
	}
}
