<?php

namespace App\Http\Controllers;

use App\Models\LoanType;
use Illuminate\Http\Request;

class LoanTypeController extends Controller
{
    /**
     * List all loan types (admin)
     */
    public function index()
    {
        $types = LoanType::orderBy('created_at', 'desc')->paginate(15);
        return view('admin.loan_types.index', compact('types'));
    }

    /**
     * Show create form
     */
    public function create()
    {
        return view('admin.loan_types.create');
    }

    /**
     * Store new loan type
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'                  => 'required|string|max:191|unique:loan_types,name',
            'description'           => 'nullable|string',
            'interest_rate'         => 'nullable|numeric|min:0',
            'duration_months'       => 'nullable|integer|min:1',
            'min_amount'            => 'nullable|numeric|min:0',
            'max_amount'            => 'nullable|numeric|min:0',
            'rules'                 => 'nullable|string',     // must be JSON
            'allow_member_application' => 'nullable',
            'allow_admin_application'  => 'nullable',
            'is_group_loan'             => 'nullable',
        ]);

        // Validate JSON rules safely
        $rulesArray = null;
        if ($request->rules) {
            $decoded = json_decode($request->rules, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                return back()
                    ->withInput()
                    ->withErrors(['rules' => 'Rules must be valid JSON.']);
            }

            $rulesArray = $decoded;
        }

        $data = [
            'name'                      => $request->name,
            'description'               => $request->description,
            'interest_rate'             => $request->interest_rate,
            'duration_months'           => $request->duration_months,
            'min_amount'                => $request->min_amount,
            'max_amount'                => $request->max_amount,
            'rules'                     => $rulesArray,
            'allow_member_application'  => $request->has('allow_member_application'),
            'allow_admin_application'   => $request->has('allow_admin_application'),
            'is_group_loan'             => $request->has('is_group_loan'),
        ];

        LoanType::create($data);

        return redirect()
            ->route('admin.loan_types.index')
            ->with('success', 'Loan type created successfully.');
    }

    /**
     * Show edit form
     */
    public function edit(LoanType $loanType)
    {
        return view('admin.loan_types.edit', compact('loanType'));
    }

    /**
     * Update loan type
     */
    public function update(Request $request, LoanType $loanType)
    {
        $request->validate([
            'name'                  => 'required|string|max:191|unique:loan_types,name,' . $loanType->id,
            'description'           => 'nullable|string',
            'interest_rate'         => 'nullable|numeric|min:0',
            'duration_months'       => 'nullable|integer|min:1',
            'min_amount'            => 'nullable|numeric|min:0',
            'max_amount'            => 'nullable|numeric|min:0',
            'rules'                 => 'nullable|string',
            'allow_member_application' => 'nullable',
            'allow_admin_application'  => 'nullable',
            'is_group_loan'             => 'nullable',
        ]);

        // Validate JSON rules
        $rulesArray = null;
        if ($request->rules) {
            $decoded = json_decode($request->rules, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                return back()
                    ->withInput()
                    ->withErrors(['rules' => 'Rules must be valid JSON.']);
            }

            $rulesArray = $decoded;
        }

        $data = [
            'description'               => $request->description,
            'name'                      => $request->name,
            'interest_rate'             => $request->interest_rate,
            'duration_months'           => $request->duration_months,
            'min_amount'                => $request->min_amount,
            'max_amount'                => $request->max_amount,
            'rules'                     => $rulesArray,
            'allow_member_application'  => $request->has('allow_member_application'),
            'allow_admin_application'   => $request->has('allow_admin_application'),
            'is_group_loan'             => $request->has('is_group_loan'),
        ];

        $loanType->update($data);

        return redirect()
            ->route('admin.loan_types.index')
            ->with('success', 'Loan type updated successfully.');
    }

    /**
     * Delete loan typestore
     */
    public function destroy(LoanType $loanType)
    {
        $loanType->delete();

        return redirect()
            ->route('admin.loan_types.index')
            ->with('success', 'Loan type deleted successfully.');
    }
}
