<?php

class db
{
    private static $dbh;
    private static $error;
    private static $qError;
    private static $stmt;

    private static function connexion()
    {
        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );

        try {
            self::$dbh = new PDO($dsn, DB_USER, DB_PASS, $options);
        } catch (PDOException $e) {
            self::$error = $e->getMessage();
        }
    }

    public static function query(string $query)
    {
        self::connexion();
        self::$stmt = self::$dbh->prepare($query);
    }

    public static function bind(string $param, string $value = NULL, string $type = null)
    {
        if (is_null($type)) {
            switch (true) {
                case is_int($value):
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = PDO::PARAM_NULL;
                    break;
                default:
                    $type = PDO::PARAM_STR;
            }
        }
        self::$stmt->bindValue($param, $value, $type);
    }

    public static function execute()
    {
        if(core::isDebug()){
            ob_start();
            $return = self::$stmt->execute();
            self::$stmt->debugDumpParams();
            $debugOutput = ob_get_clean();
            debug::logSession($debugOutput);
            return $return;
        } else {
            return self::$stmt->execute();
        }
    }

    public static function resultset()
    {
        self::execute();
        return self::$stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function single()
    {
        self::execute();
        return self::$stmt->fetch(PDO::FETCH_ASSOC);
    }

    public static function rowCount()
    {
        return self::$stmt->rowCount();
    }

    public static function lastInsertId()
    {
        return self::$dbh->lastInsertId();
    }

    public static function beginTransaction()
    {
        return self::$dbh->beginTransaction();
    }

    public static function endTransaction()
    {
        return self::$dbh->commit();
    }

    public static function cancelTransaction()
    {
        return self::$dbh->rollBack();
    }

    public static function debugDumpParams()
    {
        return self::$stmt->debugDumpParams();
    }

    public static function queryError()
    {
        self::$qError = self::$dbh->errorInfo();
        if (!is_null(self::$qError[2])) {
            echo self::$qError[2];
        }
    }
}
