<?php

namespace CarDealerPress\includes\functions;

use CarDealerPress\Includes\Database\Requests;

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

class VehicleManagementSystem {

	public $host       = null;
	public $tracer     = null;
	public $company_id = 0;
	private $url       = null;

	public function __construct( $host, $company_id ) {
		$this->host       = $host;
		$this->company_id = $company_id;
	}

	public function get_inventory( $args ) {
		$parameters = $args['parameters'] ?? array();

		return ( new Requests() )->cdp_db_init( 'inventory', $parameters );
	}

	public function get_makes( $args ) {
		$params = $args['parameters'] ?? array();

		$makes_and_count = ( new Requests() )->cdp_db_init( 'make', $params );
		if ( ! empty( $makes_and_count ) ) {
			foreach ( $makes_and_count as $make ) {
				$makes[] = $make['make'];
			}
		} else {
			$makes = array();
		}

		return $makes;
	}

	public function get_models( $args ) {
		$alt_id           = $args['alt_id'] ?? 0;
		$params           = $args['parameters'] ?? array();
		$models_and_count = ( new Requests() )->cdp_db_init( 'model', $params );
		if ( ! empty( $models_and_count ) ) {
			foreach ( $models_and_count as $model ) {
				$models[] = $model['model'];
			}
		} else {
			$models = array();
		}

		return $models;
	}

	public function get_trims( $args ) {
		$alt_id          = $args['alt_id'] ?? 0;
		$params          = $args['parameters'] ?? array();
		$trims_and_count = ( new Requests() )->cdp_db_init( 'trim', $params );
		if ( ! empty( $trims_and_count ) ) {
			foreach ( $trims_and_count as $trim ) {
				$trims[] = $trim['trim'];
			}
		} else {
			$trims = array();
		}

		return $trims;
	}

	public function get_custom_pricing( $vehicle_id ) {
		$this->url = $this->host . '/api/prices/' . $vehicle_id . '.json';

		return $this;
	}

	// TODO future, add dealers that have been 'added' and are not part of the main dealer automall.
	public function get_automall_geo_data_db() {
		if ( false === ( $geo = get_site_transient( 'dt_geo_data' ) ) ) {
			$geo     = array();
			$company = ( new Requests() )->cdp_db_init( 'company' )[0];
			$dealers = $company['automalls'] ?? array();
			if ( ! empty( $dealers ) && count( $dealers ) > 1 ) {
				foreach ( $company['automalls'] as $dealer_id ) {
					$dealer = ( new Requests() )->cdp_company_dealer_request( $dealer_id )[0];
					if ( ! empty( $dealer['city'] ) && ! empty( $dealer['state'] ) && ! empty( $dealer['zip'] ) ) {
						$geo[ $dealer['state'] ][ $dealer['city'] ][ $dealer['zip'] ][] = $dealer_id;
					}
				}
				set_site_transient( 'dt_geo_data', $geo, 60 * 60 * 12 ); // 12 Hour Expire
			}
		}

		return $geo;
	}
}
