<?php

namespace App\Services;

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

class GenerateMonthlyBill
{
    public function generateAutoBill()
    {
        $currentMonth = Carbon::now()->month;
        $currentYear = Carbon::now()->year;

        DB::beginTransaction();
        try {
            $previousPayments = Payment::with('detailPayments')
                ->whereHas('detailPayments', function ($query) {
                    $query->where('payment_month', Carbon::now()->subMonth()->month)
                        ->where('payment_year', Carbon::now()->subMonth()->year);
                })->get();

            foreach ($previousPayments as $prevPay) {
                $existingBill = DetailPayment::where('payment_id', $prevPay->id)
                    ->where('payment_month', $currentMonth)
                    ->where('payment_year', $currentYear)->exists();
            }

            if (!$existingBill) {
                $previousDetail = $prevPay->detailPayments->last();
                DetailPayment::create([
                    'payment_id' => $prevPay->id,
                    'payment_type_id' => $previousDetail->payment_type_id,
                    'amount' => $previousDetail->amount,
                    'status' => 'unpaid',
                    'payment_month' => $currentMonth,
                    'payment_year' => $currentYear,
                    'penalty' => null,
                ]);
            }

            DB::commit();
            return ['message' => 'berhasil menambah data'];
        } catch (\Exception $e) {
            DB::rollBack();
            return ['error' => 'gagal menambah data' . $e->getMessage()];
        }
    }
}
