<?php

namespace App\Http\Controllers\Admin;

use App\Enums\UserType;
use App\Http\Controllers\Controller;
use App\Models\Loan;
use App\Models\LoanTransaction;
use Illuminate\Http\Request;
use Inertia\Inertia;

class LoanController extends Controller
{
    public function index()
    {
        $loans = Loan::with(['employee', 'approver'])
            ->where('status', '!=', 'draft')
            ->latest()
            ->get();

        $employees = \App\Models\User::where('type', UserType::EMPLOYEE)
            ->where('status', 'active')
            ->get(['id', 'name']);

        return Inertia::render('Admin/Loan/Index', [
            'loans' => $loans,
            'employees' => $employees,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'employee_id' => 'required|exists:users,id',
            'loan_date' => 'required|date_format:Y-m',
            'total_amount' => 'required|numeric|min:1',
            'installment_amount' => 'required|numeric|min:1|lte:total_amount',
            'start_month' => 'required|date_format:Y-m',
            'remarks' => 'nullable|string|max:1000',
        ]);

        // Block if employee already has an outstanding (pending/approved) or partially-paid loan
        $hasActiveLoan = Loan::where('employee_id', $validated['employee_id'])
            ->where(function ($q) {
                $q->whereIn('status', ['pending', 'approved'])
                    ->orWhere('remaining_balance', '>', 0);
            })
            ->exists();

        if ($hasActiveLoan) {
            return back()->withErrors([
                'employee_id' => 'This employee already has an active or outstanding loan. A new loan can only be created after the existing one is fully cleared.',
            ])->withInput();
        }

        Loan::create([
            'employee_id' => $validated['employee_id'],
            'loan_date' => $validated['loan_date'],
            'total_amount' => $validated['total_amount'],
            'installment_amount' => $validated['installment_amount'],
            'start_month' => $validated['start_month'],
            'remaining_balance' => $validated['total_amount'],
            'status' => 'pending',
            'remarks' => $validated['remarks'] ?? null,
        ]);

        return back()->with('success', 'Loan created successfully.');
    }

    public function update(Request $request, Loan $loan)
    {
        if ($loan->status !== 'pending') {
            return back()->with('error', 'Only pending loans can be edited.');
        }

        $validated = $request->validate([
            'employee_id' => 'required|exists:users,id',
            'loan_date' => 'required|date_format:Y-m',
            'total_amount' => 'required|numeric|min:1',
            'installment_amount' => 'required|numeric|min:1|lte:total_amount',
            'start_month' => 'required|date_format:Y-m',
            'remarks' => 'nullable|string|max:1000',
        ]);

        $loan->update([
            'employee_id' => $validated['employee_id'],
            'loan_date' => $validated['loan_date'],
            'total_amount' => $validated['total_amount'],
            'installment_amount' => $validated['installment_amount'],
            'start_month' => $validated['start_month'],
            'remaining_balance' => $validated['total_amount'],
            'remarks' => $validated['remarks'] ?? null,
        ]);

        return back()->with('success', 'Loan updated successfully.');
    }

    public function show(Loan $loan)
    {
        $loan->load(['employee', 'approver', 'transactions.payroll', 'transactions.recorder:id,name']);

        return Inertia::render('Admin/Loan/Show', [
            'loan' => $loan,
        ]);
    }

    public function manualRepayment(Request $request, Loan $loan)
    {
        if (! in_array($loan->status, ['approved', 'closed'])) {
            return back()->with('error', 'Manual repayment is only available for approved loans.');
        }

        if ((float) $loan->remaining_balance <= 0) {
            return back()->with('error', 'This loan is already fully repaid.');
        }

        $validated = $request->validate([
            'amount' => ['required', 'numeric', 'min:0.01'],
            'note' => ['nullable', 'string', 'max:255'],
        ]);

        $amount = (float) $validated['amount'];
        $currentRemaining = (float) $loan->remaining_balance;

        if ($amount > $currentRemaining) {
            return back()->withErrors([
                'amount' => 'Repayment amount cannot exceed remaining balance.',
            ]);
        }

        $remainingAfter = max(0, $currentRemaining - $amount);

        LoanTransaction::create([
            'loan_id' => $loan->id,
            'payroll_id' => null,
            'source' => 'manual',
            'note' => $validated['note'] ?? null,
            'recorded_by' => $request->user()->id,
            'deducted_amount' => $amount,
            'remaining_after' => $remainingAfter,
        ]);

        $loan->update([
            'remaining_balance' => $remainingAfter,
            'status' => $remainingAfter <= 0 ? 'closed' : 'approved',
        ]);

        return back()->with('success', 'Manual repayment recorded successfully.');
    }
}
