<?php

namespace Classes;

use PDO;

class Database
{

    protected $db;
    protected $error;

    public function __construct()
    {
        $this->connect();
    }

    public function connect()
    {
        $Options = [
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ];
        try {
            $this->db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET . ';', DB_USERNAME, DB_PASSWORD, $Options);
        } catch (PDOException $e) {
            $this->error = $e->getMessage();
            echo $this->error;
        }
    }
    public function fetch($sql, $data)
    {
        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(1, $data[0], PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_OBJ);
    }

    public function prepare($sql)
    {
        $this->stmt = $this->db->prepare($sql);
        return $this;
    }

    public function bind($name, $value, $type = null)
    {
        if ($type == null) {
            switch ($value) {
                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;
                default:
                    $type = PDO::PARAM_STR;
            }
        }
        $this->stmt->bindValue($name, $value, $type);
    }

    public function execute($values = null)
    {
        if (is_array($values)) {
            if (count($values) > 0) {
                return $this->stmt->execute($values);
            } else {
                return $this->stmt->execute();
            }
        } else {
            return $this->stmt->execute();
        }
    }

    public function resultStr()
    {
        $this->execute();
        return $this->stmt->fetchAll(PDO::FETCH_OBJ);
    }

    public function rowCount()
    {
        $this->execute();
        return $this->stmt->rowCount();
    }

    public function lastInsertId()
    {
        return $this->db->lastInsertId();
    }
}
