<?php

class infoTips_model extends CI_Model
{
    var $topnum = false; //返回记录数
    var $orderby = false;
    var $where = false; //查询条件

    function __construct()
    {
        parent::__construct();
        $this->HT = $this->load->database('INFORMATION', TRUE);
    }

    public function init() {
        $this->topnum = false;
        $this->where = false;
        $this->orderby = ' order by it_expires ASC ';
    }

    public function  detail($it_id){
        $this->init();
        $this->topnum = 1;
        $this->where = ' AND  it.it_id=' . $this->HT->escape($it_id);
        return $this->get_list();
    }


    public function get_list() {
        $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT ";
        $sql .= "    
                    it.it_id
                    ,it.it_title
                    ,it.it_expires
                    ,it.it_code
                    ,it.it_content
                    ,it.it_sitecode
                    ,it.it_datetime
                 from infoTips it
                  where 1=1
                  AND it.it_sitecode=?
                 ";
        $this->where ? $sql.=$this->where : false;
        $this->orderby ? $sql.=$this->orderby : false;
        $query = $this->HT->query($sql,array($this->config->item('site_code')));
        //print_r($this->INFO->queries);
        if ($this->topnum === 1) {
            if ($query->num_rows() > 0) {
                $row = $query->row();
                return $row;
            } else {
                return FALSE;
            }
        } else {
            return $query->result();
        }
    }

    public function search($keywords, $byWhat) {
      $whereCodition = '';

      if ($byWhat == 'byTitle') {
        $whereCodition .= " and it.it_title like '%" . $this->HT->escape_str($keywords) . "%'";
      } else if ($byWhat == 'byLabel') {
        $whereCodition .= " and it.it_code like '%" . $this->HT->escape_str($keywords) . "%'";
      } else if ($byWhat == 'byContent') {
        $whereCodition .= " and it.it_content like '%" . $this->HT->escape_str($keywords) . "%'";
      }
      $searchText = 
        "select it.it_id ,it.it_title,it.it_expires,it.it_code,it.it_content,it.it_sitecode,it.it_datetime 
        from infoTips it
        where it.it_sitecode=?"
        . $whereCodition
        . " order by it_expires ASC";
      $query = $this->HT->query($searchText, array($this->config->item('site_code')));
      return $query->result();
    }

    public function add($table, $data)
    {
        if ($this->HT->insert($table, $data)) {
            return $this->HT->last_id($table);
        } else {
            return false;
        }
    }

    public function update($table, $data, $where)
    {
        return $this->HT->update($table, $data, $where);
    }

    public function delete($table, $where)
    {
        return $this->HT->delete($table, $where);
    }


}