<?php

namespace App\Http\Controllers;

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

class LoanTypeController extends Controller
{

    /**
     * List with Search & Pagination
     */
    public function index(Request $request): JsonResponse
    {
        try {

            $perPage = $request->get('per_page', 20);
            $search  = $request->get('search');

            $query = LoanType::query();

            if (!empty($search)) {
                $query->where(function ($q) use ($search) {
                    $q->where('LT_Code', 'like', "%$search%")
                        ->orWhere('LT_Name', 'like', "%$search%")
                        ->orWhere('Loan_Mode', 'like', "%$search%");
                });
            }

            $data = $query->orderBy('LT_Id', 'desc')
                ->paginate($perPage);

            return response()->json([
                'success' => true,
                'message' => 'Loan type list fetched successfully',
                'data' => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store
     */
    public function store(Request $request): JsonResponse
    {
        try {

            $validated = $request->validate([
                'LT_Code'        => 'nullable|string|max:20',
                'LT_Name'        => 'required|string|max:50',
                'Max_Amount'     => 'nullable|numeric',
                'Loan_Mode'      => 'nullable|in:IN,OUT',
                'Interest_Rate'  => 'nullable|numeric',
                'Tenure_Years'   => 'nullable|integer',
                'Is_Active'      => 'nullable|boolean'
            ]);

            $data = LoanType::create($validated);

            return response()->json([
                'success' => true,
                'message' => 'Loan type created successfully',
                'data' => $data
            ]);
        } catch (\Illuminate\Validation\ValidationException $ve) {

            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $ve->errors()
            ], 422);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /**
     * Show Single Record
     */
    public function show($id): JsonResponse
    {
        try {

            $data = LoanType::find($id);

            if (!$data) {
                return response()->json([
                    'success' => false,
                    'message' => 'Record not found'
                ], 404);
            }

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update
     */
    public function update(Request $request, $id): JsonResponse
    {
        try {

            $data = LoanType::find($id);

            if (!$data) {
                return response()->json([
                    'success' => false,
                    'message' => 'Record not found'
                ], 404);
            }

            $validated = $request->validate([
                'LT_Code'        => 'sometimes|nullable|string|max:20',
                'LT_Name'        => 'sometimes|required|string|max:50',
                'Max_Amount'     => 'sometimes|nullable|numeric',
                'Loan_Mode'      => 'sometimes|nullable|in:IN,OUT',
                'Interest_Rate'  => 'sometimes|nullable|numeric',
                'Tenure_Years'   => 'sometimes|nullable|integer',
                'Is_Active'      => 'sometimes|boolean'
            ]);

            $data->update($validated);

            return response()->json([
                'success' => true,
                'message' => 'Loan type updated successfully',
                'data' => $data
            ]);
        } catch (\Illuminate\Validation\ValidationException $ve) {

            return response()->json([
                'success' => false,
                'message' => 'Validation error',
                'errors' => $ve->errors()
            ], 422);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /**
     * Delete
     */
    public function destroy($id): JsonResponse
    {
        try {

            $data = LoanType::find($id);

            if (!$data) {
                return response()->json([
                    'success' => false,
                    'message' => 'Record not found'
                ], 404);
            }

            $data->delete();

            return response()->json([
                'success' => true,
                'message' => 'Deleted successfully'
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get All
     */
    public function all(): JsonResponse
    {
        try {

            $data = LoanType::orderBy('LT_Id', 'desc')->get();

            return response()->json([
                'success' => true,
                'message' => 'All loan types fetched successfully',
                'data' => $data
            ]);
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Something went wrong',
                'error' => env('Development_Mode') == 'Prod' 
        ? 'Something went wrong. Please try again later.' 
        : $e->getMessage()
            ], 500);
        }
    }
}
