<?php

namespace App\Services;

use App\Repositories\DivisiRepo;

class DivisiService
{
  private $divisiRepo;

  public function __construct()
  {
    $this->divisiRepo = new DivisiRepo();
  }

  public function findAll()
  {
    return $this->divisiRepo->findAll();
  }

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

  public function save(string $namaDivisi, ?string $deskripsi = null)
  {
    $this->isValid($namaDivisi);
    return $this->divisiRepo->save($namaDivisi, $deskripsi);
  }

  public function update(int $id, string $namaDivisi, ?string $deskripsi = null)
  {
    // find by id
    $divisi = $this->divisiRepo->findById($id);

    if (empty($divisi)) {
      throw new \Exception('Divisi tidak ditemukan.');
    }
    $this->isValid($namaDivisi, $id);
    return $this->divisiRepo->update($id, $namaDivisi, $deskripsi);
  }

  public function delete(int $id)
  {
    return $this->divisiRepo->delete($id);
  }

  // validation
  private function validate(string $namaDivisi, ?int $id = null)
  {
    $errors = [];

    if (trim($namaDivisi) === '') {
      $errors['namaDivisi'] = 'Nama wajib diisi.';
    }

    // nama divisi harus unik
    $divisi = $this->divisiRepo->findByNamaDivisi($namaDivisi);

    if ($divisi !== null && count($divisi) > 0 && $divisi[0]->getId() !== $id) {
      $errors['namaDivisi'] = 'Nama divisi sudah ada.';
    }

    return $errors;
  }

  private function isValid(string $namaDivisi, ?int $id = null)
  {
    $errors = $this->validate($namaDivisi, $id);

    if (count($errors) > 0) {
      throw new \Exception(implode(', ', $errors));
    }
  }
}
