<?php
/**
 * EV running-cost estimator (free tier — basic).
 *
 * Given an EV's battery size + range and a driver's annual mileage and
 * local electricity price, returns:
 *   - kWh consumed per 100 km
 *   - annual energy cost
 *   - cost per km
 *
 * The formula is intentionally simple: assumes flat consumption and ignores
 * regen, climate, charging losses, etc. Pro tier replaces this with a more
 * accurate model that incorporates real-world consumption curves.
 *
 * @package ThemeREX\AutoDealer
 * @version 1.0.0
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Frontend;

/**
 * Stateless EV cost estimator.
 */
final class EvEstimate {

	/**
	 * @param float $battery_kwh    Battery capacity (kWh).
	 * @param int   $range_km       Manufacturer range (km).
	 * @param int   $annual_km      Driver's annual distance (km).
	 * @param float $price_per_kwh  Local electricity price (currency / kWh).
	 * @return array{kwh_per_100km:float,annual_cost:float,cost_per_km:float}
	 */
	public static function compute( float $battery_kwh, int $range_km, int $annual_km, float $price_per_kwh ): array {
		if ( $battery_kwh <= 0 || $range_km <= 0 || $annual_km < 0 || $price_per_kwh < 0 ) {
			return array(
				'kwh_per_100km' => 0.0,
				'annual_cost'   => 0.0,
				'cost_per_km'   => 0.0,
			);
		}

		$kwh_per_km    = $battery_kwh / $range_km;
		$kwh_per_100km = $kwh_per_km * 100;
		$annual_cost   = $kwh_per_km * $annual_km * $price_per_kwh;
		$cost_per_km   = $kwh_per_km * $price_per_kwh;

		return array(
			'kwh_per_100km' => round( $kwh_per_100km, 2 ),
			'annual_cost'   => round( $annual_cost, 2 ),
			'cost_per_km'   => round( $cost_per_km, 4 ),
		);
	}

	/**
	 * Convenience wrapper that pulls battery/range from the specs row.
	 *
	 * @param int   $post_id        Vehicle post ID.
	 * @param int   $annual_km
	 * @param float $price_per_kwh
	 * @return array{kwh_per_100km:float,annual_cost:float,cost_per_km:float}|null
	 *         null when the listing has no EV battery/range data.
	 */
	public static function forVehicle( int $post_id, int $annual_km, float $price_per_kwh ): ?array {
		$battery = (float) get_post_meta( $post_id, '_trx_ad_ev_battery_kwh', true );
		$range   = (int) get_post_meta( $post_id, '_trx_ad_ev_range_km', true );

		if ( $battery <= 0 || $range <= 0 ) {
			return null;
		}

		return self::compute( $battery, $range, $annual_km, $price_per_kwh );
	}
}
