<?php

namespace App\Services;

use App\Models\DetailPayment;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class cekDenda
{
    public function applyPenalty()
    {
        $previousMonth = Carbon::now()->subMonth()->month;
        $previousYear = Carbon::now()->subMonth()->year;
        $currentDay = Carbon::now()->day;
        $penaltyAmount = 20000;

        if ($currentDay >= 10) {
            DB::beginTransaction();
            try {
                $unpaidPayments = DetailPayment::where('status', 'unpaid')
                    ->where('payment_month', $previousMonth)
                    ->where('payment_year', $previousYear)
                    ->get();

                foreach ($unpaidPayments as $payment) {
                    if (is_null($payment->penalty)) {
                        $payment->update([
                            'penalty' => $penaltyAmount
                        ]);
                    }
                }

                DB::commit();
                return ['message' => 'Penalty applied successfully'];
            } catch (\Exception $e) {
                DB::rollBack();
                return ['error' => $e->getMessage()];
            }
        }

        return ['message' => 'Not yet time for penalty application'];
    }
}
