<?php

namespace App\Services;

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

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

        DB::beginTransaction();
        try {
            $santriPayments = Payment::with('detailPayments')->get();

            foreach ($santriPayments as $prevPay) {
                $existingPayment = Payment::where('santri_id', $prevPay->santri_id)
                    ->whereMonth('created_at', $currentMonth)
                    ->whereYear('created_at', $currentYear)
                    ->first();

                if (!$existingPayment) {
                    $newPayment = Payment::create([
                        'payment_status' => 'pending',
                        'amount_payment' => 0,
                        'santri_id' => $prevPay->santri_id,
                        'wallet_id' => $prevPay->wallet_id,
                        'bank' => null,
                        'no_va' => null,
                        'expired_at' => null,
                        'payment_method' => null,
                    ]);
                } else {
                    $newPayment = $existingPayment;
                }

                $previousPayment = Payment::where('santri_id', $prevPay->santri_id)
                    ->whereMonth('created_at', $previousMonth)
                    ->whereYear('created_at', $previousYear)
                    ->first();

                if (!$previousPayment) {
                    continue;
                }

                $previousDetails = $previousPayment->detailPayments;

                foreach ($previousDetails as $previousDetail) {
                    $existingBill = DetailPayment::where('payment_id', $newPayment->id)
                        ->where('type_id', $previousDetail->type_id)
                        ->where('payment_month', $currentMonth)
                        ->where('payment_year', $currentYear)
                        ->exists();

                    if (!$existingBill) {
                        $paymentType = PaymentType::find($previousDetail->type_id);
                        $amount = $paymentType ? $paymentType->amount : 0;

                        DetailPayment::create([
                            'payment_id' => $newPayment->id,
                            'type_id' => $previousDetail->type_id,
                            'amount' => $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()];
        }
    }
}
