<?php

namespace CarDealerPress\Includes\Functions;

use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\helpers\helpers;
use CarDealerPress\includes\helpers\Http_Request;
use CarDealerPress\Includes\Helpers\Option;

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

class Maps {

	public function map_population( $dealer_id, $key = null ) {
		$map_key  = $key ?? Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'detail',
				'maps',
				'key',
			)
		);
		$dealer_id = $dealer_id ?? helpers::company_id();
		$data      = array();
		if ( $map_key && $dealer_id ) {
			if ( helpers::company_id() !== $dealer_id ) { // indicates adding new dealer.
				$dealers = ( new Requests() )->cdp_company_dealer_request( $dealer_id );
			} else {
				$dealers = ( new Requests() )->cdp_db_init( 'company', array( 'pass' => '1' ) );
			}
			foreach ( $dealers as $dealer ) {
				$address = rawurlencode( $dealer['street'] . ' ' . $dealer['city'] . ' ' . $dealer['state'] . ' ' . $dealer['zip'] );
				$geo     = $this->extender_map_get_geocode(
					array(
						'address' => $address,
					)
				);
				$data[]  = array(
					'dealer'  => array(
						'dealer_id' => $dealer['dealer_id'],
						'name'      => $dealer['name'],
					),
					'geocode' => $geo,
				);
			}
		}

		return $data;
	}

	public function extender_map_get_geocode( $args ) {
		$map_key  = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'detail',
				'maps',
				'key',
			)
		);
		$address        = $args['address'] ?? '';
		$geocode_caller = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=$map_key";
		$geocode        = new http_request( $geocode_caller, 'geocode' );
		$geocode_raw    = $geocode->get_file();
		$geocode_data   = ( isset( $geocode_raw['body'] ) && ! empty( $geocode_raw['body'] ) ? json_decode( $geocode_raw['body'], true ) : array() );
		if ( isset( $geocode_data['error_message'] ) ) {
			$error_message                 = $geocode_data['error_message'];
			$error_message                 = preg_replace( '~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~', "<a href=\"\\0\" target='_blank'>\\0</a>", $error_message );
			$geocode_data['error_message'] = $error_message;
		}

		return $geocode_data;
	}
}
