<?php

declare(strict_types=1);

namespace App\Repository;

final class MaestroRepository
{
    private \PDO $database;

    public function __construct(\PDO $database)
    {
        $this->database = $database;
    }

    public function getDb(): \PDO
    {
        return $this->database;
    }

    public function checkAndGet(int $MaestroId): object
    {
        $query = 'SELECT * FROM `Maestro` WHERE `id` = :id';
        $statement = $this->getDb()->prepare($query);
        $statement->bindParam('id', $MaestroId);
        $statement->execute();
        $Maestro = $statement->fetchObject();
        if (! $Maestro) {
            throw new \Exception('Maestro not found.', 404);
        }

        return $Maestro;
    }

    public function getAll(): array
    {
        $query = 'SELECT * FROM `Maestro` ORDER BY `id`';
        $statement = $this->getDb()->prepare($query);
        $statement->execute();

        return (array) $statement->fetchAll();
    }

    public function create(object $Maestro): object
    {
        $query = 'INSERT INTO `Maestro` (`campo`, `texto`, `estado`) VALUES (:campo, :texto, :estado)';
        $statement = $this->getDb()->prepare($query);
//         $statement->bindParam('id', $Maestro->id);
//         $statement->bindParam('fecha', $Maestro->fecha);
        $statement->bindParam('campo', $Maestro->campo);
        $statement->bindParam('texto', $Maestro->texto);
        $statement->bindParam('estado', $Maestro->estado);

        $statement->execute();

        return $this->checkAndGet((int) $this->getDb()->lastInsertId());
    }

    public function update(object $Maestro, object $data): object
    {
        if (isset($data->fecha)) {
            $Maestro->fecha = $data->fecha;
        }
        if (isset($data->campo)) {
            $Maestro->campo = $data->campo;
        }
        if (isset($data->texto)) {
            $Maestro->texto = $data->texto;
        }
        if (isset($data->estado)) {
            $Maestro->estado = $data->estado;
        }

        $query = 'UPDATE `Maestro` SET `fecha` = :fecha, `campo` = :campo, `texto` = :texto, `estado` = :estado WHERE `id` = :id';
        $statement = $this->getDb()->prepare($query);
        $statement->bindParam('id', $Maestro->id);
        $statement->bindParam('fecha', $Maestro->fecha);
        $statement->bindParam('campo', $Maestro->campo);
        $statement->bindParam('texto', $Maestro->texto);
        $statement->bindParam('estado', $Maestro->estado);

        $statement->execute();

        return $this->checkAndGet((int) $Maestro->id);
    }

    public function delete(int $MaestroId): void
    {
        $query = 'DELETE FROM `Maestro` WHERE `id` = :id';
        $statement = $this->getDb()->prepare($query);
        $statement->bindParam('id', $MaestroId);
        $statement->execute();
    }
}
