<?php
print_r ($_SERVER);
//require_once "/saa_dsk/www/vendor/autoload.php";
require_once "/usr/share/nginx/html/checadores/vendor/autoload.php";
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
use \SeinopSys\PostgresDb;

# Connect to the database
try {
    // Postgres
    $pdo = new PDO("pgsql:host=" . $_ENV['DB_HOST'] . ";dbname=" . $_ENV['DB_NAME'], $_ENV['DB_USER'], $_ENV['DB_PASS']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $db = new PostgresDb();
    $db->setConnection($pdo);
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

// check recursivelly if the array has only empty strings
function is_response_empty($array)
{
    foreach ($array as $value) {
        if (is_array($value)) {
            if (!is_response_empty($value)) {
                return false;
            }
        } else {
            if (!empty($value)) {
                return false;
            }
        }
    }
    return true;
}

// SQL function
function query(string $sql, array $params = null, bool $single = true)
{
    global $pdo;
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $response = $single ? $stmt->fetch(PDO::FETCH_ASSOC) : $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $response;
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
        return false;
    } finally {
        $stmt->closeCursor();
        $stmt = null;
    }
}

function queryAll(string $sql, array $params = null)
{
    return query($sql, $params, false);
}

function toSQLArray(array $array): string
{
    return sprintf("{%s}", implode(", ", $array));
}
