<?php

namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;

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

class LoanSettingController extends Controller
{
    public function index()
    {
        $settings = LoanSetting::orderByDesc('id')->paginate(12);
        return view('backend.loan_settings.index', compact('settings'));
    }

    public function create()
    {
        return view('backend.loan_settings.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'interest_rate'            => ['required','numeric','min:0'],
            'eligibility_min_turnover' => ['required','numeric','min:0'],
            'loan_options'             => ['nullable','string'],
            'loan_periods'             => ['nullable','string'],
        ]);

        $data['loan_options'] = $this->toNumberArray($data['loan_options'] ?? '');
        $data['loan_periods'] = $this->toNumberArray($data['loan_periods'] ?? '', integers:true);

        LoanSetting::create($data);
        return redirect(url('/admin/loan-settings'))->with('success', 'Loan setting created.');
    }

    public function show($id)
    {
        $row = LoanSetting::findOrFail($id);
        return view('backend.loan_settings.show', compact('row'));
    }

    public function edit($id)
    {
        $row = LoanSetting::findOrFail($id);
        return view('backend.loan_settings.edit', compact('row'));
    }

    public function update(Request $request, $id)
    {
        $row  = LoanSetting::findOrFail($id);
        $data = $request->validate([
            'interest_rate'            => ['required','numeric','min:0'],
            'eligibility_min_turnover' => ['required','numeric','min:0'],
            'loan_options'             => ['nullable','string'],
            'loan_periods'             => ['nullable','string'],
        ]);

        $data['loan_options'] = $this->toNumberArray($data['loan_options'] ?? '');
        $data['loan_periods'] = $this->toNumberArray($data['loan_periods'] ?? '', integers:true);

        $row->update($data);
        return redirect(url('/admin/loan-settings'))->with('success', 'Loan setting updated.');
    }

    public function destroy($id)
    {
        LoanSetting::findOrFail($id)->delete();
        return redirect(url('/admin/loan-settings'))->with('success', 'Loan setting deleted.');
    }

    /**
     * "1, 2, 3.5" -> [1,2,3.5]
     */
    private function toNumberArray(string $csv, bool $integers = false): array
    {
        $parts = array_filter(array_map(fn($v)=>trim($v), explode(',', $csv)));
        $nums  = array_map(function($v) use($integers){
            return $integers ? (int)$v : (float)$v;
        }, $parts);
        return array_values(array_unique(array_filter($nums, fn($n)=>$n >= 0)));
    }
}
