<?php
class Landingmain_Model extends CI_Model{

        private function _autofill ($arr)
        {
            $title = '';
            $title_en = '';
            if (array_key_exists('title', $arr)) {
                $title = trim($arr['title']);
            }
            if (array_key_exists('title_en', $arr)) {
                $title_en = trim($arr['title_en']);
            }
            if (($title !== "") && ($title_en !== "")) {
                return [
                    'zh' => $title,
                    'en' => $title_en,
                ];
            }
            if (($title === "") && ($title_en === "")) {
                return [
                    'zh' => $title,
                    'en' => $title_en,
                ];
            }
            if ($title === "") {
                return [
                    'zh' => $title_en,
                    'en' => $title_en,
                ];
            }
            return [
                'zh' => $title,
                'en' => $title,
            ];
        }

        function insert($arr)
        {
            $t = $this->_autofill($arr);
            $arr['title'] = $t['zh'];
            $arr['title_en'] = $t['en'];
            $this->db->insert('_landing_main', $arr);
            return $this->db->insert_id();

        }
        
        function update($id, $arr)
        {
            $t = $this->_autofill($arr);
            $arr['title'] = $t['zh'];
            $arr['title_en'] = $t['en'];
            $this->db->where('id', $id);
            $this->db->update('_landing_main', $arr);
        }
        
        function get($include_hidden = false)
        {       
            $this->db->select('*');
            $this->db->order_by("displayorder","asc");
            if (! $include_hidden) {
                $this->db->where('display_in_menu', 1);
            }
            $this->db->from('_landing_main');
            $query=$this->db->get();
            return $query->result();
        }
        
        function get_id($id)
        {
            $this->db->where('id', $id);
            $query = $this->db->get('_landing_main');
            return $query->result();
        }
        
        function get_lang($lang)
        {
            $this->db->where('lang', $lang);
            $query = $this->db->get('_landing_main');
            return $query->result();
        }

        function search_by_uri($controller)
        {
            $this->db->where('uri', $controller);
            $query = $this->db->get('_landing_main');
            return $query->row_array();
        }

        function delete($id)
        {
            $this->db->where('id', $id);
            $this->db->delete('_landing_main');
        }
        function update_rank($id, $rank)
        {
            $data = array(
                'displayorder' => $rank
            );

            $this->db->where('id', $id);
            $this->db->update('_landing_main', $data);
        }
        
}

?>