<?php

namespace App\Services;

use App\Models\Bank;
use App\Models\Kas;
use App\Repositories\KasRepository;
use Illuminate\Database\Eloquent\Collection;
use Exception;

class KasService
{
    protected $kasRepository;

    public function __construct(KasRepository $kasRepository)
    {
        $this->kasRepository = $kasRepository;
    }

    public function getAllKas(): Collection
    {
        return $this->kasRepository->getAll();
    }

    public function findById(string $id): ?Kas
    {
        return $this->kasRepository->findById($id);
    }

    public function findByNama(string $nama): ?Kas
    {
        return $this->kasRepository->findByNama($nama);
    }

    public function createKas(array $data): Kas
    {
        $count = $this->kasRepository->count();
        $data['id'] = "KAS" . str_pad($count + 1, 5, "0", STR_PAD_LEFT);

        return $this->kasRepository->create($data);
    }

    public function updateKas(string $id, array $data): ?Kas
    {
        $role = $this->kasRepository->findById($id);
        if ($role->nama != $data['nama']) {
            $role_nama = $this->kasRepository->findByNama($data['nama']);
            if ($role_nama) {
                throw new \Exception("Duplikat nama");
            };
        }

        if (!$role) {
            throw new Exception("Kas tidak ditemukan");
        }

        return $this->kasRepository->update($id, $data);
    }

    public function deleteKas(string $id): bool
    {
        $kas = $this->kasRepository->findById($id);
        if (!$kas) {
            throw new Exception('Kas tidak ditemukan.');
        }

        return $this->kasRepository->delete($kas);
    }
}
