<?php

namespace App\Http\Controllers\Api;

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

class PenempatanController extends Controller
{
    protected $penempatanService;

    public function __construct(PenempatanBankService $penempatanService)
    {
        $this->penempatanService = $penempatanService;
    }

    public function index()
    {
        return $this->penempatanService->getAllPenempatanBank();
    }

    public function create() {}

    public function store(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'rekening' => 'required|string|unique:data_penempatan_master,rekening',
                'nama' => 'required',
                'bank_id' => 'required',
                'tgl_penempatan' => 'required',
                'suku_bunga' => 'nullable',
                'jkw' => 'nullable',
                'saldo' => 'nullable',
                'akun_penempatan' => 'required'
            ]);

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

    public function show(string $id)
    {
        $penempatan = $this->penempatanService->findById($id);

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

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

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

            $kas = $this->penempatanService->updatePenempatanBank($id, $validator->validate());

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

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

    public function destroy(string $id)
    {
        return $this->penempatanService->deletePenempatanBank($id);
    }
}
