<?php

namespace App\Repositories;

use App\Models\DivisiModel;
use PDO;
use App\Config\DatasourceConfig;
use App\Helpers\DivisiMapper;

final class DivisiRepo
{

  private PDO $connection;
  private DivisiMapper $mapper;

  public function __construct()
  {
    $this->connection = (new DatasourceConfig())->connect();
    $this->mapper = new DivisiMapper();
  }

  private string $querySelect = "
    SELECT id_divisi, nama_divisi, deskripsi, created_at, updated_at
    FROM divisions
  ";

  public function findAll()
  {

    $statement = $this->connection->prepare($this->querySelect);
    $statement->execute();
    $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

    return array_map([$this->mapper, 'toDivisi'], $rows);
  }

  public function findById(int $id): ?DivisiModel
  {

    $statement = $this->connection->prepare($this->querySelect . " WHERE id_divisi = :id");
    $statement->execute(['id' => $id]);
    $row = $statement->fetch(PDO::FETCH_ASSOC);

    if (empty($row)) {
      return null;
    }

    return $this->mapper->toDivisi($row);
  }

  public function save(string $namaDivisi, ?string $deskripsi = null)
  {
    $query = "INSERT INTO divisions (nama_divisi, deskripsi) VALUES(:namaDivisi, :deskripsi);";

    $statement = $this->connection->prepare($query);
    $statement->execute([
      'namaDivisi' => $namaDivisi,
      'deskripsi' => $deskripsi
    ]);
  }

  public function update(int $id, string $namaDivisi, ?string $deskripsi = null)
  {
    $query = "UPDATE divisions SET nama_divisi=:namaDivisi, deskripsi=:deskripsi WHERE id_divisi=:id;";

    $statement = $this->connection->prepare($query);
    $statement->execute([
      'namaDivisi' => $namaDivisi,
      'deskripsi' => $deskripsi,
      'id' => $id
    ]);
  }

  public function delete(int $id)
  {
    $query = "DELETE FROM divisions WHERE id_divisi=:id;";

    $statement = $this->connection->prepare($query);
    $statement->execute([
      'id' => $id
    ]);
  }

  // findByNamaDivisi
  public function findByNamaDivisi(string $namaDivisi)
  {
    $statement = $this->connection->prepare($this->querySelect . " WHERE nama_divisi = :namaDivisi");
    $statement->execute(['namaDivisi' => $namaDivisi]);
    $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

    return array_map([$this->mapper, 'toDivisi'], $rows);
  }
}
