<?php
class SessionDBHandler implements SessionHandlerInterface {
    private $db;
    private $config;
    
    function __construct() {
	    global $config;
	    
	    $this->config = $config;
    }
    
    function open($savePath, $sessionName) {
	    
        $this->db = MysqliDb::getInstance();
        
        return true;
    }

    function close() {
        return true;
    }

    function read($id) {
	    $session_data = '';
	    $result = $this->db->rawQuery('SELECT session_data FROM sessions WHERE session_id = ? AND session_expires > ?', [$id, date('Y-m-d H:i:s')]);
	    $session_data = isset($result[0]['session_data']) && !empty($result[0]['session_data']) ? $result[0]['session_data'] : '';

		if (!is_string($session_data)) $session_data = '';	    

	    return $session_data;
    }

    function write($id, $data) {
	    $dateTime = date('Y-m-d H:i:s');
	    $expireTime = $this->config['settings']['session-expires'];
        $newDateTime = date('Y-m-d H:i:s', strtotime($dateTime.' '.$expireTime));
                
        $this->db->rawQuery("INSERT INTO sessions (session_id, user_ip, session_expires, session_updated_at, session_data) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE session_id=?, user_ip=?, session_expires=?, session_updated_at=?, session_data=?", [$id, $_SERVER['REMOTE_ADDR'], $newDateTime, $dateTime, $data, $id, $_SERVER['REMOTE_ADDR'], $newDateTime, $dateTime, $data]);
        
        return $this->db->getLastErrno() === 0 ? true : false;
    }

    function destroy($id) {
	    
	    if ($this->db->where('session_id', $id)->delete('sessions')) {
		    return true;
	    } else {
			return false;
	    }
    }

    function gc($maxlifetime) {
	    
	    $this->db->rawQuery("DELETE FROM sessions WHERE ((UNIX_TIMESTAMP(session_expires) + ?) < ?)", [$maxlifetime, $maxlifetime]);
	    
	    return $this->db->getLastErrno() === 0 ? true : false;

    }
}