<?php
class ModelExtensionModuleNetreviews extends Model {
    
    public function __construct($registry) {
        parent::__construct($registry);
        
        $this->DB_PREFIX = (defined('DB_PREFIX'))? DB_PREFIX : '';
    }

     public function get_default_lang_store($store_id) {
        $config_lang = $this->db->query("SELECT value FROM ".$this->DB_PREFIX."setting "
                . "WHERE ".$this->DB_PREFIX."setting.key = 'config_language' and ".$this->DB_PREFIX."setting.store_id ='".$store_id."'");
        $id_lang = $this->db->query($sql = "SELECT language_id FROM ".$this->DB_PREFIX."language "
                . "WHERE ".$this->DB_PREFIX."language.code = '".$config_lang->row['value']."'");
        return $id_lang->row['language_id'];
    }

    public function get_query_date($delay) {
        
        $len = strlen($delay);
        $len = $len - 1;
    
        if ($delay[$len] == 'w'){
            $value = stristr($delay,'w',true);
            $query_date = "DATE_SUB(now(), INTERVAL ".$value." WEEK)";
        }
        elseif ($delay[$len] == 'm'){
            $value = stristr($delay,'m',true);
            $query_date = "DATE_SUB(now(), INTERVAL ".$value." MONTH)";
        }
        else {
            $query_date = "DATE_SUB(now(), INTERVAL 1 YEAR)";
        }
        return $query_date;
    }

    public function get_result_export($date,$status,$store_id, $id_lang) {
        
        $condition = ' AND o.store_id = '.$store_id;
        $query = "SELECT o.order_id as order_id,"."o.store_id, o.language_id,o.email,o.firstname,o.lastname,o.date_modified AS order_date,o.total AS amount_order,"
                . "os.name AS order_status,op.product_id AS product_id,op.name AS product_name "
                . "FROM `".$this->DB_PREFIX."order` AS o "
                . "LEFT JOIN ".$this->DB_PREFIX."order_status AS os ON os.order_status_id=o.order_status_id "
                . "LEFT JOIN ".$this->DB_PREFIX."order_product AS op ON op.order_id=o.order_id "     
                . "WHERE os.name IN (".$status.")".$condition." AND o.date_added BETWEEN {$date} AND DATE_ADD(curdate(),INTERVAL 1 DAY) AND o.language_id = os.language_id AND o.language_id = '".$id_lang."'";

        $results = $this->db->query($query);
        return $results->rows;
    }

    public function get_list_status($language_id) {
        
        $resultat = array();
        $list_status = $this->db->query("SELECT name FROM ".$this->DB_PREFIX."order_status "
                . "WHERE language_id = '".$language_id."'");
        foreach ($list_status->rows as $status) {
            $resultat[] = $status;
        }
        return $resultat;
    }

    public function get_language_id($lang_code) {
             
        $id_lang = $this->db->query($sql = "SELECT language_id FROM ".$this->DB_PREFIX."language "
                . "WHERE ".$this->DB_PREFIX."language.code = '".$lang_code."'");
        return $id_lang->row['language_id'];
    }

    public function get_count_flag($type,$store_id, $lang_id) {
        
        $results = $this->db->query("SELECT COUNT(flag_get) AS flag FROM netreviews_orders WHERE flag_get = '".$type."' AND id_shop ='".$store_id."' AND id_lang_order = '".$lang_id."'");
        return $results->row['flag'];
    }

    public function get_config_languages($store_id){

        $result = $this->db->query("SELECT DISTINCT id_lang FROM netreviews_configuration WHERE id_shop = '".$store_id."' AND name = 'SECRET_KEY'");
        return $result->rows;
    }
    
    public function validate() {
        
        if (!$this->user->hasPermission('modify', 'extension/module/netreviews')) {
                $this->error['warning'] = $this->language->get('error_permission');
        }
        	
        if (isset($this->request->post['netreviews_module'])) {
                foreach ($this->request->post['netreviews_module'] as $key => $value) {
        	if (!$value['image_width'] || !$value['image_height']) {
                        $this->error['image'][$key] = $this->language->get('error_image');
        	}
                }
        }
        	
        if (!$this->error) {
                return true;
        } else {
                return false;
        }	
    }

    public function removeLangSiteSettings($store_id, $id_lang){

        $this->db->query("DELETE FROM netreviews_configuration WHERE id_shop = '".$store_id."' and id_lang='".$id_lang."'");
    }

    public function getPropertyLangSite($name,$store_id, $id_lang) {
        
        $id = (empty($store_id))? 0:$store_id;
        if ($results = $this->db->query("SELECT value FROM netreviews_configuration "
            . "AS net_conf WHERE net_conf.name= '".$name."' AND net_conf.id_shop='".$id."' AND net_conf.id_lang='".$id_lang."'")) {
            if (!isset($results->row['value']) || $results->row['value'] == '') {
                return NULL;
            }
            return $results->row['value'];
        }
        return NULL;
    }
    
    public function insertPropertyLangSite($name, $value, $id_shop, $id_lang){
        $this->db->query("INSERT INTO netreviews_configuration (name,value,id_shop, id_lang) VALUES ('".$name."','".$value."','".$id_shop."','".$id_lang."')");
    }

    public function deletePropertyLangSite($store_id, $value, $id_lang){

        $this->db->query("DELETE FROM netreviews_configuration WHERE id_shop = '".$store_id."' and id_lang='".$id_lang."'"." and name='".$value."'");
    }

    public function getPropertySite($name,$store_id) {
        
        $id = (empty($store_id))? 0:$store_id;
        if ($results = $this->db->query("SELECT value FROM netreviews_configuration "
            . "AS net_conf WHERE net_conf.name= '".$name."' AND net_conf.id_shop='".$id."'")) {
            if (!isset($results->row['value']) || $results->row['value'] == '') {
                return NULL;
            }
            return $results->row['value'];
        }
        return NULL;
    }

    public function removePropertySite($name,$store_id) {
        
        $this->db->query("DELETE FROM netreviews_configuration WHERE id_shop = '".$store_id."' and name='".$name."'");
    }

    public function insertPropertySite($name, $value, $id_shop){
        $this->db->query("INSERT INTO netreviews_configuration (name,value,id_shop) VALUES ('".$name."','".$value."','".$id_shop."')");
    }

    public function get_url_config($store_id) {
        
        if (empty($store_id) || $store_id == 0) {
            return HTTP_CATALOG;
        }
        else {
            $result = $this->db->query("SELECT sett.value FROM ".$this->DB_PREFIX."setting AS sett WHERE sett.key = 'config_url' AND store_id='".$store_id."'");
            return $result->row['value'];
        }
    }
    
    public function get_language() {
        
        $lang_result = $this->db->query("SELECT sett.value FROM ".$this->DB_PREFIX."setting AS sett WHERE sett.key = 'config_admin_language'");
        $code = $lang_result->row['value'];
        
        $result = $this->db->query("SELECT directory FROM ".$this->DB_PREFIX."language WHERE code = '".$code."'");
        return $result->row['directory'];
    }
    
    public function get_module_state() {
        
        $results = $this->db->query("SELECT code FROM ".$this->DB_PREFIX."extension WHERE type = 'module'");
        foreach ($results->rows as $result) {
            if ($result['code'] == 'netreviews')
                return true;
        }
        return false;
    }
    
    public function install_netreviews () {
        $this->model_extension_module_netreviews->create_tables();
    }
    
    public function uninstall_netreviews () {
        $this->model_extension_module_netreviews->drop_tables();
        //$this->model_extension_module_netreviews->delete_pages();
    }
    
    // public function delete_pages() {
        
    //     $type[0] = 'api';
    //     $type[1] = 'ajax';
    //     foreach ($type as $page) {
    //         $this->db->query("DELETE FROM ".$this->DB_PREFIX."layout_route WHERE route = 'netreviews/".$page."'");
    //     }
    // }
    
    // public function check_index($index) {
        
    //     $flag = 0;
    //     $results = $this->db->query("SELECT layout_route_id FROM ".$this->DB_PREFIX."layout_route");
    //     foreach ($results->rows as $id) {
    //         if ($index == $id['layout_route_id'])
    //             $flag = 1;
    //     }
    //     if ($flag == 0)
    //         return true;
    //     else
    //         return false;
    // }
    
    // public function create_pages($store_id,$store_url) {
        
    //     $type[0] = 'api';
    //     $type[1] = 'ajax';
    //     $layout_id = 12;
    //     $index = 1;
    //     while ($this->check_index($index) == false)
    //         ++$index;
    //     foreach ($type as $page) {
    //         $result = $this->db->query("SELECT route FROM ".$this->DB_PREFIX."layout_route WHERE route='netreviews/".$page."' AND store_id = '".$store_id."'");
    //         if ($result->num_rows == 0) {
    //             $this->db->query("INSERT INTO ".$this->DB_PREFIX."layout_route (layout_route_id, layout_id, store_id, route) VALUES
    //             (".$index.", ".$layout_id.", ".$store_id.", 'netreviews/".$page."')");
    //         }
    //         $url = $store_url.'index.php?route=netreviews/'.$page;
    //         $this->db->query("UPDATE netreviews_configuration SET value = '".$url."' WHERE name = 'URL_".strtoupper($page)."' AND id_shop = '".$store_id."'");
    //         ++$layout_id;
    //         ++$index;
    //         while ($this->check_index($index) == false)
    //             ++$index;
    //     }
    // }
    
    public function create_tables() {
        
        $this->db->query("CREATE TABLE IF NOT EXISTS netreviews_configuration (
            `id` int(10) NOT NULL AUTO_INCREMENT,
            `name` varchar(25) NOT NULL,
            `value` text NOT NULL,
            `id_shop` int(10) NOT NULL,
            `id_lang` varchar(25) DEFAULT NULL,
            PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=21");
                      
        $this->db->query("CREATE TABLE IF NOT EXISTS netreviews_orders (
        `id_order` int(11) NOT NULL,
        `id_shop` int(2) DEFAULT NULL,
        `flag_get` int(2) DEFAULT NULL,
        `horodate_get` varchar(25) DEFAULT NULL,
        `id_order_state` int(5) DEFAULT NULL,
        `id_lang_order` int(5) DEFAULT NULL,
        `horodate_now` varchar(25) DEFAULT NULL,
        PRIMARY KEY (`id_order`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
    }
    
    // public function add_config_store($store_id,$index) {
        
    //     $resIfExist = $this->db->query("SELECT id_shop FROM netreviews_configuration WHERE id_shop='".$store_id."'");
    //     if ($resIfExist->num_rows == 0) {
    //         $result = $this->db->query("SELECT COUNT(*) AS nb FROM netreviews_configuration");
    //         if ($result->row['nb'] == $index) {
    //             $this->db->query("INSERT INTO netreviews_configuration (`id`, `name`, `value`, `id_shop`) VALUES
    //                 (".($index+1).", 'SECRET_KEY', NULL, ".$store_id."),
    //                 (".($index+2).", 'ID_WEBSITE', NULL, ".$store_id."),
    //                 (".($index+3).", 'IS_ACTIVE', NULL, ".$store_id."),
    //                 (".($index+4).", 'GETPRODREVIEWS', NULL, ".$store_id."),
    //                 (".($index+5).", 'PROCESSINIT', NULL, ".$store_id."),
    //                 (".($index+6).", 'ORDERSTATESCHOOSEN', NULL, ".$store_id."),
    //                 (".($index+7).", 'FORBIDDEN_EMAIL', NULL, ".$store_id."),
    //                 (".($index+8).", 'DELAY', NULL, ".$store_id."),
    //                 (".($index+9).", 'DISPLAYPRODREVIEWS', NULL, ".$store_id."),
    //                 (".($index+10).", 'SCRIPTFIXE_ALLOWED', NULL, ".$store_id."),
    //                 (".($index+11).", 'SCRIPTFIXE_POSITION', NULL, ".$store_id."),
    //                 (".($index+12).", 'SCRIPTFLOAT_ALLOWED', NULL, ".$store_id."),
    //                 (".($index+13).", 'URLCERTIFICAT', NULL, ".$store_id."),
    //                 (".($index+14).", 'SCRIPTFIXE', NULL, ".$store_id."),
    //                 (".($index+15).", 'SCRIPTFLOAT', NULL, ".$store_id."),
    //                 (".($index+16).", 'MODVERSION', NULL, ".$store_id."),
    //                 (".($index+17).", 'OCVERSION', '".VERSION."', ".$store_id."),
    //                 (".($index+18).", 'RANDOMNAME', 'NULL', ".$store_id."),
    //                 (".($index+19).", 'URL_API', NULL, ".$store_id."),
    //                 (".($index+20).", 'URL_AJAX', NULL, ".$store_id.")");
    //         }
    //     }
    // }
    
    public function drop_tables() {
        
        $tables = array('netreviews_configuration','netreviews_orders');
        
        $list_tables = $this->db->query("SHOW TABLES");
        foreach ($list_tables->rows as $table) {
            
            if (($table['Tables_in_'.DB_DATABASE.''] == $tables[0]) ||
                ($table['Tables_in_'.DB_DATABASE.''] == $tables[1])) {
                $this->db->query("DROP TABLE ".$table['Tables_in_'.DB_DATABASE.'']."");
            }
        }
    }
    
    public function update_field($id,$name,$value) {
        
        $this->db->query("UPDATE ".$this->DB_PREFIX."order SET ".$name." = '".$value."' WHERE order_id IN (".$id.")");
    }
    
    public function get_ids() {
        
        $results = $this->db->query("SELECT order_id FROM ".$this->DB_PREFIX."order");
        return $results->rows;
    }

    public function getUrl_image($product_id,$store_id) {

        
        if ($results = $this->db->query("SELECT image FROM ".$this->DB_PREFIX."product WHERE product_id = '".$product_id."'")) {
            if (!empty($results->row)) {
                if ($store_id == 0) {
                    $url_config = HTTP_CATALOG;
                    return $url_config.'image/'.$results->row['image'];
                }
                else {
                    $this->load->model('setting/store');
                    if ($res = $this->model_setting_store->getStores()) {
                        foreach ($res as $store) {
                            if ($store_id == $store['store_id']) {
                                return $store['url'].'image/'.$results->row['image'];
                            }
                        }
                    }
                }
            }
        }
        return '';
    }

    public function get_new_format_date($old_date) {
        
        list($date,$time) = explode(' ',$old_date);
        $date_tmp = explode('-', $date);
        $new_date = $date_tmp[2].'-'.$date_tmp[1].'-'.$date_tmp[0].' '.$time;
        return $new_date;
    }
}
?>