<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Smstemplate_model extends MY_Model
{
	
	protected $table_name = 'tblsmstemplate';
	protected $id_name = 'sms_id';

	function __construct()
	{
		parent::__construct();
	}
	function getSmstemplates($data) {
        $sql = "SELECT * FROM " . $this->table_name;
        if ($data['keyword']) {
            if ($data['search_field'] == "cellphone") {
                $sql.=" WHERE (service_id LIKE '%" . $data['keyword'] . "%')";
            } else {
                $sql.=" WHERE (sms_content LIKE '%" . $data['keyword'] . "%' OR sms_reply LIKE '%" . $data['keyword'] . "%') ";
            }
        }

        $order = "";
        if ($data['sorting_order'] != "sorting") {
            if ($data['sorting_field'] != "money") {
                $sort = "DESC";
                if ($data['sorting_order'] == "sorting_asc")
                    $sort = "ASC";
                $order = "ORDER BY " . $data['sorting_field'] . " " . $sort;
            }
        }
        $sql=$sql . " " . $order . " LIMIT " . $data['start'] . ", " . $data['perpage'] . " ";
       
        return $this->db->query($sql)->result_array();
    }

    function isExist($data) {
        $sql = "SELECT COUNT(id) as total FROM " . $this->table_name . " WHERE " . $data['field'] . " = '" . $data['value'] . "'";
        if (isset($data['id']))
        {
            $id=$data['id'];
            $sql.=" AND id <> ".$id." LIMIT 1";
        }
        $result = $this->db->query($sql)->row_array();
        if ($result['total'] == 1) {
            return true;
        } else {
            return false;
        }
    }

    function countSmstemplate($data) {
        $sql = "SELECT COUNT(".$this->id_name.") as total FROM " . $this->table_name;
        if ($data['keyword']) {
            if ($data['search_field'] == "cellphone") {
                $sql.=" WHERE (service_id LIKE '%" . $data['keyword'] . "%')";
            } else {
                $sql.=" WHERE (sms_content LIKE '%" . $data['keyword'] . "%' OR sms_reply LIKE '%" . $data['keyword'] . "%') ";
            }
        }
        $result = $this->db->query($sql)->row_array();
        return $result['total']; 
    }
    function getSmstemplate($id)
    {
        $sql="SELECT * FROM ".$this->table_name." WHERE ".$this->id_name."=".$id." LIMIT 1";
        $result = $this->db->query($sql)->row_array();
        return $result;
    }
}