<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\KasService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class KasController extends Controller
{
    protected $kasService;

    public function __construct(KasService $kasService)
    {
        $this->kasService = $kasService;
    }

    public function index()
    {
        return $this->kasService->getAllKas();
    }

    public function create()
    {
        // Logic to show form for creating a new kas entry
    }

    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'nama' => 'required|string|unique:data_kas_master,nama',
                'akun_kas' => 'required',
                'is_default' => 'nullable',
            ]);

            $role = $this->kasService->createKas($validator->validated());
            return response()->json($role, 201);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 400);
        }
    }

    public function show($id)
    {
        $kas = $this->kasService->findById($id);

        if (!$kas) {
            return response()->json(['message' => 'Kas tidak ditemukan'], 404);
        }

        return response()->json($kas);
    }

    public function edit($id)
    {
        // Logic to show form for editing a kas entry
    }

    public function update(Request $request, $id)
    {
        try {
            $validator = Validator::make($request->all(), [
                'id' => 'required',
                'nama' => 'required|string',
                'akun_kas' => 'required|string',
                'is_default' => 'nullable',
            ]);

            $kas = $this->kasService->updateKas($id, $validator->validate());

            if (!$kas) {
                return response()->json(['message' => 'Kas tidak ditemukan'], 404);
            }

            return response()->json($kas);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 400);
        }
    }

    public function destroy($id)
    {
        return $this->kasService->deleteKas($id);
    }
}
