<?php

namespace App\Http\Controllers\Admin\Expance;

use App\Http\Controllers\Controller;
use App\Models\Expance;
use App\Models\ExpanceCategory;
use App\Service\Expance\ExpanceCategoryService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class ExpanceCategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {

        return Inertia::render('Expance/ExpanceCategory');
    }

    public function veiw()
    {
        $category = ExpanceCategory::latest()->get();

        return response()->json(['category' => $category]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        // No separate edit view; handled via Inertia modal on index page
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        ExpanceCategoryService::store(request()->all());
        $category = ExpanceCategory::latest()->get();

        return response()->json(['success' => 'Category created successfully', 'category' => $category]);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        ExpanceCategoryService::update(request()->all(), $id);
        $category = ExpanceCategory::latest()->get();

        return response()->json(['success' => 'Category update successfully', 'category' => $category]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $expense = Expance::where('category_id', $id)->first();
        if ($expense) {
            return response()->json(['error' => 'Category have a Data'], 422);
        } else {
            ExpanceCategory::where('id', $id)->delete();
        }

        $category = ExpanceCategory::latest()->get();

        return response()->json(['success' => 'Category delete successfully', 'category' => $category]);
    }
}
