<?php

namespace CarDealerPress\Includes\Helpers;

use CarDealerPress\includes\functions\Logger;
use WP_Http;

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

class Remote_Requests {
	use Logger;

	public static function http_get_file(string $params, bool $purge = false): array
	{
		// TODO future add a param for api_key. future implementation.
		$request_args = self::build_request_arguments( $params, $purge );

		if ($purge) {
			// when purged, last-modified is null.
			// first call passes the 'purge' header param, second call is a normal 'get' request.
			// allows for the last-modified header to be returned.
			// only called in the purge process.
			$purged_response = wp_remote_request( BASE_INVENTORY_API_URL . $params, $request_args );
			$purge = false;
			$request_args = self::build_request_arguments( $params, $purge );
		}
		$response = wp_remote_request( BASE_INVENTORY_API_URL . $params, $request_args );

		return self::handle_response($response);
	}

	private static function build_request_arguments(string $params, bool $purge): array
	{
		$headers = self::build_headers($purge);

		// Build the request arguments
		$args = [
			'headers'     => $headers,
			'body'        => null,
			'data_format' => 'body',
			'method' => $purge ? 'PURGE': 'GET',
		];
		$args['headers']['Content-Type'] = 'application/json';

		return $args;
	}

	private static function build_headers(bool $purge): array
	{
		$headers = [
			'Referer'     => site_url(),
			'User-Agent'  => 'Mozilla/5.0 (compatible; MyScript/1.0)',
		];

		if ($purge) {
			$headers['fastly-soft-purge'] = 1;
		}

		return $headers;
	}

	private static function handle_response($response): array
	{
		if (is_wp_error($response)) {
			return ['error' => true, 'message' => $response->get_error_message()];
		}
		$headers = wp_remote_retrieve_headers($response);
		$body = wp_remote_retrieve_body($response);
		$statusCode = wp_remote_retrieve_response_code($response);

		$unix_time = time();
		$http_date = gmdate('D, d M Y H:i:s', $unix_time) . ' GMT';
		$last_modified = $headers['last-modified'] ?? $http_date; // Failsafe, when purge is used, last-modified is null, use the current time.

		return [
			'error'         => false,
			'status_code'   => $statusCode,
			'headers'       => $headers,
			'last_modified' => $last_modified,
			'body'          => $body,
		];
	}

	public static function check_for_valid_company_id( $dealer_id ) {
		$api_params    = '/api/companies/' . $dealer_id;
		$response      = self::http_get_file( $api_params );

		$response_code = isset($response) ? $response['status_code'] : '';
		// todo future add other response codes.
		if ( 200 === $response_code || 304 === $response_code ) {
			return $response;
		} else {
			return false;
		}
	}

	public static function api_vehicle_vdp_call( $dealer_id, $vin ) {
		$api_params = "/$dealer_id/inventory/vehicles.json?vin=$vin";
		$response   = self::http_get_file( $api_params );
		$response_body                     = json_decode( $response['body'] );
		$api_vehicle['dealer_options']     = $response_body->dealer_options ?? '';
		$api_vehicle['standard_equipment'] = $response_body->standard_equipment ?? array();
		$api_vehicle['photos_raw']         = $response_body->photos ?? array();
		return $api_vehicle;
	}
}
