<?php

namespace App\Http\Controllers;

use App\Http\Requests\TreasuryCategoryStoreRequest;
use App\Http\Requests\TreasuryCategoryUpdateRequest;
use App\Http\Resources\TreasuryCategoryResource;
use App\Models\TreasuryCategory;

class TreasuryCategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Get all categories (entries and exits)
        return response()->json(TreasuryCategoryResource::collection(TreasuryCategory::all()));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(TreasuryCategoryStoreRequest $request)
    {
        $fields = $request->validated();

        $category = TreasuryCategory::create($fields);

        return response()->json([
            "category" => new TreasuryCategoryResource($category)
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        // Find borrower by ID
        $category = TreasuryCategory::find($id);

        if ($category) {
            return new TreasuryCategoryResource($category);
        } else {
            return response()->json(['message' => 'Category not found'], 404);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(TreasuryCategoryUpdateRequest $request, string $id)
    {
        $category = TreasuryCategory::find($id);

        if (!$category) {
            return response()->json(['message' => 'Category not found'], 404);
        }

        $fields = $request->validated();

        $category->update($fields);

        return response()->json([
            'category' => new TreasuryCategoryResource($category)
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $category = TreasuryCategory::find($id);

        if (!$category) {
            return response()->json(['message' => 'Category not found'], 404);
        }

        $category->delete();

        return response()->json(['message' => 'Category deleted successfully'], 200);
    }
}
