<?php

class User_Model extends MY_Model {

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

    function logout() {
        if ($this->db->update('gkpos_customer', array('is_logged_in' => 0), array('phone' => $this->session->userdata('online_userphone'), 'email' => $this->session->userdata('online_useremail')))) {
            $this->session->sess_destroy();
            redirect('/');
        }
    }

    function is_logged_in() {
        return $this->session->userdata('online_userphone') != false && $this->session->userdata('online_useremail') != false;
    }

    public function get_single_post($slug) {
        $this->_table_name = 'post';
        return $this->get_by(array('slug' => $slug, 'is_published' => 1, 'is_deleted' => 0), TRUE);
    }

    public function get_page($slug) {
        $this->_table_name = 'page';
        return $this->get_by(array('slug' => $slug, 'is_published' => 1), TRUE);
    }

    public function get_code() {
        $key = self::_generate_code();
        if ($key) {
            return $key;
        }
    }

    private function _generate_code($length = 7) {
        do {
            $newkey = substr(str_shuffle(str_repeat($x = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
        } while (self::_code_exists($newkey));
        return $newkey;
    }

    private function _code_exists($key) {
        return $this->db->where('verified_code', $key)->count_all_results('gkpos_customer') > 0;
    }

}
