<?php

namespace App\Services;

use App\Repositories\AkunRepository;

class AkunService
{
    protected $akunRepository;

    public function __construct(AkunRepository $akunRepository)
    {
        $this->akunRepository = $akunRepository;
    }

    public function getAll()
    {
        return $this->akunRepository->getAll();
    }

    public function findById($id)
    {
        return $this->akunRepository->findById($id);
    }

    public function findByKodeAkun($kode_akun)
    {
        return $this->akunRepository->findByKodeAkun($kode_akun);
    }

    public function createAkun(array $data)
    {
        $akun = $this->akunRepository->findById($data['kode_akun']);
        if (!$akun) {
            if ($data['kode_induk']) {
                $induk = $this->akunRepository->findByKodeAkun($data['kode_induk']);
                $data['level'] = $induk->level + 1;
            } else {
                $data['level'] = 1;
            }

            return $this->akunRepository->createAkun($data);
        } else {
            return $this->akunRepository->updateAkun($data['kode_akun'], $data);
        }
    }

    public function updateAkun($id, array $data)
    {
        $akun = $this->akunRepository->findById($data['id']);
        if (!$akun) {
            throw new \Exception('Akun tidak ditemukan');
        }

        if ($data['kode_akun'] && $data['kode_akun'] != $akun->kode_akun) {
            $akun_kode = $this->akunRepository->findByKodeAkun($data['kode_akun']);
            if ($akun_kode) {
                throw new \Exception('Duplikat kode akun');
            };
        }
        return $this->akunRepository->updateAkun($id, $data);
    }

    public function deleteAkun(string $id)
    {
        $akun = $this->akunRepository->findByKodeAkun($id);
        if (!$akun) {
            throw new \Exception('Akun tidak ditemukan');
        }
        return $this->akunRepository->deleteAkun($id);
    }
}
