<?php
/**
 * SQL Handler
 */

class db{

    static $instance , $i;

    public $queries = 0;
    public $error , $user_error;
    public $dataObject;
    public $rows = 0;

    /**
     * Połączenie MySql
     */
    public function __construct(){



        $this -> connection = @mysqli_connect(  _cfg::$i->db->host , _cfg::$i->db->user , _cfg::$i->db->pass );
        $this -> q( 'SET NAMES ' . _cfg::$i->db->charset );

        if( $this -> connection ) $this -> status = 1;

        $this -> selected_base = mysqli_select_db( $this->connection , _cfg::$i->db->base );

        if( !$this -> selected_base ) $this -> status = 2;


        self::$i = $this;
        self::$instance = $this;

    }

    public function __desctruct(){
        mysqli_close( $this -> connection );
    }


    public function q( $query , $counter = false , $pagination = false ){

        $this -> query = $query;

        if( $pagination ){

            $rows = $this -> count( preg_replace("#select\s([a-zA-Z\*\._\(\)]+)\sfrom#i","select 1 from", $this -> query ) );

            str::$instance->modify('results', $rows );
            str::$instance->params();

            $this -> resource = mysqli_query( $this->connection ,$this -> query . " limit ". str::$instance->from ."," . str::$instance->to);

        } else $this -> resource = mysqli_query( $this->connection, $this -> query );



        if( !$this -> resource ) $this -> error = mysqli_error( $this->connection );
        else {
            $this -> queries++;
            if( $counter and !$pagination ){
                db::$instance->count( $this -> query );
            }


        }

        return $this -> resource;

    }

    public function f( $resource ){
        return mysqli_fetch_array( $resource );
    }

    public function insert( $table , $array , $mode = INSERT_TO_DATABASE ){

        $fields = array();
        $values = array();

        foreach( $array as $field => $value ){
            array_push( $fields , "`{$field}`" );
            array_push( $values , $value === null ? "NULL" : "'{$value}'" );
        }

        $query = "INSERT INTO `{$table}` (" . join( "," , $fields ) .") VALUES(" . join( "," , $values ). ")";

        switch( $mode ){

            case 'INSERT_TO_DATABASE':

                if( db::$instance->q( $query ) ){

                    $this -> insert_id = mysqli_insert_id( $this->connection );
                    return true;

                } else return false;

                break;

            case 'QUERY_BACK':
                return $query;
                break;

            default:

                //

                break;
        }

    }

    public function update( $table , $array , $id = false , $where = 'id' ){

        $revalue = array();
        foreach( $array as $field => $value ){
            array_push( $revalue , (("`{$field}` = ").($value === null ? "NULL" : "'{$value}'")) );
        }

        if( !$id ) $query = "UPDATE `{$table}` SET ".join(' , ',$revalue)." WHERE {$where}";
        else $query = "UPDATE `{$table}` SET ".join(' , ',$revalue)." WHERE `{$where}`='{$id}'";

        if( db::$instance->q( $query ) ) return true;
        else return false;

    }

    public function chk($what,$from,$field_name){

        $request = db::$instance->row("SELECT `$field_name` FROM `$from` WHERE `$field_name` = '$what'");

        if( $request ) return true;
        else return false;
    }

    public function del( $table , $value , $field_name , $limit='1' ){

        if( db::$instance -> chk( $value , $table , $field_name ) ){

            if( db::$instance->q("DELETE FROM `".esc($table)."` WHERE `{$field_name}`='{$value}' LIMIT {$limit}")) return true;
            else {
                $this->user_error = l('Podczas usuwanie wystąpił błąd');
                return false;
            }

        } else {
            $this->user_error = l('Element który próbujesz usunąć nie istnieje');
            return false;
        }
    }

    public function count( $query ){

        $query = mysqli_query( $this->connection , $query );
        $this -> queries++;

        if( !$query ) $this -> error = mysqli_error( $this->connection );
        else {
            $this -> rows = $rows = mysqli_num_rows( $query );
            $this->queries++;
        }

        return $this->rows;
    }


    public function rowsClean(){
        $this->rows = false;
    }

    public function converted( $query , $use_parser = false , $from_class = false ){

        $data = db::$instance->q( $query );
        if( $data ){

            if( mysqli_num_rows( $data ) ){

                while( $item = db::$i->f( $data ) ){

                    // Parsowanie wynikow
                    if( $use_parser ){
                        /*
                        if((version_compare(phpversion(),"5.3.0")>=0)){
                            if( $from_class ) $item = $from_class::$use_parser( $item );
                            else $item = $use_parser( $item );
                        } else {
                            if( $from_class ) $item = eval( ''.$from_class.'::'.$use_parser.'( '.$item.' )');
                            else $item = $use_parser( $item );
                        }
                        */
                        if( $from_class ) $item = eval( ''.$from_class.'::'.$use_parser.'( '.$item.' )');
                        else $item = $use_parser( $item );
                    }
                    // --->

                    $arr[] = $item;
                }
                return $arr;
            }
        }

        return false;
    }

    /**
     * Pobierz element na podstawie ID
     * @param string $table - Nazwa tabeli mysql
     * @param int $id - Identyfikator / Domyślnie core::$i->id
     */
    public function byid( $table , $id = false ){
        if(!$id) $id = core::$i->id;

        if( $row = $this->row("SELECT * FROM `".esc( $table )."` WHERE `id`='".esc( $id )."'") ) return $row;
        else return false;
    }

    public function getBy( $value , $from , $by = 'id' , $limit = false , $fetch = false ){

        if( is_array( $by ) ){

            $wheres = array();

            foreach( $by AS $field => $val ){
                $wheres[] = "`{$field}`='{$val}'";
            }

            $where = join( ' AND ' , $wheres );

        } else $where = "`{$by}`='{$value}'";

        $backdata = db::$instance->q("SELECT * FROM `{$from}` WHERE {$where}" . ( $limit ? " LIMIT {$limit}" : ''));
        if( $fetch ) $backdata = db::$instance->f( $backdata );

        return $backdata;
    }

    public function row( $query ){
        return $this->f( $this->q( $query . " LIMIT 1" ) );
    }

    public function once( $field , $from , $where , $order = false ){
        $q = $this->row( "select `{$field}` from `{$from}` where {$where}" . ($order ? (" ORDER BY {$order}") : '') );
        return $q[0];
    }

    /**
     * @param void
     */
    public function read( $query = false ){
        return db::$instance->f( $query ? $query : db::$instance->resource );
    }

    /**
     *
     */
    public function delete( $table , $by , $byname = 'id' ){

        if( $this->q("DELETE FROM `{$table}` WHERE `{$byname}`='{$by}'") ) return true;
        else $this->user_error = CE_EXISTS;

    }

    public static function getWhere( $field , $operator , $value )
    {
        switch( $operator )
        {
            case 'like':
                return "`".$field."` LIKE('".esc( $value )."')";
                break;

            case 'in':
                return "`".$field."` IN(".esc( $value ).")";
                break;

            default:

                return "`".$field."`".$operator."'".esc( $value )."'";

                break;
        }
    }

    public static function decreasing( $table , $field  , $WhereArray , $DecreasingValue = 1 )
    {

        if( !count( $WhereArray ) ) return;

        $query = "UPDATE `".( $table )."` SET `".( $field )."`=`".( $field )."`-".esc( $DecreasingValue )." WHERE ".query::where( $WhereArray );
        return self::$i->q( $query );



    }

    public static function increasing( $table , $field  , $WhereArray , $DecreasingValue = 1 )
    {

        if( !count( $WhereArray ) ) return;

        $query = "
            UPDATE `".( $table )."` 
            SET `".( $field )."`=`".( $field )."`+".esc( $DecreasingValue )." 
            WHERE " . query::where( $WhereArray );

        return self::$i->q( $query );


    }

    public static function ExistsById( $Table , $id )
    {
        return self::$i->row("
            SELECT 1 
            FROM `".( $Table )."` 
            WHERE `id`='".( esc( $id ) )."'
            ");
    }

}

?>