<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\PaymentType;
use App\Models\DetailPayment;
use Inertia\Inertia;
use App\Services\cekDenda;
use App\Services\GenerateMonthlyBill;
use Illuminate\Support\Facades\DB;
use Exception;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    public function indexManualPayment(cekDenda $cekDenda, GenerateMonthlyBill $generateMonthlyBill)
    {
        $penalty = $cekDenda->applyPenalty();
        $bill = $generateMonthlyBill->generateAutoBill();

        $paymentTypes = PaymentType::get(['id', 'payment_type', 'nominal']);

        $paymentPenalties = DetailPayment::with('paymentType')
            ->get()
            ->pluck('penalty', 'type_id');

        $santri = User::with([
            'payments.detailPayments.paymentType',
        ])->paginate(10);

        return Inertia::render('list-admin/payment/ManualPayment', [
            'santri' => $santri->items(),
            'penalty' => $penalty,
            'bill' => $bill,
            'fields' => [
                'nis' => ['type' => 'text', 'readonly' => true],
                'nama' => ['type' => 'text', 'readonly' => true],
                'status_santri' => ['type' => 'text', 'readonly' => true],
            ],
            'options' => [
                'payment_type' => $paymentTypes->pluck('payment_type', 'id'),
                'payment_nominal' => $paymentTypes->pluck('nominal', 'id'),
                'payment_penalty' => $paymentPenalties
            ]
        ]);
    }

    public function manualPayment(Request $request, $paymentId)
    {
        // $request->validate([
        //     'items' => 'required|array',
        //     'items.*.type_id' => 'required|exists:payment_types,id',
        //     'items.*.range' => 'required|integer|min:1'
        // ]);


        $items = $request->input('items');
        $userId = $request->id;
        $items = json_decode($request->input('items'), true);

        try {
            DB::beginTransaction();


            // Ambil semua payment type sekaligus
            $paymentTypes = PaymentType::pluck('nominal', 'id');

            $existingPayment = Payment::where('user_id', $userId)
                ->where('payment_status', 'pending')
                ->first();

            if ($existingPayment) {
                $totalAmount = 0;

                foreach ($items as $item) {
                    $typeId = $item['type_id'];
                    $range = $item['range'];
                    $nominal = $paymentTypes[$typeId] ?? 0;

                    // Ambil unpaid details
                    $unpaidDetails = DetailPayment::where('payment_id', $existingPayment->id)
                        ->where('status', 'unpaid')
                        ->where('type_id', $typeId)
                        ->orderBy('payment_year')
                        ->orderBy('payment_month')
                        ->get();

                    // Proses unpaid details
                    $toPay = $unpaidDetails->take($range);
                    $toPay->each(function ($detail) use (&$totalAmount, $nominal) {
                        $detail->update([
                            'status' => 'paid',
                            'amount' => $nominal,
                            'penalty' => $detail->penalty ?? 0,
                        ]);
                        $totalAmount += $nominal + $detail->penalty;
                    });

                    // Hitung sisa bulan yang perlu dibuat
                    $sisa = $range - $toPay->count();
                    if ($sisa > 0) {
                        // Ambil bulan/tahun terakhir
                        $lastDetail = DetailPayment::where('payment_id', $existingPayment->id)
                            ->orderBy('payment_year', 'desc')
                            ->orderBy('payment_month', 'desc')
                            ->first();

                        $bulan = $lastDetail->payment_month ?? now()->month;
                        $tahun = $lastDetail->payment_year ?? now()->year;

                        for ($i = 0; $i < $sisa; $i++) {
                            $bulan++;
                            if ($bulan > 12) {
                                $bulan = 1;
                                $tahun++;
                            }

                            DetailPayment::create([
                                'payment_id' => $existingPayment->id,
                                'payment_month' => $bulan,
                                'payment_year' => $tahun,
                                'amount' => $nominal,
                                'penalty' => 0,
                                'status' => 'paid',
                                'type_id' => $typeId,
                            ]);

                            $totalAmount += $nominal;
                        }
                    }
                }

                // Update payment status
                $existingPayment->update([
                    'amount_payment' => DetailPayment::where('payment_id', $existingPayment->id)->sum('amount'),
                    'payment_status' => DetailPayment::where('payment_id', $existingPayment->id)
                        ->where('status', 'unpaid')
                        ->exists() ? 'pending' : 'success'
                ]);

                DB::commit();
                return response()->json(['message' => 'Pembayaran berhasil diupdate']);
            }

            // Jika tidak ada existing payment, buat baru
            $newPayment = Payment::create([
                'payment_status' => 'success',
                'amount_payment' => 0,
                'user_id' => $userId,
            ]);

            $bulan = now()->month;
            $tahun = now()->year;
            $totalAmount = 0;

            foreach ($items as $item) {
                $typeId = $item['type_id'];
                $range = $item['range'];
                $nominal = $paymentTypes[$typeId] ?? 0;

                for ($i = 0; $i < $range; $i++) {
                    DetailPayment::create([
                        'payment_id' => $newPayment->id,
                        'payment_month' => $bulan,
                        'payment_year' => $tahun,
                        'amount' => $nominal,
                        'penalty' => 0,
                        'status' => 'paid',
                        'type_id' => $typeId,
                    ]);

                    $totalAmount += $nominal;

                    $bulan++;
                    if ($bulan > 12) {
                        $bulan = 1;
                        $tahun++;
                    }
                }
            }

            $newPayment->update(['amount_payment' => $totalAmount]);
            DB::commit();
            dd('berhasil lur');

            // return redirect()->back()->with(['success' => 'Pembayaran baru berhasil dibuat']);
        } catch (Exception $e) {
            DB::rollBack();
            dd('gagal' . $e->getMessage());
            return redirect()->back()->with(['error' => 'gagal' . $e->getMessage()]);
        }
    }
}
