<?php

require_once(LIB_PATH .'/'. 'database.php');

class DatabaseObject
{

	 public static function find_all()
    {
        global $database;
        return static::find_by_sql("SELECT * FROM " . static:: $table_name);
        //return $result_set;

    }

    public static function find_by_id($id = 0)
    {
        global $database;
        $result_array = static::find_by_sql("SELECT * FROM  " . static::$table_name . " WHERE id={$id} LIMIT 1");
        //$found = $database->fetch_array($result_set);
        //return $found;
        return !empty($result_array) ? array_shift($result_array) : false;

    }

    



    
    

    public static function find_by_sql($sql = "")
    {
        global $database; $connection='';
        $result_set = $database->query($sql);
        $object_array = array();
        while ($row = $database->fetch_array($result_set)) {
            $object_array[] = self::instantiate($row);
        }
        return $object_array;

    }

    private static function instantiate($record)
    {
    	$class_name = get_called_class();
        $object = new $class_name;
        foreach ($record as $attribute => $value) {
            if ($object->has_attribute($attribute)) {
                $object->$attribute = $value;
            }

        }
        return $object;
    }

    private function has_attribute($attribute)
    {

        $object_vars = get_object_vars($this);
        return array_key_exists($attribute, $object_vars);
    }

    public function save()
    {
        return isset($this->id) ? $this->update() : $this->create();
    }

    public function create()
    {
        global $database;
        $sql = "INSERT INTO " . static::$table_name . " (";
        $sql .= "username, password";
        $sql .= ") 	VALUES ('";
        $sql .= $database->escape_value($this->username) . "', '";
        $sql .= $database->escape_value($this->password) . "') '";
        if ($database->query($sql)) {
            $this->id = $database->insert_id();
            return true;
        } else {
            return false;
        }

    }

    public function update1()
    {

        global $database;
        $sql = "UPDATE " . static::$table_name . "(";
        $sql .= "formno = '" . $database->escape_value($this->username) . "',";
        $sql .= "email ='" . $database->escape_value($this->password) . "', ";
        $sql .= "WHERE id=" . $database->escape_value($this->id);

        $database->query($sql);
        return ($database->affected_rows() == 1) ? true : false;
    }

    public static function delete1($id=0)
    {
        global $database;
       $id= $database->escape_value($id);
        $sql = "DELETE FROM " . static::$table_name . " ";
        $sql .= "WHERE id=" .$id ;
        $sql .= " LIMIT 1";
        $database->query($sql);
        return ($database->affected_rows() == 1) ? true : false;
    }




    /*
     * Returns rows from the database based on the conditions
     * @param string name of the table
     * @param array select, where, order_by, limit and return_type conditions
     */
   /* public function getRows($table, $conditions = array()){
          global $database;
        $sql = 'SELECT ';
        $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
        $sql .= ' FROM '.$table;
        if(array_key_exists("where",$conditions)){
            $sql .= ' WHERE ';
            $i = 0;
            foreach($conditions['where'] as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $sql .= $pre.$key." = '".$value."'";
                $i++;
            }
        }
        
        if(array_key_exists("order_by",$conditions)){
            $sql .= ' ORDER BY '.$conditions['order_by']; 
        }else{
            $sql .= ' ORDER BY id DESC '; 
        }
        
        if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit']; 
        }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
            $sql .= ' LIMIT '.$conditions['limit']; 
        }
        
        $result = $database->query($sql);
        
        if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
            switch($conditions['return_type']){
                case 'count':
                    $data = $result->num_rows;
                    break;
                case 'single':
                    $data = $result->fetch_assoc();
                    break;
                default:
                    $data = '';
            }
        }else{
            if($result->num_rows > 0){
                while($row = $result->fetch_assoc()){
                    $data[] = $row;
                }
            }
        }
        return !empty($data)?$data:false;
    }
    
    /*
     * Insert data into the database
     * @param string name of the table
     * @param array the data for inserting into the table
     */
    /*public function insert($table, $data){
          global $database;
        if(!empty($data) && is_array($data)){
            $columns = '';
            $values  = '';
            $i = 0;
            if(!array_key_exists('created',$data)){
                $data['created'] = date("Y-m-d H:i:s");
            }
            if(!array_key_exists('modified',$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $columns .= $pre.$key;
                $values  .= $pre."'".$this->database->real_escape_string($val)."'";
                $i++;
            }
            $query = "INSERT INTO ".$table." (".$columns.") VALUES (".$values.")";
            $insert = $database->query($query);
            return $insert? $database->insert_id:false;
        }else{
            return false;
        }
    }
    
    /*
     * Update data into the database
     * @param string name of the table
     * @param array the data for updating into the table
     * @param array where condition on updating data
     */
    /*public function update($table, $data, $conditions){
          global $database;
        if(!empty($data) && is_array($data)){
            $colvalSet = '';
            $whereSql = '';
            $i = 0;
            if(!array_key_exists('modified',$data)){
                $data['modified'] = date("Y-m-d H:i:s");
            }
            foreach($data as $key=>$val){
                $pre = ($i > 0)?', ':'';
                $colvalSet .= $pre.$key."='".$this->database->real_escape_string($val)."'";
                $i++;
            }
            if(!empty($conditions)&& is_array($conditions)){
                $whereSql .= ' WHERE ';
                $i = 0;
                foreach($conditions as $key => $value){
                    $pre = ($i > 0)?' AND ':'';
                    $whereSql .= $pre.$key." = '".$value."'";
                    $i++;
                }
            }
            $query = "UPDATE ".$table." SET ".$colvalSet.$whereSql;
            $update = $this->database->query($query);
            return $update?$database->affected_rows:false;
        }else{
            return false;
        }
    }
    
    /*
     * Delete data from the database
     * @param string name of the table
     * @param array where condition on deleting data
     */
    /*public function delete($table, $conditions){
          global $database;
        $whereSql = '';
        if(!empty($conditions)&& is_array($conditions)){
            $whereSql .= ' WHERE ';
            $i = 0;
            foreach($conditions as $key => $value){
                $pre = ($i > 0)?' AND ':'';
                $whereSql .= $pre.$key." = '".$value."'";
                $i++;
            }
        }
        $query = "DELETE FROM ".$table.$whereSql;
        $delete = $database->query($query);
        return $delete?true:false;
    }*/

    //Closing tags for user's class
}








?>