<?php

if ( ! class_exists( 'Entry_Processing' ) ) {
	class Entry_Processing {
		public function __construct() {
			add_filter( 'bw_survey_entry', array( $this, 'filter_entry' ), 10,  2);
			add_filter( 'bw_survey_confirmation', array( $this, 'filter_confirmation' ), 10, 3 );
			add_action( 'bw_survey_notifications', array( $this, 'notifications' ), 10, 2 );
		}

		public function filter_entry ($entry, $survey) {
			$data = array();
			foreach($survey['data']['fields'] as $field_id => $field) {
				if (empty($entry['data'][$field_id])) continue;
				if (empty($field['conditionalLogic']) || $this->check_conditional_logic($field['conditionalLogic'], $entry)) {
					$data[$field_id] = $entry['data'][$field_id];
				}
			}
			$entry['data'] = $data;
			return $entry;			
		}

		public function filter_confirmation ($message, $entry, $survey) {
			global $wpdb;
			$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}bwsurvey_confirmations WHERE survey_id = %d ORDER BY 'priority'", $survey['id']));
			if ($wpdb->last_error) {
				return $this->str_replace($message, $entry, $survey);
			}
			foreach ($results as $confirmation) {
				$data = unserialize($confirmation->data);
				if (empty($data['conditionalLogic']) || $this->check_conditional_logic($data['conditionalLogic'], $entry)) {
					$message = $data['content'];
				}
			}
			return $this->str_replace($message, $entry, $survey);
		}

		public function notifications ($entry, $survey) {
			global $wpdb;
			$results = $wpdb->get_results($wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}bwsurvey_notifications WHERE survey_id = %d AND id NOT IN (SELECT notification_id FROM {$wpdb->prefix}bwsurvey_sent_notifications WHERE entry_id = %d)",
				$survey['id'],
				$entry['id']
			));
			if ($wpdb->last_error) {
				return;
			}
			foreach ($results as $notification) {
				$data = unserialize($notification->data);
				if (empty($data['conditionalLogic']) && $entry['submitted'] || !empty($data['conditionalLogic']) && $this->check_conditional_logic($data['conditionalLogic'], $entry)) {
					// Mark notification as sent
					$wpdb->insert(
						"{$wpdb->prefix}bwsurvey_sent_notifications",
						array(
							'entry_id' => $entry['id'],
							'notification_id' => $notification->id
						),
						array(
							'%d',
							'%d'
						)
					);
					// Send Notification
					// WhatsApp
					if ($notification->type === 'whatsapp') {
						$args = array(
							'to' => $data['to'],
							'template' => $data['template'],
							'language_code' => $data['languageCode'],
							'header_parameters' => array(),
							'body_parameters' => array()
						);
						foreach($data['headerParameters'] as $param) {
							$args['header_parameters'][] = array(
								'type' => 'text',
								'text' => $this->str_replace($param, $entry, $survey)
							);
						}
						foreach($data['bodyParameters'] as $param) {
							$args['body_parameters'][] = array(
								'type' => 'text',
								'text' => $this->str_replace($param, $entry, $survey)
							);
						}
						$this->send_whatsapp_template($args);
					}
					// Email
					if ($notification->type === 'email') {
						wp_mail(
							$data['to'],
							$this->str_replace($data['subject'], $entry, $survey),
							$this->str_replace($data['message'], $entry, $survey)
						);
					}
				}
			}
		}

		private function str_replace ($str, $entry, $survey) {
			preg_match_all('/{field_(label|value):(\d+)}/', $str, $matches);

			return preg_replace_callback('/{field_(label|value):(\d+)}/', function ($match) use($entry, $survey) {
				if ($match[1] == 'label') {
					return isset($survey['data']['fields'][$match[2]]['label']) ? $survey['data']['fields'][$match[2]]['label'] : '';
				}
				if ($match[1] == 'value') {
					return isset($entry['data'][$match[2]]) ? $entry['data'][$match[2]] : '';
				}
			}, $str);

			return $str;
		}

		private function check_conditional_logic ($conditional_logic, $entry) {
			$result = false;
			foreach ($conditional_logic as $group_logic) {
				$group_result = true;
				foreach($group_logic as $condition) {
					if (empty($entry['data'][$condition['field']])) {
						$group_result = false;
					} else if ($condition['operator'] === '==') {
						$group_result = $entry['data'][$condition['field']] == $condition['value'];
					} else if ($condition['operator'] === '<=') {
						$group_result = intval($entry['data'][$condition['field']]) <= intval($condition['value']);
					} else if ($condition['operator'] === '>=') {
						$group_result = intval($entry['data'][$condition['field']]) >= intval($condition['value']);
					} else if ($condition['operator'] === '<') {
						$group_result = intval($entry['data'][$condition['field']]) < intval($condition['value']);
					} else if ($condition['operator'] === '>') {
						$group_result = intval($entry['data'][$condition['field']]) > intval($condition['value']);
					} else if ($condition['operator'] === '!=') {
						$group_result = $entry['data'][$condition['field']] != $condition['value'];
					}
					if (!$group_result) break;
				}
				$result = $group_result;
				if ($result) break;
			}
			return $result;
		}

		private function send_whatsapp_template ( $args ) {
			$whatsapp_options = get_option( 'bw_survey_whatsapp' );
			$phone_number_id = $whatsapp_options['phone_number_id'];
			$access_token = $whatsapp_options['access_token'];

			if (!empty($phone_number_id)) {
				$to = $args['to'];
				$template = $args['template'];
				$language_code = $args['language_code'];
				$header_parameters = $args['header_parameters'];
				$body_parameters = $args['body_parameters'];

				$url = "https://graph.facebook.com/v17.0/{$phone_number_id}/messages";
				$request_arguments = array(
					'method' => 'POST',
					'blocking' => false,
					'headers' => array(
						'Authorization' => "Bearer {$access_token}",
						'Content-Type' => 'application/json'
					)
				);
				foreach ($to as $number) {
					$request_arguments['body'] = json_encode(array(
						'messaging_product' => 'whatsapp',
						'to' => preg_replace('/[^\d]/', '', $number),
						'type' => 'template',
						'template' => array(
							'name' => $template,
							'language' => array(
								'code' => $language_code
							),
							'components' => array(
								array(
									'type' => 'HEADER',
									'parameters' => $header_parameters
								),
								array(
									'type' => 'BODY',
									'parameters' => $body_parameters
								)
							)
						)
					));
					$response = wp_remote_request($url, $request_arguments);
				}
			}
		}

		// private function send_whatsapp_notification ($to, $message) {
		// 	$whatsapp_options = get_option( 'bw_survey_whatsapp' );
		// 	if (!empty($whatsapp_options['phone_number_id'])) {
		// 		$url = "https://graph.facebook.com/v17.0/{$whatsapp_options['phone_number_id']}/messages";
		// 		$request_arguments = array(
		// 			'method' => 'POST',
		// 			// 'blocking' => false,
		// 			'headers' => array(
		// 				'Authorization' => "Bearer {$whatsapp_options['access_token']}",
		// 				'Content-Type' => 'application/json'
		// 			)
		// 		);
		// 		foreach ($to as $number) {
		// 			$args['body'] = $body = json_encode(array(
		// 				'messaging_product' => 'whatsapp',
		// 				'recipient_type' => 'individual',
		// 				'to' => preg_replace('/[^\d]/', '', $number),
		// 				'type' => 'text',
		// 				'text' => array(
		// 					'preview_url' => false,
		// 					'body' => $message,
		// 				)
		// 			));
		// 			$response = wp_remote_request($url, $args);
		// 		}
		// 	}
		// }
	}
}
