<?php

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

class Templates_model extends CI_Model {

    var $insert_id = -1;
    var $top_num = false;
    var $tp_sn = false;
    var $order_by = false;

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

    function init() {
        $this->top_num = false;
        $this->tp_sn = false;
        $this->order_by = ' ORDER BY tp.tp_title ASC ';
    }

    public function get_list() {
        $this->top_num ? $sql = "SELECT TOP " . $this->top_num : $sql = "SELECT ";
        $sql .= "
             tp.tp_sn,
                   tp.tp_u_sn,
                   tp.tp_title,
                   tp.tp_content,
                   tp.tp_delete,
                   tp.tp_date
            FROM   templates tp
            WHERE  tp.tp_delete = 0
            ";
        $this->tp_sn ? $sql.=$this->tp_sn : false;
        $this->order_by ? $sql.=$this->order_by : false;
        $query = $this->DEST->query($sql);
        //print_r($this->DEST->queries);
        if ($this->top_num == 1) {
            if ($query->num_rows() > 0) {
                $row = $query->row();
                return $row;
            } else {
                return FALSE;
            }
        } else {
            return $query->result();
        }
    }

    public function detail($tp_sn) {
        $this->init();
        $this->top_num=1;
        $this->tp_sn = 'AND  tp.tp_sn =  ' . $this->DEST->escape($tp_sn);
        return $this->get_list();
    }

    public function add($tp_u_sn, $tp_title, $tp_content) {
        $sql = "
                INSERT INTO templates
                ( tp_u_sn,tp_title,tp_content,tp_delete,tp_date
                )
                VALUES
                (   ?,N?,N?,0,GETDATE()
                )          
            ";
        $query = $this->DEST->query($sql, array($tp_u_sn, $tp_title, $tp_content));
        $this->insert_id = $this->DEST->last_id('templates');
        return $query;
    }

    public function update($tp_sn, $tp_u_sn, $tp_title, $tp_content) {
        $sql = "
            UPDATE templates
            SET    tp_u_sn        = ?,
                   tp_title       = N?,
                   tp_content     = N?,
                   tp_date        = GETDATE()
            WHERE  tp_sn          = ?    
            ";
        $query = $this->DEST->query($sql, array($tp_u_sn, $tp_title, $tp_content, $tp_sn));
        return $query;
    }

    public function delete($tp_sn) {
        $sql = "
            UPDATE templates
            SET    
                   tp_delete     = 1,
                   tp_date        = GETDATE()
            WHERE  tp_sn          = ?    
            ";
        $query = $this->DEST->query($sql, array($tp_sn));
        return $query;
    }

}
