<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Car;
use App\Models\Depreciation;
use Carbon\Carbon;

class CalculateFleetDepreciation extends Command
{
    protected $signature = 'fleet:calculate-depreciation {--month= : Month to calculate for (YYYY-MM)}';
    protected $description = 'Calculates monthly depreciation for all vehicles in the fleet';

    public function handle()
    {
        $dateStr = $this->option('month') ? Carbon::parse($this->option('month'))->endOfMonth() : Carbon::now()->endOfMonth();
        $targetDate = Carbon::parse($dateStr);
        
        $this->info("Calculating depreciation for: " . $targetDate->format('Y-m'));

        $cars = Car::whereNotNull('purchase_price')
            ->whereNotNull('purchase_date')
            ->where('purchase_date', '<=', $targetDate)
            ->get();

        $count = 0;

        foreach ($cars as $car) {
            // Check if already calculated for this month
            $exists = Depreciation::where('car_id', $car->id)
                ->whereYear('depreciation_date', $targetDate->year)
                ->whereMonth('depreciation_date', $targetDate->month)
                ->exists();

            if ($exists) {
                $this->line("Car #{$car->id} ({$car->plate_number}): Already calculated.");
                continue;
            }

            // Calculate mileage this month if units_of_production
            $mileageThisMonth = 0;
            if ($car->depreciation_method === 'units_of_production') {
                // Fetch mileage from rentals or records in this month
                $mileageThisMonth = $car->rentals()
                    ->whereBetween('start_date', [$targetDate->copy()->startOfMonth(), $targetDate])
                    ->sum('distance_driven') ?: 500; // Default or actual
            }

            $amount = $car->calculateMonthlyDepreciation($mileageThisMonth);

            if ($amount <= 0) continue;

            // Ensure we don't go below salvage value
            if (($car->current_book_value - $amount) < $car->salvage_value) {
                $amount = $car->current_book_value - $car->salvage_value;
            }

            if ($amount <= 0) continue;

            Depreciation::create([
                'car_id' => $car->id,
                'depreciation_date' => $targetDate,
                'amount' => $amount,
                'book_value' => $car->current_book_value - $amount,
                'accumulated_depreciation' => $car->accumulated_depreciation + $amount,
                'mileage_at_period' => $car->mileage
            ]);

            $count++;
        }

        $this->info("Successfully processed {$count} vehicles.");
    }
}
