<?php

/**
 * FeedSync Session DB Class
 *
 *
 * @package FeedSync
 * @subpackage Session
 * @since 3.5.94
 */

class FS_Session_Database {
        
        private $host      = DB_HOST;
        private $user      = DB_USER;
        private $pass      = DB_PASS;
        private $dbname    = DB_NAME;
        private $mysqli;
        private $error;
        private $stmt;
        
        public function __construct(){
                
                $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
                if ($this->mysqli->connect_error) {
                        $this->error = $this->mysqli->connect_error;
                }
        }
        
        public function query($query){
                
                $this->stmt = $this->mysqli->prepare($query);
        }

        public function bind($type, ...$params) {
                $this->stmt->bind_param($type, ...$params);
        }

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

                $meta = $this->stmt->result_metadata();
                $row = [];
                $result = [];

                while ($field = $meta->fetch_field()) {
                        $params[] = &$row[$field->name];

                }
                call_user_func_array(array($this->stmt, 'bind_result'), $params);

                while ( $this->stmt->fetch() ) {

                        foreach($row as $key => $val) {
                
                            $c[$key] = $val;
                
                        }
                
                        $result[] = $c;
                
                }

                return $result;
        }
        
        public function resultset(){
                $this->execute();
                return $this->get_result();
        }
        
        public function single(){
                $this->execute();
                return current( $this->get_result() );
        }
        
        public function rowCount(){
                return count( $this->get_result() );
        }
        
        public function lastInsertId(){
                return $this->mysqli->insert_id;
        }
        
        public function close(){
                $this->mysqli->close();
        }
}