<?php
namespace DB;
final class Sqlite {
    private $connection;
    private $mode=SQLITE3_ASSOC;
    private $user;

    public function __construct($registry) {
        $this->user = $registry->get('user');

          $this->connection = new \SQLite3(DIR_USER_DB.$this->user->userdb().'.db');


    /*    if ($this->connection->connect_error) {
            throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno);
        }*/

     //   $this->connection->set_charset("utf8");
      //  $this->connection->query("SET SQL_MODE = ''");
    }






    function query( $query ){



        $res = $this->connection->query( $query );
        if ( !$res ){
            throw new Exception( $this->sqlite->lastErrorMsg() );
        }

        return $res;
    }

   public function row( $query ){
        $res = $this->query( $query );
        $row = $res->fetchArray( $this->mode );
        return $row;
    }

    function queryOne( $query ){
        $res = $this->sqlite->querySingle( $query );
        return $res;
    }

    public function rows( $query, $return_array = FALSE ){



        $rows = array();
        if( $res = $this->query( $query ) ){
            while($row = $res->fetchArray($this->mode)){
                $rows[] = $row;
            }
        }
        return $rows;
    }

    public function escape($value) {
        return $this->connection->real_escape_string($value);
    }

    public function countAffected() {
        return $this->connection->affected_rows;
    }

    public function getLastId() {
        return $this->connection->lastInsertRowID();
    }

    public function connected() {
        return $this->connection->ping();
    }
    function clean( $str ){
        return $this->connection->escapeString( $str );
    }

    public function logout() {
        $this->connection->close();
    }

    public function __destruct() {
        $this->connection->close();
    }
}
