<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LoanProduct;
use App\Models\LoanCategory;
use App\Models\LoanTenure;
use Illuminate\Http\Request;

class LoanProductController extends Controller
{
    public function index()
    {
        $products = LoanProduct::with('category')->get();


        // dd($products);
        $tenures = LoanTenure::all();
        return view('admin.loan-products.index', compact('products', 'tenures'));
    }

    public function create()
    {
        return view('admin.loan-products.create', [
            'categories' => LoanCategory::all(),
            'tenures' => LoanTenure::all()
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'loan_category_id' => 'required|exists:loan_categories,id',
            'amount' => 'required|integer',
            'interest_percent' => 'required|numeric',
            'processing_fee_percent' => 'required|numeric',
            'processing_fee_per_day' => 'required|numeric',
            'processing_offer_percent' => 'nullable|numeric',
            'protection_fee_percent' => 'nullable|numeric',
            'tenure_ids' => 'required|array',
            'tenure_ids.*' => 'exists:loan_tenures,id'
        ]);

        LoanProduct::create($request->all());

        return redirect()->route('admin.loan-products.index');
    }

    public function edit(LoanProduct $loanProduct)
    {
        return view('admin.loan-products.edit', [
            'loanProduct' => $loanProduct,
            'categories' => LoanCategory::all(),
            'tenures' => LoanTenure::all()
        ]);
    }

    public function update(Request $request, LoanProduct $loanProduct)
    {
        $request->validate([
            'loan_category_id' => 'required|exists:loan_categories,id',
            'amount' => 'required|integer',
            'interest_percent' => 'required|numeric',
            'processing_fee_percent' => 'required|numeric',
            'processing_fee_per_day' => 'required|numeric',
            'processing_offer_percent' => 'nullable|numeric',
            'protection_fee_percent' => 'nullable|numeric',
            'tenure_ids' => 'required|array',
            'tenure_ids.*' => 'exists:loan_tenures,id'
        ]);

        $loanProduct->update($request->all());

        return redirect()->route('admin.loan-products.index');
    }

    public function destroy(LoanProduct $loanProduct)
    {
        $loanProduct->delete();
        return back();
    }
}
