<?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;
use Illuminate\Support\Facades\Validator;

class PaymentController extends Controller
{
    public function indexManualPayment(cekDenda $cekDenda, GenerateMonthlyBill $generateMonthlyBill)
    {

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

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

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

        return Inertia::render('list-admin/payment/ManualPayment', [
            'santri' => $santri,
            'penalty' => 0,
            '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, $userId)
    {
        $validator = Validator::make($request->all(), [
            'items' => 'required|array',
            'items.*.type_id' => 'required|exists:payment_types,id',
            'items.*.range' => 'required|integer|min:1',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        DB::beginTransaction();

        try {
            $paymentTypes = PaymentType::pluck('nominal', 'id');
            $user = User::findOrFail($userId);

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

            if ($existingPayment) {
                $totalAmountExisting = DetailPayment::where('payment_id', $existingPayment->id)->sum('amount');
                $hasUnpaid = DetailPayment::where('payment_id', $existingPayment->id)
                    ->where('status', 'unpaid')
                    ->exists();

                $existingPayment->update([
                    'amount_payment' => $totalAmountExisting,
                    'payment_status' => $hasUnpaid ? 'pending' : 'success',
                ]);

                DB::commit();

                return redirect()->back()->with('success', 'Pembayaran yang pending sudah diupdate.');
            }

            $newPayment = Payment::create([
                'payment_status' => 'success',
                'amount_payment' => 0,
                'transaction_type' => 'payment',
                'user_id' => $userId,
                'order_id' => 'TRX' . uniqid(),
            ]);

            $totalAmount = 0;

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

                $lastDetail = DetailPayment::whereHas('payments', function ($q) use ($userId) {
                    $q->where('user_id', $userId);
                })
                    ->where('type_id', $typeId)
                    ->orderBy('payment_year', 'desc')
                    ->orderBy('payment_month', 'desc')
                    ->first();

                if ($lastDetail) {
                    $bulan = $lastDetail->payment_month;
                    $tahun = $lastDetail->payment_year;
                } else {
                    $bulan = now()->month;
                    $tahun = now()->year;
                }

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

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

                    $totalAmount += $nominal;
                }
            }

            $newPayment->update(['amount_payment' => $totalAmount]);

            DB::commit();

            return redirect()->back()->with('success', 'Pembayaran baru berhasil dibuat');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'Gagal membuat pembayaran: ' . $e->getMessage());
        }
    }


    public function transaction()
    {
        $transaction = User::with('payments', 'payments.detailPayments', 'wallet.walletTransactions', 'payments.detailPayments.paymentType')
            ->where('level', 10)
            ->paginate(2);

        // dd($transaction);

        return Inertia::render('list-admin/payment/Transaction', compact('transaction'));
    }
}
