<?php
if (!defined('APP_ROOT')) {
    die('Bootstrap not loaded');
}

function cyldb_select(PDO $pdo, string $sql, array $params = []): array
{
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll();
    } catch (Throwable $e) {

        $dbError = [
            'message' => $e->getMessage(),
            'query'   => $sql,
            'params'  => $params
        ];

        error_log(
            '[DB ERROR] ' .
            $dbError['message'] .
            ' | SQL: ' . $sql .
            ' | PARAMS: ' . json_encode($params)
        );

        http_response_code(500);
        require APP_ROOT . '/errors/500.php';
        die;
    }
}

function cyldb_exec(
    PDO $pdo,
    string $sql,
    array $params = []
): int {
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);

        return $stmt->rowCount();

    } catch (Throwable $e) {

        $dbError = [
            'message' => $e->getMessage(),
            'query'   => $sql,
            'params'  => $params
        ];

        error_log(
            '[DB EXEC ERROR] ' .
            $dbError['message'] .
            ' | SQL: ' . $sql .
            ' | PARAMS: ' . json_encode($params)
        );

        http_response_code(500);
        require APP_ROOT . '/errors/500.php';
        die;
    }
}