<?php

namespace App\Services;

use App\Models\Vehicle;
use App\Models\EmissionPoolRate;
use Carbon\Carbon;

class CarEmissionService
{






    public function calculateRate($carId)
    {
        // Fetch the car with registration date and CO2 emission
        $car = Vehicle::find($carId);
        $carCo2Emission = $car->co2_emission;
        $registrationDate = new Carbon($car->registration_date);



        // $capital_allownces =  1st april 2021 se pehle car registration, upto (<=) 110g/km co2, = 6% x carValue
        // $capital_allownces =  1st april 2021 k bad car registration, upto (<=) 50g/km co2, = 18% x carValue
        // vehicle usage = from 6 april - purchase/sell date = forexample 11 months
        // $capital_allownces_permonth = $capital_allownces/12 x $vehicleusage
        // next year = car value - capital_allownces

        // Date of first registration for finding co2
        // Co2Emission aur Date of first registration comes from API
        // 6% ya 18%

        // user input
        // Vehicle Value
        // Vehicle Business Date





        // Fetch the correct emission limits based on registration date
        $mainPoolRate = EmissionPoolRate::where('type', 'main')
            ->where('valid_from', '<=', $registrationDate)
            ->orderBy('valid_from', 'desc')
            ->first();

        $specialPoolRate = EmissionPoolRate::where('type', 'special')
            ->where('valid_from', '<=', $registrationDate)
            ->orderBy('valid_from', 'desc')
            ->first();

        // Check which rate applies based on the CO2 emission level
        if ($carCo2Emission <= $mainPoolRate->emission_limit) {
            $rate = 'Main Pool Rate';
        } elseif ($carCo2Emission > $mainPoolRate->emission_limit) {
            $rate = 'Special Pool Rate';
        }

        return $rate;
    }
}
