<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CalculateInstallmentSurcharges extends Command
{
    protected $signature = 'installments:calculate-surcharges';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Calculate and apply daily late payment surcharges to overdue installments.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $surchargePercent = \App\Models\Setting::where('key', 'late_payment_surcharge_percent')->value('value') ?? 5;
        
        $installments = \App\Models\Installment::whereIn('status', ['Pending', 'Partial Paid'])
            ->whereDate('due_date', '<', now()->toDateString())
            ->get();
            
        $count = 0;
        foreach ($installments as $installment) {
            $remaining = $installment->amount_due - $installment->amount_paid;
            if ($remaining > 0) {
                // Apply a one-time penalty for becoming overdue, or a daily fractional penalty.
                // Assuming it's a one-time penalty applied on the day it becomes overdue.
                if ($installment->status !== 'Overdue') {
                    $penalty = $remaining * ($surchargePercent / 100);
                    $installment->update([
                        'surcharge_amount' => $installment->surcharge_amount + $penalty,
                        'status' => 'Overdue'
                    ]);
                    $count++;
                    
                    // Update linked invoice if exists
                    \App\Models\Invoice::where('installment_id', $installment->id)
                        ->update(['status' => 'Overdue']);
                }
            }
        }
        
        $this->info("Surcharges applied to $count installments.");
    }
}
