<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class MY_Model extends CI_Model {

    protected $_table_name = '';
    protected $_primary_key = 'id';
    protected $_primary_filter = 'intval';
    protected $_order_by = '';
    protected $_rules = array();
    protected $_timestamps = FALSE;

    function __construct() {
        parent::__construct();
    }

    public function get($id = NULL, $single = FALSE) {
        if ($id != NULL) {
            $filter = $this->_primary_filter;
            $id = $filter($id);
            $this->db->where($this->_primary_key, $id);
            $method = 'row';
        } else if ($single == TRUE) {
            $method = 'row';
        } else {
            $method = 'result';
        }
        if (!count($this->db->order_by($this->_order_by))) {
            $this->db->order_by($this->_order_by);
        }
        return $this->db->get($this->_table_name)->$method();
    }

    public function get_by($where, $single = FALSE) {
        $this->db->where($where);
        return $this->get(NULL, $single);
    }

    public function save($data, $id = NULL) {
        $status = false;
        if ($id !== NULL) {
            $this->_timestamps = TRUE;
        }
        if ($this->_timestamps == TRUE) {
            $now = date('Y-m-d H:i:s');
            $id || $data['created_at'] = $now;
            $data['updated_at'] = $now;
        }
        if ($id === NULL) {
            !isset($data[$this->_primary_key]) || $data[$this->_primary_key] == NULL;
            $this->db->set($data);
            $status = $this->db->insert($this->_table_name);
            $id = $this->db->insert_id();
        } else {
            $filter = $this->_primary_filter;
            $id = $filter($id);
            $this->db->set($data);
            $this->db->where($this->_primary_key, $id);
            $status = $this->db->update($this->_table_name);
        }
        if ($id) {
            return $id;
        } else {
            return $status;
        }
    }

    public function delete($id) {
        $filter = $this->_primary_filter;
        $id = $filter($id);
        if (!$id) {
            return FALSE;
        }
        $this->db->where($this->_primary_key, $id);
        $this->db->limit(1);
        $status = $this->db->delete($this->_table_name);
        return $status ? $id : $status;
    }

    public function get_list($table, $condition = null, $columns = null, $limit = null, $offset = 0, $order_field = null, $order_type = null) {
        if ($columns) {
            $this->db->select($columns);
        }
        if ($limit) {
            $this->db->limit($limit, $offset);
        }
        if ($condition) {
            $this->db->where($condition);
        }
        if ($order_field && $order_type) {
            $this->db->order_by($order_field, $order_type);
        }

        return $this->db->get($table);
    }

    public function get_single($table, $condition = null, $columns = '*', $order = null) {
        $this->db->select($columns);
        if ($order) {
            $this->db->order_by($order);
        }
        if ($condition) {
            $this->db->where($condition);
        }
        $this->db->limit(1);
        return $this->db->get($table);
    }

    public function exists($table, $column, $value) {
        return $this->db->where($column, $value)->count_all_results($table) > 0;
    }

    function count_rows($table, $condition = null) {
        if ($condition) {
            $this->db->where($condition);
        }
        $this->db->from($table);
        return $this->db->count_all_results();
    }

    public function get_min_max($table, $column, $condition = null) {
        $this->db->select_max($column, 'max');
        $this->db->select_min($column, 'min');
        if ($condition) {
            $this->db->where($condition);
        }
        return $this->db->get($table);
    }

    public function isThisUserAnOnlineLogger() {
        return $this->session->userdata('owner') != false && $this->session->userdata('team') != false && $this->session->userdata('group') != false && $this->session->userdata('branch') != false;
    }

    public function isThisUserAnEposLogger() {
        return $this->session->userdata('owner') != false && $this->session->userdata('team') != false && $this->session->userdata('group') != false && $this->session->userdata('branch') != false;
    }

    function eposUserLogout() {
        if ($this->db->update('user', array('isLoggedIn' => 'no'), array('id' => $this->session->userdata('owner'))) && $this->db->update('userlogtime', array('logout' => date('Y-m-d H:i:s')), array('id' => $this->session->userdata('usserAccessID')))) {
            if (session_destroy()) {
                return true;
            }
        } else {
            return false;
        }
    }

    public function checkEposCookie() {
        $restaurantName = $this->config->item('general_name');
        $restaurantNameWithUnderScore = preg_replace('/\s+/', '_', $restaurantName);
        $primary = $this->input->cookie($restaurantNameWithUnderScore . 'pqr', true);
        $secondary = $this->input->cookie($restaurantNameWithUnderScore . 'mno', true);
        $tertiary = $this->input->cookie($restaurantNameWithUnderScore . 'xyz', true);
        if ($primary && $tertiary && $tertiary) {
            return array('primary' => base64_decode($primary), 'secondary' => base64_decode($secondary), 'tertiary' => base64_decode($tertiary));
        } else {
            return FALSE;
        }
    }

    public function hasEposUpdate() {
        if ($this->isThisUserAnEposLogger()) {
            $userUpdate = $this->db->where(array('id' => (int) $this->session->userdata('owner'), 'hasUpdate' => 'yes'))->get('user')->row();
            $updates = $updates = $this->db->where(array('status' => 2, 'user' => $this->session->userdata('owner')))->get('updates')->result();
            if (!empty($userUpdate) && !empty($updates)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function posactivity($data = null) {
        $data['user'] = $this->session->userdata('owner') ? $this->session->userdata('owner') : 0;
        $data['branch'] = $this->session->userdata('branch') ? $this->session->userdata('branch') : 0;
        $data['login_ip'] = $_SERVER['REMOTE_ADDR'];
        $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
        $data['access_time'] = date('Y-m-d H:i:s');
        $data['access_url'] = base_url(uri_string());
        $data['access_id'] = $this->session->userdata('usserAccessID') ? $this->session->userdata('usserAccessID') : 0;
        $this->db->set($data);
        $this->db->insert('useractivity', $data);
        return $this->db->insert_id();
    }

    function notifyupdate($issue) {
        $s1 = $this->db->update('user', array('hasUpdate' => 'yes'), array('branch' => $this->session->userdata('branch')));
        $issueObj = $this->get_single('updateissue', array('title' => $issue))->row();
        $users = $this->get_list('user', array('hasUpdate' => 'yes', 'branch' => $this->session->userdata('branch')))->result();
        $s2 = true;
        if (!empty($users && $s1)) {
            foreach ($users as $auser) {
                $doesExist = $this->get_single('updates', array('user' => $auser->id, 'issue' => $issueObj->id, 'branch' => $this->session->userdata('branch')))->row();
                $s2 = $doesExist ? $this->db->update('updates', array('status' => 2), array('user' => $auser->id, 'issue' => $issueObj->id, 'branch' => $this->session->userdata('branch'))) : $this->db->insert('updates', array('issue' => $issueObj->id, 'issueTitle' => $issueObj->title, 'user' => $auser->id, 'branch' => $this->session->userdata('branch')));
            }
        }
        return $s1 && $s2;
    }

}
