<?php

namespace Database;

use DateTime;
use Shared\Log;

class Connexion extends \PDO {
    private $stmt;

    public function __construct(string $dsn,string $username, string $password) {
        try {
            parent::__construct($dsn,$username,$password);
            $this->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        } catch (\PDOException $e) {
            // Log error or handle it as needed
            throw new \PDOException("Error connecting to the database: " . $e->getMessage());
        }
    }

    public function executeQuery(string $query, array $parameters = []) {
        $this->stmt = $this->prepare($query);
//        foreach ($parameters as $name => $value) {
//            $this->stmt->bindValue($name, $value[0], $value[1]);
//        }
        foreach ($parameters as $name => $value) {
            $dataType = is_numeric($value) ? \PDO::PARAM_INT : \PDO::PARAM_STR;
            $bindValueResult = $this->stmt->bindValue($name, $value, $dataType);
            if (!$bindValueResult) {
                // Gérez l'erreur, par exemple, en lançant une exception.
                throw new \PDOException('Failed to bind value for parameter ' . $name);
            }
        }
        return $this->stmt->execute();
    }

    public function executeWithErrorHandling(string $query, array $params = []): array {
        try {
            $this->beginTransaction();
            $this->executeQuery($query, $params);
            $this->commit();
            return $this->getResults();
        } catch (\PDOException $e) {
            $this->rollBack();
            throw new \PDOException('Unexpected error on database client: ' . $e->getMessage());
        }
    }

    public function getResults(): array {
        $results = $this->stmt->fetchAll(\PDO::FETCH_ASSOC);

        // Convertissez les colonnes "taille" et "poids" en nombres
        foreach ($results as &$row) {
            $row['taille'] = floatval($row['taille']);
            $row['poids'] = floatval($row['poids']);
        }

        return $results;
    }
}
?>