<?php

namespace SCF\Core;

use PDO;
use PDOException;

class Database {
    /**
     * @var null|PDO
     */
    private $db = NULL;

    /**
     * @var
     */
    private $stmt;

    /**
     * @var string
     */
    private $error;

    /**
     * Database constructor.
     * @param $dbext
     * @param $dbhost
     * @param $dbuser
     * @param $dbpass
     * @param $dbname
     */
    public function __construct($dbext, $dbhost, $dbuser, $dbpass, $dbname)
    {
        $dsn = $dbext.':dbname='.$dbname.';host='.$dbhost.';charset=utf8';

        $options = [
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ];

        try {
            $this->db = new PDO($dsn, $dbuser, $dbpass, $options);
        }
        catch (PDOException $e) {
            $this->error = $e->getMessage();
        }
    }

    /**
     * @param $query
     */
    public function query($query)
    {
        $this->stmt = $this->db->prepare($query);
    }

    /**
     * @param $param
     * @param $value
     * @param null $type
     */
    public function bind($param, $value, $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;
            }
        }

        $this->stmt->bindValue($param,$value,$type);
    }

    /**
     * @return mixed
     */
    public function execute()
    {
        return $this->stmt->execute();
    }

    /**
     * @return mixed
     */
    public function fetchArray()
    {
        $this->execute();
        return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * @return mixed
     */
    public function single()
    {
        $this->execute();
        return $this->stmt->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * @return mixed
     */
    public function rowCount()
    {
        return $this->stmt->rowCount();
    }

    /**
     * @return mixed
     */
    public function lastInsertId()
    {
        return $this->stmt->lastInsertId();
    }


}