<?php

namespace App\Repositories;

use PDO;
use App\Config\DatasourceConfig;
use App\Helpers\CategoryMapper;

final class CategoryRepo
{
  private PDO $connection;
  private CategoryMapper $mapper;

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

  private string $querySelect = "
        SELECT id_kategori, nama_kategori, deskripsi, created_at, updated_at
        FROM categories
    ";

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

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

  public function findById(int $id)
  {
    $statement = $this->connection->prepare($this->querySelect . " WHERE id_kategori = :id");
    $statement->execute([
      'id' => $id
    ]);

    $row = $statement->fetch(PDO::FETCH_ASSOC);

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

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

  public function save(string $namaKategori, ?string $deskripsi = null)
  {
    $query = "
            INSERT INTO categories (nama_kategori, deskripsi)
            VALUES (:namaKategori, :deskripsi);
        ";

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

  public function update(int $id, string $namaKategori, ?string $deskripsi = null)
  {
    $query = "
            UPDATE categories
            SET nama_kategori = :namaKategori,
                deskripsi = :deskripsi
            WHERE id_kategori = :id;
        ";

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

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

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

  // findByNamaKategori
  public function findByNamaKategori(string $namaKategori)
  {
    $statement = $this->connection->prepare(
      $this->querySelect . " WHERE nama_kategori = :namaKategori"
    );

    $statement->execute([
      'namaKategori' => $namaKategori
    ]);

    $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

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