<?php
/**
 * Abandoned Cart Logic Trait.
 *
 * @package automation-web-platform
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/**
 * Trait WAWP_Abandoned_Cart_Logic.
 * Handles core logic for capturing and managing abandoned carts.
 */
trait WAWP_Abandoned_Cart_Logic {

	/**
	 * Check if the request is from a bot.
	 */
	public function is_bot() {
		if ( ! isset( $_SERVER['HTTP_USER_AGENT'] ) || empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
			return true;
		}

		$ua   = strtolower( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) );
		$bots = array(
			'bot',
			'crawl',
			'slurp',
			'spider',
			'mediapartners',
			'facebookexternalhit',
			'client',
			'twitterbot',
			'bingpreview',
			'curl/',
			'libcurl',
			'wget/',
			'python-requests',
			'python-urllib',
			'go--client',
			'java/',
			'okhttp',
			'ie',
			'axios/',
			'zgrab',
			'masscan',
			'nmap',
			'nikto',
			'nuclei',
			'sqlmap',
			'dirbuster',
			'wfuzz',
			'gobuster',
			'burpsuite',
			'pingdom',
			'uptimerobot',
			'statuscake',
			'freshping',
			'hetrixtools',
			'newrelic',
			'datadog',
			'appdynamics',
			'dynatrace',
			'zabbix',
			'k6/',
			'locust/',
			'jmeter',
			'gatling',
			'headlesschrome',
			'phantomjs',
			'slimerjs',
		);
		foreach ( $bots as $b ) {
			if ( strpos( $ua, $b ) !== false ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Get IP country code from cookie.
	 */
	public function get_ip_country_code() {
		if ( isset( $_COOKIE['wawp_user_country'] ) ) {
			return sanitize_text_field( wp_unslash( $_COOKIE['wawp_user_country'] ) );
		}

		return '';
	}

	/**
	 * Add history event to session.
	 *
	 * @param string $type Event type.
	 * @param mixed  $data Event data.
	 */
	public function add_history_event( $type, $data ) {
		if ( empty( $_SESSION['wac_session'] ) ) {
			return;
		}

		global $wpdb;
		$table       = $wpdb->prefix . 'wawp_abandoned_carts';
		$wac_session = isset( $_SESSION['wac_session'] ) ? sanitize_text_field( wp_unslash( $_SESSION['wac_session'] ) ) : '';

		if ( ! $wac_session ) {
			return;
		}

		$cache_key = 'wawp_ac_history_' . md5( $wac_session );
		$row       = wp_cache_get( $cache_key, 'wawp_ac' );

		if ( false === $row ) {
			$row = WAWP()->db->get_results_cached( $wpdb->prepare( 'SELECT page_history FROM %i WHERE session_id = %s ORDER BY id DESC LIMIT 1', $table, $wac_session ), $cache_key, 'wawp_ac', 300 );
			$row = ! empty( $row ) ? (object) $row[0] : null;
		}

		$history = array();
		if ( $row && $row->page_history ) {
			$decoded = json_decode( $row->page_history, true );
			if ( is_array( $decoded ) ) {
				$history = $decoded;
			}
		}

		if ( 'page' === $type && ! empty( $history ) ) {
			$keys       = array_keys( $history );
			$last_key   = end( $keys );
			$last_event = $history[ $last_key ];
			if ( isset( $last_event['type'] ) && 'page' === $last_event['type'] && isset( $last_event['data']['url'] ) && $last_event['data']['url'] === $data['url'] ) {
				$history[ $last_key ]['timestamp'] = time();
				WAWP()->db->update_row( 'abandoned_carts', array( 'page_history' => wp_json_encode( $history ) ), array( 'session_id' => $wac_session ) );
				wp_cache_delete( $cache_key, 'wawp_ac' );
				return;
			}
		}

		if ( 'cart_add' === $type && ! empty( $history ) ) {
			$last_event = end( $history );
			if ( isset( $last_event['type'] ) && 'cart_add' === $last_event['type'] && isset( $last_event['timestamp'] ) && ( time() - $last_event['timestamp'] < 3 ) && isset( $last_event['data'] ) && $last_event['data'] === $data ) {
				return;
			}
		}

		$new_event = array(
			'type'      => $type,
			'data'      => $data,
			'timestamp' => time(),
		);
		$history[] = $new_event;

		if ( count( $history ) > 20 ) {
			$history = array_slice( $history, - 20 );
		}

		WAWP()->db->update_row( 'abandoned_carts', array( 'page_history' => wp_json_encode( $history ) ), array( 'session_id' => $wac_session ) );
		wp_cache_delete( $cache_key, 'wawp_ac' );
	}

	/**
	 * Parse User Agent for browser/OS info.
	 *
	 * @param string $ua User agent string.
	 */
	public function parse_user_agent( $ua ) {
		$b = 'Unknown';
		$o = 'Unknown';
		$d = 'Desktop';
		if ( preg_match( '/android/i', $ua ) ) {
			$o = 'Android';
			$d = 'Mobile';
		} elseif ( preg_match( '/iphone/i', $ua ) ) {
			$o = 'iOS';
			$d = 'Mobile';
		} elseif ( preg_match( '/ipad/i', $ua ) ) {
			$o = 'iOS';
			$d = 'Tablet';
		} elseif ( preg_match( '/windows|win32/i', $ua ) ) {
			$o = 'Windows';
		} elseif ( preg_match( '/macintosh|mac os x/i', $ua ) ) {
			$o = 'Mac';
		} elseif ( preg_match( '/linux/i', $ua ) ) {
			$o = 'Linux';
		}

		if ( preg_match( '/MSIE/i', $ua ) && ! preg_match( '/Opera/i', $ua ) ) {
			$b = 'Internet Explorer';
		} elseif ( preg_match( '/Firefox/i', $ua ) ) {
			$b = 'Firefox';
		} elseif ( preg_match( '/Edg/i', $ua ) ) {
			$b = 'Edge';
		} elseif ( preg_match( '/Chrome/i', $ua ) ) {
			$b = 'Chrome';
		} elseif ( preg_match( '/Safari/i', $ua ) ) {
			$b = 'Safari';
		} elseif ( preg_match( '/Opera/i', $ua ) ) {
			$b = 'Opera';
		}

		return array( $b, $o, $d );
	}

	/**
	 * Get user IP address.
	 */
	public function get_user_ip() {
		$ip = '0.0.0.0';
		if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
			$ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CLIENT_IP'] ) );

		} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
			$ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) );
		} elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
			$ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );

		}

		// Handle comma separated list of IPs.
		if ( strpos( $ip, ',' ) !== false ) {
			$ip_parts = explode( ',', $ip );
			$ip       = trim( $ip_parts[0] );
		}

		return sanitize_text_field( wp_unslash( $ip ) );
	}
}
