<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Loan;
use App\Models\LoanInstallment;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class LoanInstallmentController extends Controller
{
    /** নির্দিষ্ট loan এর সব কিস্তি লিস্ট + status + action */
    public function index(Loan $loan)
    {
        $installments = $loan->installments()
            ->orderBy('due_date')
            ->get();

        return view('backend.loans.installments_index', compact('loan', 'installments'));
    }

    /** এক কিস্তি edit form */
    public function edit(LoanInstallment $installment)
    {
        $loan = $installment->loan;

        return view('backend.loans.installments_edit', [
            'loan'        => $loan,
            'installment' => $installment,
        ]);
    }

    /** কিস্তি update (paid / late / upcoming) */
    public function update(Request $request, LoanInstallment $installment)
    {
        $loan = $installment->loan;

        $validated = $request->validate([
            'status'         => ['required', 'in:upcoming,paid,late'],
            'paid_amount'    => ['nullable', 'integer', 'min:1'],
            'payment_method' => ['nullable', 'string', 'max:100'],
            'payment_trx_id' => ['nullable', 'string', 'max:191'],
        ]);

        // যদি paid select করে, তাহলে paid_amount অবশ্যই লাগবে
        if ($validated['status'] === 'paid') {
            if (empty($validated['paid_amount'])) {
                return back()->withErrors([
                    'paid_amount' => 'Paid amount অবশ্যই দিতে হবে যখন status paid করবেন।',
                ])->withInput();
            }
        }

        // আপডেট লজিক
        $updateData = [
            'status'         => $validated['status'],
            'payment_method' => $validated['payment_method'] ?? null,
            'payment_trx_id' => $validated['payment_trx_id'] ?? null,
        ];

        if ($validated['status'] === 'paid') {
            $updateData['paid_amount'] = $validated['paid_amount'];
            $updateData['paid_at']     = $installment->paid_at ?? Carbon::now();
        } else {
            // upcoming / late করলে payment resetও করতে পারো
            $updateData['paid_amount']    = null;
            $updateData['payment_method'] = null;
            $updateData['payment_trx_id'] = null;
            $updateData['paid_at']        = null;
        }

        $installment->update($updateData);

        // loan status update (সব paid হলে completed)
        $this->updateLoanStatus($loan);

        return redirect()
            ->route('admin.loans.installments', $loan)
            ->with('success', 'Installment updated successfully.');
    }

    /** loan এর status auto update */
    protected function updateLoanStatus(Loan $loan): void
    {
        $total  = $loan->installments()->count();
        $paid   = $loan->installments()->where('status', 'paid')->count();

        if ($total > 0 && $paid === $total) {
            // সব কিস্তি পরিশোধ — loan completed
            $loan->status       = 'completed';
            $loan->completed_at = $loan->completed_at ?? now();
            $loan->save();
        } else {
            // অন্তত ১টা paid হলে নিশ্চিতভাবে running করতে চাইলে
            if ($paid > 0 && $loan->status !== 'completed') {
                $loan->status = 'running';
                $loan->save();
            }
        }
    }
}
