<?php
class ModelExtensionModuleNetreviews extends Model {


	public function __construct($registry) {
        parent::__construct($registry);
        
        $this->DB_PREFIX = (defined('DB_PREFIX'))? DB_PREFIX : '';
    }
    
    public function isConfigured($store_id, $id_lang) {

    	$secret_key = null;
    	$id_website = null;
    	$platform_code = null;

        $result = $this->db->query("SELECT value FROM netreviews_configuration WHERE id_shop ='".$store_id."' AND id_lang = '".$id_lang."' AND name='SECRET_KEY'");
        $secret_key = isset($result->row['value']) ? $result->row['value'] : null;
        $result = $this->db->query("SELECT value FROM netreviews_configuration WHERE id_shop ='".$store_id."' AND id_lang = '".$id_lang."' AND name='ID_WEBSITE'");
        $id_website = isset($result->row['value']) ? $result->row['value'] : null;
        $result = $this->db->query("SELECT value FROM netreviews_configuration WHERE id_shop ='".$store_id."' AND id_lang = '".$id_lang."' AND name='PLATFORM_CODE'");
        $platform_code = isset($result->row['value']) ? $result->row['value'] : null;

        if($secret_key != null && $id_website != null && $platform_code != null){
        	return true;
        } else {
        	return false;
        }


    }

    public function get_language_code($lang_id){

    	$result = $this->db->query("SELECT code FROM ".$this->DB_PREFIX."language WHERE language_id = '".$lang_id."'");
    	return $result->row['code'];
    }

    public function get_attribute($store_id, $id_lang, $property_name){

    	$result = $this->db->query("SELECT value FROM netreviews_configuration WHERE id_shop ='".$store_id."' AND id_lang = '".$id_lang."' AND name='".$property_name."'");

    	return isset($result->row['value']) ? $result->row['value'] : null;
    }


    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 AV_encode_base64($sData) {
    
        $sBase64 = base64_encode($sData);
        return strtr($sBase64, '+/', '-_');
    }

    
    public function AV_decode_base64($sData) {

        $sData = urldecode($sData);
        $sBase64 = strtr($sData, '-_', '+/');
        return base64_decode($sBase64);
    }


    public function isActiveModule ($post_data, $idWebsite) {

        $results = $this->db->query("SELECT Count(*) as Count FROM netreviews_configuration "
            . "AS net_conf WHERE net_conf.name= '"."ID_WEBSITE"."' AND net_conf.value='".$idWebsite."'");

        // If we have one or more stores configured we're good to go
        if ($results->row['Count'] >= 1) {

            return array(
                'debug' => 'Module Installé et activé',
                'return' => 1,//Module OK
                'query' => (isset($post_data['query']))? $post_data['query'] : ' pas de query',
            );
        } else{
            return array(
                'debug' => 'Module Désactivé',
                'return' => 2, //Module désactivé
                'query' => 'isActive'
            );
        }
    }

    public function getConfig($name,$store_id, $lang_id) {
        
        if ($results = $this->db->query("SELECT value FROM netreviews_configuration "
            . "AS net_conf WHERE net_conf.name= '".$name."' AND net_conf.id_shop='".$store_id."' AND net_conf.id_lang='".$lang_id."'")) {
            if ($results->num_rows != 0) {
                return $results->row['value'];
            }
        }
        return NULL;
    }




    public function getListStores($idWebsite){

        $stores = array();
        $single_store = array();

        $results = $this->db->query("SELECT net_conf.id_shop, net_conf.id_lang FROM netreviews_configuration "
            . "AS net_conf WHERE net_conf.name= '"."ID_WEBSITE"."' AND net_conf.value='".$idWebsite."'");

        // Compile a list of stores with idWebsite then check the configuration of each store 
        foreach($results->rows as $store){

            $single_store['id_shop'] = $store['id_shop'];
            $single_store['id_lang'] = $store['id_lang'];
            $single_store['idWebsite'] = $idWebsite;
            $stores[] = $single_store;
            $single_store = array();
        }
        // Add the secret keys to each store
        foreach($stores as $i => $store){

            $secret_key = $this->getConfig('SECRET_KEY',$store['id_shop'],$store['id_lang']);
            $stores[$i]['secret_key'] = $secret_key;
        }
        return $stores;
    }


    // For each store that is configured check that the idWebsite and Secret Key match
    public function checkData ($message,$post_query) {

        $stores = array();
        if (!isset($message['idWebsite']) or empty($message['idWebsite'])){ 
            $reponse['debug'] = "Identifiants clients non renseignés sur le module";
            $reponse['message'] = "Identifiants clients non renseignés sur le module";
            $reponse['return'] = 3; //A definir
            $reponse['query'] = 'check_data';
            return $reponse;
        }
       
        // Return the list of stores configured with this idWebsite
        $stores = $this->getListStores($message['idWebsite']);

        if(empty($stores)){

            $reponse['debug'] = "Identifiants clients non renseignés sur le module";
            $reponse['message'] = "Identifiants clients non renseignés sur le module";
            $reponse['return'] = 3; //A definir
            $reponse['query'] = 'check_data';
            return $reponse;
        }

        foreach($stores as $store){

            if(!isset($store['secret_key']) or empty($store['secret_key'])){
                $reponse['debug'] = "Identifiants clients non renseignés sur le module";
                $reponse['message'] = "Identifiants clients non renseignés sur le module";
                $reponse['return'] = 3; //A definir
                $reponse['query'] = 'check_data';
                return $reponse;
            }

            $SHA1 = sha1($post_query.$store['idWebsite'].$store['secret_key']);

            if($message['sign'] != $SHA1){
                $reponse['message'] = "La signature est incorrecte";        
                $reponse['debug'] = "La signature est incorrecte";                  
                $reponse['return'] = 5; //A definir
                $reponse['query'] = 'check_data';   
                return $reponse;
            }
        }

        $reponse['message'] = "Identifiants Client Ok"; 
        $reponse['debug'] = "Identifiants Client Ok";   
        $reponse['return'] = 1; //A definir
        $reponse['query'] = 'check_data';   
        return $reponse;
     
    }

    public function getModuleAndSiteConfiguration($message) {
    

        $reponse['message'] = $this->_getModuleAndSiteInfos($message['idWebsite']);
        $reponse['query'] = $message['query'];
        $reponse['return'] = (empty($reponse['message']))? 2 : 1; // 2:error, 1:success.
    
        return $reponse;
    }

    public function _getModuleAndSiteInfos($idWebsite){

            $stores = $this->getListStores($idWebsite);
            $version_module = "";
            // All stores configured with this idWebsite will have the same module version
            
            $version_module = $this->getConfig('MODVERSION', $stores[0]['id_shop'], $stores[0]['id_lang']);
            
            
            $temp = array(
            'Version_PS' => VERSION,
            'Version_Module' => $version_module,       
            'idWebsite' => $idWebsite,
            'Websites' => "",
            'Id_Website_encours' => ""
            );

            // our configuration
            $champ = array('Delay'=>'DELAY',
                'Statut_choisi'=>'ORDERSTATESCHOOSEN',
                'Initialisation_du_Processus'=>'PROCESSINIT',
                'Recuperation_Avis_Produits'=>'GETPRODREVIEWS',
                'Affiche_Avis_Produits'=>'DISPLAYPRODREVIEWS',
                'Affichage_Widget_Flottant'=>'SCRIPTFLOAT_ALLOWED',
                'Script_Widget_Flottant'=>'SCRIPTFLOAT',
                'Affichage_Widget_Fixe'=>'SCRIPTFIXE_ALLOWED',
                'Position_Widget_Fixe'=>'SCRIPTFIXE_POSITION',
                'Script_Widget_Fixe'=>'SCRIPTFIXE',
                'Emails_Interdits'=>'FORBIDDEN_EMAIL');
        
            //**** Important **** 
            // All storefronts under this idWebsite will have the same configuration settings so just use the first storefront - storefront = (website + language)
            foreach($champ as $key=>$champsname) {
                $var = $this->getConfig($champsname,$stores[0]['id_shop'], $stores[0]['id_lang']);
                $var = ($var == 'NULL') ? '' : $var; 
                // FIX pour NULL Variable, DATA are saved default with NULL Var
                // fix for SCRIPTFLOAT && SCRIPTFIXE
                if($champsname == 'SCRIPTFLOAT' || $champsname == 'SCRIPTFIXE') 
                    $temp[$key] = $this->AV_decode_base64($var);
                else   
                    $temp[$key] = $var;
            }
            //**** Important ********
            // Get the admin language, then retrieve the list of order states using the admin_language
            // Opencart 3 order states work on the level of language. Languages have the same number of order states and the order_states_id stay the same the only difference is the name depending on the language
            $admin_language = $this->get_admin_language();
            $temp['Liste_des_statuts']= $this->getOrderStatus($admin_language);
            $temp['Date_Recuperation_Config']= date('Y-m-d H:i:s');

            // Create a list of all Stores which have been configured, sort by website URL
            $map_configuration = array();
            $map_configuration['websites'] = array();
            foreach($stores as $store){

                if($store['id_shop'] == 0){

                    $store['name'] = "Default";
                    $store['url'] = HTTPS_SERVER;

                }else{

                    $results = $this->db->query("SELECT name, url FROM ".$this->DB_PREFIX."store WHERE store_id = '".$store['id_shop']."'");
                    $store['name'] = $results->row['name'];
                    $store['url'] = $results->row['url'];
                }

                $results = $this->db->query("SELECT code FROM ".$this->DB_PREFIX."language WHERE language_id = '".$store['id_lang']."'");
                $store['lang_code'] = $results->row['code'];
                $store['Liste_des_statuts'] = $this->getOrderStatus($store['id_lang']);
                $store['Version_Module'] = $this->getConfig('MODVERSION', $store['id_shop'], $store['id_lang']);
                $map_configuration['websites'][$store['name']]['stores'][] = $store;
            }

            $temp['Map_Configuration'] = $map_configuration;
            return $temp;
    }

    // Order states are at the level of language
    // Find the default language of the admin and return all order states for the default admin language
    // All the installed languages will have the same list of order states in terms of order_status_id with
    // the only difference being the name of the order state can be different depending on the language
    public function getOrderStatus($language_id){
        

        $results = $this->db->query("SELECT os.order_status_id AS orders_status_id,os.name AS orders_status_name
            FROM ".$this->DB_PREFIX."order_status AS os
            WHERE os.language_id = '".$language_id."'
            ORDER BY orders_status_id ASC");
        
        $resultat = array();
        if (!empty($results)) {
            foreach ($results->rows as $row) {
                $resultat[$row['orders_status_id']] = $row['orders_status_name'];
            }
            return $resultat;
        }
        return null;
    }

    // Get order states of the default admin language
    public function get_admin_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 language_id FROM ".$this->DB_PREFIX."language WHERE code = '".$code."'");
        return $result->row['language_id'];
    }

    public function updateConfig($name,$value,$store_id, $lang_id) {

        $result = $this->db->query("SELECT value FROM netreviews_configuration WHERE name = '".$name."' AND id_shop ='".$store_id."' AND id_lang='".$lang_id."'");

        if ($result->num_rows == 0) {

            $this->db->query("INSERT INTO netreviews_configuration (name, value, id_shop, id_lang) VALUES ('".$name."', '".$value."', '".$store_id."', '".$lang_id."')");

        } else {

            $this->db->query("UPDATE netreviews_configuration SET value = '".$value."' WHERE name = '".$name."' AND id_shop ='".$store_id."' AND id_lang='".$lang_id."'");
        }
   
    }

    public function setModuleConfiguration($message) {

        $idWebsite = $message['idWebsite'];

        $stores = $this->getListStores($idWebsite);


        //Implode si plusieurs éléments donc is_array
        $ORDERSTATESCHOOSEN = (is_array($message['id_order_status_choosen'])) ? implode(';',$message['id_order_status_choosen']) : $message['id_order_status_choosen'];
        //Implode si plusieurs éléments donc is_array
        $FORBIDDENEMAIL = (is_array($message['forbidden_mail_extension'])) ? implode(';',$message['forbidden_mail_extension']) : $message['forbidden_mail_extension'];
        //Encode le donnee avant le sauvegarde dans le db.
        $data_fixe = $this->AV_encode_base64(str_replace(array("\r\n", "\n"), '', stripslashes(str_replace('\"','"',$message['script_fixe_widget']))));
        $data_float = $this->AV_encode_base64(str_replace(array("\r\n", "\n"), '', stripslashes(str_replace('\"','"',$message['script_float_widget']))));

        foreach($stores as $store){

            // either onorder or onorderstatuschange
            $this->updateConfig('PROCESSINIT',$message['init_reviews_process'],$store['id_shop'], $store['id_lang']);
            $this->updateConfig('ORDERSTATESCHOOSEN', $ORDERSTATESCHOOSEN,$store['id_shop'], $store['id_lang']);
            $this->updateConfig('DELAY', $message['delay'], $store['id_shop'], $store['id_lang']);
            $this->updateConfig('GETPRODREVIEWS',$message['get_product_reviews'], $store['id_shop'], $store['id_lang']);
            $this->updateConfig('DISPLAYPRODREVIEWS',$message['display_product_reviews'],$store['id_shop'], $store['id_lang']);
            $this->updateConfig('SCRIPTFIXE_ALLOWED',$message['display_fixe_widget'],$store['id_shop'], $store['id_lang']);
            $this->updateConfig('SCRIPTFIXE_POSITION',$message['position_fixe_widget'],$store['id_shop'], $store['id_lang']);
            $this->updateConfig('SCRIPTFLOAT_ALLOWED',$message['display_float_widget'],$store['id_shop'], $store['id_lang']);
            $this->updateConfig('URLCERTIFICAT',$message['url_certificat'],$store['id_shop'], $store['id_lang']);
            $this->updateConfig('FORBIDDEN_EMAIL', $FORBIDDENEMAIL,$store['id_shop'], $store['id_lang']);
            $this->updateConfig('SCRIPTFIXE',$data_fixe,$store['id_shop'], $store['id_lang']);
            $this->updateConfig('SCRIPTFLOAT',$data_float,$store['id_shop'], $store['id_lang']);
        }
        
        $reponse['message'] = $this->_getModuleAndSiteInfos($idWebsite);
        $reponse['debug'] = "La configuration du site a été mise Ã  jour";
        $reponse['return'] = 1; //A definir 
        $reponse['query'] = $message['query'];

        return $reponse;
    }

    public function get_truncatetables() {

        if ($this->db->query("TRUNCATE TABLE netreviews_products_reviews") == true) {
            return 1; // ok
        }
        else {
            return 'Erreur tables non vidées.'; // erreur
        }
    }

    public function truncateTables($post_query) { 
    
        $reponse['return'] = 1;
        $reponse['debug'][]  = "Tables vidées";
        $reponse['message'] = "Tables vidées";
        $reponse['debug'][] = $this->get_truncatetables();
        $reponse['query'] = $post_query; // get request post
        return $reponse;
    }

    public function getDataOrders(array $config, $store_id, $lang_id) {

        if (isset($config['from']) && isset($config['to'])) {
            $from = $config['from'];
            $to = $config['to'];
        }
        if (isset($config['flag'])) {
            $flag = 0;
        }
        if (isset($config['flag'])) {
            $status = $config['status'];
        }
        if ($config['includeProducts'] == 'yes') {
            $includeProducts = TRUE;
        }
        if (isset($config['status'])) {
            $where = $config['status'];
        }


        $q2 = (isset($includeProducts))? '' : ' GROUP BY refcommande';
        $where = (isset($where) AND ($where!=''))? ' AND os.order_status_id IN ('.$where.')' : '';
        $whereFlag = ($flag == 0)? ' AND neto.flag_get = '.$flag : '';
        $whereDate = (isset($from) && isset($to))? ' AND (o.date_modified >= '.$from.' AND o.date_modified <= '.$to.')' : '';

        $results = $this->db->query("SELECT neto.id_order AS refcommande,DATE_FORMAT(o.date_modified,'%d/%m/%Y %H:%i') AS date_modified,o.total AS amount_order, UNIX_TIMESTAMP(o.date_added) AS timestamp,
            os.name AS status_order,DATE_FORMAT(o.date_added,'%d/%m/%Y %H:%i') AS datecommande,
            op.product_id AS product_id,o.customer_id AS id_customer,o.email AS email,o.lastname AS nom,o.firstname AS prenom,    
            op.name AS product_name,'url','url_image','delaiavis' FROM netreviews_orders AS neto
            LEFT JOIN `".$this->DB_PREFIX."order` AS o ON neto.id_order = o.order_id
            LEFT JOIN ".$this->DB_PREFIX."order_status AS os ON o.order_status_id = os.order_status_id
            LEFT JOIN ".$this->DB_PREFIX."order_product AS op ON op.order_id = o.order_id
            WHERE neto.id_shop='".$store_id."' "."AND neto.id_lang_order='".$lang_id."' "."AND os.language_id = neto.id_lang_order ".$where.$whereDate.$whereFlag.$q2."");

     
        $resultat = array();
        if (!empty($results)) {
            foreach ($results->rows as $row) {
                $resultat[] = array(
                    0 => $row['refcommande'],
                    'refcommande' => $row['refcommande'],
                    1 => $row['amount_order'],
                    'amount_order' => (round($row['amount_order'],2) * 100),
                    2 => $row['date_modified'],
                    'date_modified' => $row['date_modified'],
                    3 => $row['timestamp'],
                    'timestamp' => $row['timestamp'],
                    4 => $row['status_order'],
                    'status_order' => $row['status_order'],
                    5 => $row['datecommande'],
                    'datecommande' => $row['datecommande'],
                    6 => (isset($includeProducts))? $row['product_id'] : '',
                    'product_id' => (isset($includeProducts))? $row['product_id'] : '',
                    7 => $row['id_customer'],
                    'id_customer' => $row['id_customer'],
                    8 => $row['email'],
                    'email' => $row['email'],
                    9 => $row['nom'],
                    'nom' => $row['nom'],
                    10 => $row['prenom'],
                    'prenom' => $row['prenom'],
                    11 => (isset($includeProducts))? $row['product_name'] : '',
                    'product_name' => (isset($includeProducts))? $row['product_name'] : '',
                    12 => (isset($includeProducts))? $this->getUrl_product($row['product_id'],$store_id) : '',
                    'url' => (isset($includeProducts))? $this->getUrl_product($row['product_id'],$store_id) : '',
                    13 => (isset($includeProducts))? $this->getUrl_image($row['product_id'],$store_id) : '',
                    'url_image' => (isset($includeProducts))? $this->getUrl_image($row['product_id'],$store_id) : '',
                    14 => $row['delaiavis'],
                    'delaiavis' => $row['delaiavis'],
                    'id_shop' => $store_id,
                    'id_lang' => $lang_id
                );
            }
            return $resultat;
        }
        return null;
    }

    // *** Everything to do with Recuperating orders
    public function getOrders($message,$post_query) {

        $data = array();

        $idWebsite = $message['idWebsite'];

        $stores = $this->getListStores($idWebsite);

        // All Storefronts with this IDWebsite will have the same configuration settings, use the first storefront incase there is only one Storefront 
        $allowedProducts = $this->getConfig('GETPRODREVIEWS', $stores[0]['id_shop'], $stores[0]['id_lang']);
        $processChoosen = $this->getConfig('PROCESSINIT', $stores[0]['id_shop'], $stores[0]['id_lang']);
        $statusChoosen = implode(",",explode(";",$this->getConfig('ORDERSTATESCHOOSEN', $stores[0]['id_shop'], $stores[0]['id_lang'])));
        $forbiddenMailExtensions = explode('%3B',$this->getConfig('FORBIDDEN_EMAIL', $stores[0]['id_shop'], $stores[0]['id_lang']));
        $delay = $this->getConfig('DELAY', $stores[0]['id_shop'], $stores[0]['id_lang']);

        //**** Important ********
        // Get the admin language, then retrieve the list of order states using the admin_language
        // Opencart 3 order states work on the level of language. Languages have the same number of order states and the order_states_id stay the same the only difference is the name depending on the language
        $admin_language_id = $this->get_admin_language();

        if ($processChoosen == 'onorderstatuschange')
            $list_status = $this->get_status($statusChoosen,$admin_language_id);


        $config = array(
            'includeProducts' => $allowedProducts,
            'status' => $statusChoosen,
            'flag' => true );
    
        if ($message['force'] == 1) {
            if ($message['date_deb'] && $message['date_fin']) {
                $from = date("Y-m-d H:i:s",strtotime($message['date_deb']));
                $to = date("Y-m-d H:i:s",strtotime($message['date_fin']));
                foreach($stores as $store){
                $single_store_data = $this->getDataOrders(array_merge($config,array('from'=>$from,'to'=>$to)), $store['id_shop'], $store['id_lang']);
                $data = array_merge($single_store_data, $data);
                }
                $reponse['debug']['mode'] = "[forcé] ".count($data)." commandes récupérées en force du ".$from." au ".$to;
            }
            else { // en cas d'erreur 
                $reponse['debug'][] = "Aucune période renseignée pour la récupération des commandes en mode forcé";
                return $reponse;
            }
        }
        elseif ($processChoosen == 'onorder') {
            foreach($stores as $store){
                // Get all the orders for this Storefront = Store + Lang
                $single_store_data = $this->getDataOrders($config, $store['id_shop'], $store['id_lang']);
                // Merge to get all the orders for the Storefronts under this IDWebsite
                $data = array_merge($single_store_data, $data);
            }

            $reponse['debug']['mode'] = "[onorder] ".count($data)." commandes récupérées";
        }
        elseif ($processChoosen == 'onorderstatuschange') {         
            if (count($statusChoosen) >= 1) {
                foreach($stores as $store){
                    $single_store_data = $this->getDataOrders($config, $store['id_shop'], $store['id_lang']);
                    $data = array_merge($single_store_data, $data);
                }
                $reponse['debug']['mode'] = "[onorderstatuschange] ".count($data)." commandes récupérées avec statut ".$list_status.".";
            }
            else { // en cas d'erreur
                $reponse['debug'][] = "Aucun statut n'a été renseigné pour la récupération des commandes en fonction de leur statut";
                $reponse['return'] = 2;
                return $reponse;
            }
        }
        else { // en cas d'erreur
            $reponse['debug'][] = "Aucun évènement onorder ou onorderstatuschange n'a été renseigné pour la récupération des commandes";
            $reponse['return'] = 3;
            return $reponse;
        }
    
        $ordersIds = $tmp = array();
        foreach ($data as $order) {
            $customerEmailExtension = explode('@', $order['email']);
            if (!in_array($customerEmailExtension[1],$forbiddenMailExtensions)) {
                // save same order into once.
                $id = (int)$order['refcommande'];
                $tmp2 = (isset($tmp[$id]))? $tmp[$id] : array();
                $tmp[$id] = array_merge($tmp2,array(
                    'id_order' => $order['refcommande'],
                    'date_order' => $order['timestamp'], //date timestamp de la table orders
                    'amount_order' => $order['amount_order'],
                    'date_order_formatted' => $order['datecommande'], //date de la table orders formatté            
                    //'date_av_getted_order' => $order['date_av_getted_order'], //date de la table order_history de récup par AV
                    'date_last_status_change' => $order['date_modified'],
                    //'is_flag' => $order['is_flag'], //si la commande est déjà à flaggué       
                    'state_order' => $order['status_order'], // we use the status and not the state.
                    'id_customer' => $order['id_customer'],
                    'firstname_customer' => $order['prenom'],
                    'lastname_customer' => $order['nom'],
                    'email_customer' =>  $order['email'],
                ));// add order products as array.
                if (strtolower($allowedProducts) === 'no') {
                    $tmp[$id]['products'][] = array();
                }
                else {
                    $tmp[$id]['products'][] = array(
                        'id_product' => $order['product_id'],
                        'name_product' => $order['product_name'],
                        'url' => $order['url'],
                        'url_image' => $order['url_image']
                    );
                }
                
                $ordersIds[] = $id;   
            }
            else {
                $reponse['message']['Emails_Interdits'][] = 'Commande n°'.$order['increment_id'].' Email:'.$order['email'];     
            }
        }
        
        // update Flag db;
        $noFlag = $message['no_flag'];  
        if(isset($noFlag) && $noFlag == 0 && !empty($ordersIds)) {
            // OrderIDs are unique
            $this->updateFlag($ordersIds);
        }
    
        // return value
        $reponse['return'] = 1; 
        $reponse['query'] = $post_query; // get request post
        $reponse['message']['nb_orders'] = count($tmp);
        $reponse['message']['delay'] = $delay;  
        $reponse['message']['nb_orders_bloques'] = 0;
        $reponse['message']['list_orders'] = $tmp;
        $reponse['debug']['force'] = $message['force'];
        $reponse['debug']['produit'] = $allowedProducts;
        $reponse['debug']['no_flag'] = $message['no_flag'];
        return $reponse;
    }


    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 = HTTPS_SERVER;
                    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 getUrl_product($product_id,$store_id) {

        if ($store_id == 0) {
            $url_config = HTTPS_SERVER;
            return $url_config.'index.php?route=product/product&product_id='.$product_id;
        }
        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'].'index.php?route=product/product&product_id='.$product_id;
                    }
                }
            }
        }
        return "";
    }



    public function updateFlag(array $ids) {
    
        $i = 0;
        $save = $ids[0];
        $tab[$i] = "'".$ids[0]."'";
        ++$i;
        foreach ($ids as $id) {
            
            if ($id != $save) {
                $save = $id;
                $tab[$i] = "'".$id."'";
                ++$i;
            }
        }
        $where = implode(',',$tab);
        $time = time();
        $this->db->query("UPDATE netreviews_orders SET flag_get = '1',horodate_get = '".$time."' WHERE id_order IN (".$where.")");
    }

    public function get_status($statusChoosen,$language_id) {
    
        $results = $this->db->query("SELECT name FROM ".$this->DB_PREFIX."order_status "
            . "WHERE order_status_id IN (".$statusChoosen.") AND language_id = '".$language_id."'");
   
        foreach ($results->rows as $row) {
            $tab[] = $row['name'];
        }
        $resultat = implode(",",$tab);
        return $resultat;
    }


}
?>