<?php

namespace CarDealerPress\includes\helpers;


use CarDealerPress\includes\functions\Logger;

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

class Http_Request {
	use Logger;

	const TIMEOUT = 20;

	public $url = null;

	public $group = null;

	public $request_parameters
		= array(
			'timeout' => self::TIMEOUT,
			'headers' => array(
				'Referer'             => null,
				'X-WordPress-Version' => null,
				'X-Plugin-Version'    => null,
			),
		);
	private $admin_options;

	function __construct( $url, $group ) {
		global $wp, $wp_version;
		$this->url                                      = $url;
		$this->group                                    = $group;
		$this->admin_options                            = get_option( 'cdp_admin_options' );
		$this->request_parameters['headers']['Referer'] = $wp ? site_url() . '/' . $wp->request : site_url() . '/';
		$this->request_parameters['headers']['X-WordPress-Version'] = $wp_version;
		$this->request_parameters['headers']['X-Plugin-Version']    = CDP_VERSION;
	}

	function get_file( $sanitize = false ) {
		$response = wp_remote_request( $this->url, $this->request_parameters );
		if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
			if ( true === $sanitize ) {
				$response['body'] = wp_kses_data( $response['body'] );
			}

			return $response;
		} else {
			if ( is_wp_error( $response ) ) {
				$error_title   = 'CDP WP Error - ';
				$error_code    = $response->get_error_code();
				$error_message = $response->get_error_message();
			} else {
				$error_title   = 'CDP API Error - ';
				$error_code    = wp_remote_retrieve_response_code( $response );
				$error_message = wp_remote_retrieve_response_message( $response );
			}
			$error_array = array(
				'code'    => $error_code,
				'message' => $error_message,
			);
			if ( $this->admin_options['admin']['general']['debug_plugin_info'] ) {
				$this->append_log( array( 'message' => 'CDP Message: Version: ' . CDP_VERSION . ' | ' . $error_title . ' code: ' . $error_code . ' | message: ' . $error_message . ' | call: ' . $this->url ) );
			}

			return $error_array;
		}
	}

	public function cache_file( $data ) {
		return wp_cache_add( $this->url, $data, $this->group, 7200 );
	}

	public function cached() {
		return wp_cache_get( $this->url, $this->group );
	}

}
