<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
class SafeWP_Setup_Tracking_Access {
	public function __construct() {
	}

	public function track_access_attempt() {
		$request_uri = sanitize_text_field( $_SERVER['REQUEST_URI'] );

		if ( preg_match( '/^\/wp-admin\/?$/', $request_uri ) || preg_match( '/^\/wp-login\.php$/', $request_uri ) ) {
			global $wpdb;
			$table_name = $wpdb->prefix . 'iron_security_logs';

			$ip_address = filter_var( $_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP );
			$country    = $this->get_country_by_ip( $ip_address );
			$url        = esc_url_raw( $_SERVER['REQUEST_URI'] );
			$time       = current_time( 'mysql' );

			if ( $this->is_ip_blocked( $ip_address ) ) {
//				$this->log_blocked_attempt( $ip_address, $url, $country );
			} else {
				$wpdb->insert(
					$table_name,
					array(
						'log_type'     => 'access_attempt',
						'user_id'      => null,
						'username'     => null,
						'ip_address'   => $ip_address,
						'message'      => __('Access attempt to: ', 'iron-security') . $url,
						'status'       => 'attempt',
						'date_created' => $time,
						'extra_data'   => maybe_serialize( array(
							'country' => $country,
							'url'     => $url,
						) ),
					),
					array( '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s' )
				);
			}
		}
	}


	public function get_country_by_ip( $ip ) {
		$response = wp_remote_get( "https://ipinfo.io/{$ip}/json" );
		if ( is_wp_error( $response ) ) {
			return 'Unknown';
		}
		$body = wp_remote_retrieve_body( $response );
		$data = json_decode( $body );

		return isset( $data->country ) ? $data->country : 'Unknown';
	}

	public function wpironis_access_log_results() {
		global $wpdb;
		$table_name = $wpdb->prefix . 'iron_security_logs';

		$results = $wpdb->get_results( "
			SELECT ip_address, status, log_type, COUNT(*) as attempts 
			FROM $table_name 
			WHERE log_type IN ('access_attempt', 'blocked_attempt')
			GROUP BY ip_address, status, log_type 
			ORDER BY attempts DESC
		" );

		return $results;
	}

	public function log_blocked_attempt( $ip_address, $url, $country = 'Unknown' ) {
		global $wpdb;
		$table_name = $wpdb->prefix . 'iron_security_logs';
		$time = current_time( 'mysql' );

		$wpdb->insert(
			$table_name,
			array(
				'log_type'     => 'blocked_attempt',
				'user_id'      => null,
				'username'     => null,
				'ip_address'   => $ip_address,
				'message'      => __('Blocked access to: ', 'iron-security') . $url,
				'status'       => 'blocked',
				'date_created' => $time,
				'extra_data'   => maybe_serialize( array(
					'country' => $country,
					'url'     => $url,
				) ),
			),
			array( '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s' )
		);
	}

	private function is_ip_blocked( $ip_address ) {
		return get_transient( $ip_address . '_wpis_lockout' ) ? true : false;
	}

}