<?php

class Tbm_Tagmailer_Common {

	public function tbm_write_log( $text = '', $data = array(), $level = 'info', $name = '' ): bool {
		return false;
	}

	public function tbm_send_rocket_notifications( $message = array(), $level = 'warning', $interval = 10 ): bool {
		return false;
	}

	public function tbm_replace_wp_entities( $title ) {

		if ( ! $title ) {
			return '';
		}

		return str_replace(
			array(
				'&#8220;',
				'&#8221;',
				'&#8222;',
				'&#8230;',
				'&#8217;',
				'&#8211;',
				'&nbsp;'
			),
			array(
				'"',
				'"',
				'"',
				'...',
				'\'',
				'-',
				' ',
			), $title );

	}

	public function html_get_client_ip(): string {
		if ( isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ) {
			$ipaddress = $_SERVER['HTTP_CF_CONNECTING_IP'];
		} else if ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
			$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
		} else if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
			$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else if ( isset( $_SERVER['HTTP_X_FORWARDED'] ) ) {
			$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
		} else if ( isset( $_SERVER['HTTP_FORWARDED_FOR'] ) ) {
			$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
		} else if ( isset( $_SERVER['HTTP_FORWARDED'] ) ) {
			$ipaddress = $_SERVER['HTTP_FORWARDED'];
		} else if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
			$ipaddress = $_SERVER['REMOTE_ADDR'];
		} else {
			$ipaddress = '127.0.0.1';
		}

		return $ipaddress;
	}

	public function tbm_gump_send_success_response( $body = array( '' ), $message = 'message', $title = 'response', $headers = array() ) {

		/**
		 * {
		 * "status": "success",
		 * "data": "code_200_optin",
		 * "message": "Risultato code_200_optin",
		 * "title": "success"
		 * }
		 *
		 * {
		 * "success": true,
		 * "status": "success",
		 * "data": "code_200_optin",
		 * "message": "Risultato code_200_optin",
		 * "title": "success"
		 * }
		 */

		$data = array(
			'status'  => 'success',
			'data'    => $body,
			'message' => $message,
			'title'   => $title,
		);

		wp_send_json($data, 200);

		exit;
	}

	public function tbm_gump_send_error_response( $body = '', $message = 'message', $title = 'error', $headers = array() ) {

		if ( is_object( $body ) && method_exists( $body, 'get_errors_array' ) ) {
			$message = $body->get_errors_array();
		} else {
			$message = $body;
		}

		$data = array(
			'status'  => 'error',
			'data'    => $body,
			'message' => $message,
			'title'   => $title,
		);

		wp_send_json($data, 400);

	}

	public function tbm_log( $data = null, bool $die = true ) {
		$style = 'text-align: left;font-size:17px;line-height:25px;font-family: "Courier New", Courier, monospace;z-index: 999999;background-color: white;position: absolute;top: 0;left: 0;width: 99%;padding: 10px 0 10px 10px;border: 2px solid lightsalmon;';
		echo '<script>document.onkeydown=function(a){a=a||window.event;if("key"in a?"Escape"==a.key||"Esc"==a.key:27==a.keyCode)document.getElementById(\'tbm_log\').style.display="none"};</script>';
		echo "<div id='tbm_log' style='{$style}'><h3 style='margin-top: 10px;font-family: arial'>Log</h3>\n";
		highlight_string( "<?php\n\$data =\n" . var_export( $data, true ) . ";\n?>" );
		echo "</div>\n";
		if ( $die ) {
			die( 'finito' );
		}
	}

	public function tagmailer_generate_final_content( $content = '' ) {
		global $post;

		if ( is_admin() ) {
			return $content;
		}

		$html_newsletter = $this->html_newsletter_get_template();
		$html_newsletter = apply_filters( 'newsletter_html_parser_template', $html_newsletter );

		/**
		 * Print privacy policy URL
		 */
		$privacy_url     = get_field( "tbl_nl_policy_url", "option" ) ?: "/privacy-policy";
		$privacy_url     = apply_filters( "newsletter_privacy_url", $privacy_url );
		$html_newsletter = str_replace( '%%PRIVACY_URL%%', $privacy_url, $html_newsletter );

		/**
		 *Define CTA
		 */
		$categories    = get_the_category( $post->ID );
		$category_name = '';
		if ( ! empty( $categories ) ) {
			$category_name = $categories[0]->name;
		}

		$cta_title       = $category_name ?: $post->post_title;
		$html_newsletter = str_replace( array('%%TITLE%%','%%title%%'), $cta_title, $html_newsletter );

		$content .= $html_newsletter;

		return $content;
	}

	public function tbm_get_container_id() {
		/**
		 * Get the default list
		 */
		$default_list = get_field( "tbl_nl_list_id", "option" );

		if ( ! $default_list ) {
			return false;
		}

		// Get multilist configuration
		$multilists = get_field( "tbm_nl_mutilist", "option" );

		if ( ! $multilists ) {
			return $default_list;
		}

		// Get current category and tag
		$post       = get_the_ID();
		$categories = get_the_terms( $post, 'category' );
		$post_tags  = get_the_terms( $post, 'post_tag' );

		$categories_id  = wp_list_pluck( $categories, 'term_id' );
		$tags_id        = wp_list_pluck( $post_tags, 'term_id' );
		$post_type_name = array( get_post_type( $post ) );

		// Set the default values
		$this_category  = false;
		$this_tag       = false;
		$this_post_type = false;

		foreach ( $multilists as $multilist ) {

			if ( ! $multilist['multilist_id'] ) {
				continue;
			}

			if ( $multilist['category'] ) {
				// Check if the array 'category' contains the current category
				if ( array_intersect( $multilist['category'], $categories_id ) ) {
					$this_category = true;
				}
			} else {
				// If the array 'category' is empty, means that the multilist is for all the categories
				$this_category = true;
			}

			if ( $multilist['post_tag'] ) {
				// Check if the array 'post_tag' contains the current tag
				if ( array_intersect( $multilist['post_tag'], $tags_id ) ) {
					$this_tag = true;
				}
			} else {
				// If the array 'post_tag' is empty, means that the multilist is for all the tags
				$this_tag = true;
			}

			if ( $multilist['post_type'] ) {
				// Check if the array 'post_type' contains the current post_type
				if ( array_intersect( $multilist['post_type'], $post_type_name ) ) {
					$this_post_type = true;
				}
			} else {
				// If the array 'post_type' is empty, means that the multilist is for all the post_type
				$this_post_type = true;
			}

			// If all the conditions are true, return the multilist id
			if ( $this_category && $this_tag && $this_post_type ) {
				return $multilist['multilist_id'];
			}
		}

		return $default_list;
	}

	/**
	 * @return false|string
	 */
	private function html_newsletter_get_template() {

		// controllo se c'è una directory newsletter/newsletter.php da cui recuperare il template da utilizzare
		if ( file_exists( get_template_directory() . '/partials/tbm-tagmailer-public-display.php' ) ) {
			$html_path = get_template_directory() . '/partials/tbm-tagmailer-public-display.php';
		} else {
			$html_path = TBM_TAGMAILER_PLUGIN_DIR . 'public/partials/tbm-tagmailer-public-display.php';
		}

		// Get the form content
		ob_start();
		include( $html_path );
		$contents = ob_get_contents();
		ob_end_clean();

		return $contents;

	}

	public function get_gender() {
		return apply_filters( 'tagmailer_form_gender', array(
			"F" => "Femminile",
			"M" => "Maschile",
			"X" => "Non binario",
		) );
	}

	public function get_birth_date() {
		$date = array();

		$from = idate( 'Y' ) - 100;
		$to   = idate( 'Y' ) - 18;

		for ( $year = $from; $year <= $to; ++ $year ) {
			$date[ $year ] = $year;
		}

		return apply_filters( 'tagmailer_form_birth_date', $date );
	}

	public function get_qualifications() {
		return apply_filters( 'tagmailer_form_qualifications', array(
			"1" => "Nessuno",
			"2" => "Licenza elementare",
			"3" => "Licenza media inferiore",
			"4" => "Diploma scuola media sup.",
			"5" => "Diploma di laurea",
			"6" => "Laurea",
			"7" => "Specializzazione",
			"8" => "Dottorato",
		) );
	}

	public function get_states() {
		return apply_filters( 'tagmailer_form_states', array(
			"AG" => "Agrigento",
			"AL" => "Alessandria",
			"XX" => "Altro (Estero)",
			"AN" => "Ancona",
			"AO" => "Aosta",
			"AR" => "Arezzo",
			"AP" => "Ascoli Piceno",
			"AT" => "Asti",
			"AV" => "Avellino",
			"BA" => "Bari",
			"BT" => "Barletta-Andria-Trani",
			"BL" => "Belluno",
			"BN" => "Benevento",
			"BG" => "Bergamo",
			"BI" => "Biella",
			"BO" => "Bologna",
			"BZ" => "Bolzano",
			"BS" => "Brescia",
			"BR" => "Brindisi",
			"CA" => "Cagliari",
			"CL" => "Caltanissetta",
			"CB" => "Campobasso",
			"CI" => "Carbonia-Iglesias",
			"CE" => "Caserta",
			"CT" => "Catania",
			"CZ" => "Catanzaro",
			"CH" => "Chieti",
			"CO" => "Como",
			"CS" => "Cosenza",
			"CR" => "Cremona",
			"KR" => "Crotone",
			"CN" => "Cuneo",
			"EN" => "Enna",
			"FM" => "Fermo",
			"FE" => "Ferrara",
			"FI" => "Firenze",
			"FG" => "Foggia",
			"FC" => "Forlì-Cesena",
			"FR" => "Frosinone",
			"GE" => "Genova",
			"GO" => "Gorizia",
			"GR" => "Grosseto",
			"IM" => "Imperia",
			"IS" => "Isernia",
			"SP" => "La Spezia",
			"AQ" => "L'Aquila",
			"LT" => "Latina",
			"LE" => "Lecce",
			"LC" => "Lecco",
			"LI" => "Livorno",
			"LO" => "Lodi",
			"LU" => "Lucca",
			"MC" => "Macerata",
			"MN" => "Mantova",
			"MS" => "Massa-Carrara",
			"MT" => "Matera",
			"VS" => "Medio Campidano",
			"ME" => "Messina",
			"MI" => "Milano",
			"MO" => "Modena",
			"MB" => "Monza e Brianza",
			"NA" => "Napoli",
			"NO" => "Novara",
			"NU" => "Nuoro",
			"OG" => "Ogliastra",
			"OT" => "Olbia-Tempio",
			"OR" => "Oristano",
			"PD" => "Padova",
			"PA" => "Palermo",
			"PR" => "Parma",
			"PV" => "Pavia",
			"PG" => "Perugia",
			"PU" => "Pesaro e Urbino",
			"PE" => "Pescara",
			"PC" => "Piacenza",
			"PI" => "Pisa",
			"PT" => "Pistoia",
			"PN" => "Pordenone",
			"PZ" => "Potenza",
			"PO" => "Prato",
			"RG" => "Ragusa",
			"RA" => "Ravenna",
			"RC" => "Reggio di Calabria",
			"RE" => "Reggio nell'Emilia",
			"RI" => "Rieti",
			"RN" => "Rimini",
			"RM" => "Roma",
			"RO" => "Rovigo",
			"SA" => "Salerno",
			"SS" => "Sassari",
			"SV" => "Savona",
			"SI" => "Siena",
			"SR" => "Siracusa",
			"SO" => "Sondrio",
			"TA" => "Taranto",
			"TE" => "Teramo",
			"TR" => "Terni",
			"TO" => "Torino",
			"TP" => "Trapani",
			"TN" => "Trento",
			"TV" => "Treviso",
			"TS" => "Trieste",
			"UD" => "Udine",
			"VA" => "Varese",
			"VE" => "Venezia",
			"VB" => "Verbania",
			"VC" => "Vercelli",
			"VR" => "Verona",
			"VV" => "Vibo Valentia",
			"VI" => "Vicenza",
			"VT" => "Viterbo",
		) );
	}

	public function get_jobs() {
		return apply_filters( 'tagmailer_form_jobs', array(
			"1"  => "Artigiano/commerciante",
			"2"  => "Casalinga",
			"3"  => "Coltivatore/allevatore",
			"4"  => "Commesso",
			"5"  => "Dirigente",
			"6"  => "Funzionario",
			"7"  => "Impiegato",
			"8"  => "Imprenditore",
			"9"  => "Operaio",
			"10" => "Pensionato",
			"11" => "Professionista",
			"12" => "Studente",
			"13" => "Disoccupato",
			"14" => "Altro",
			"15" => "Quadro",
		) );
	}

}
