<?php

class ControllerExtensionModuleNetreviews extends Controller
{


    public function index()
    {


    $model_version = "3.0.0";
    //*****************************************************************************
    //***************** Load all the files ****************************************
    //*****************************************************************************

        $this->load->language('extension/module/netreviews');
        $this->document->setTitle($this->language->get('heading_title'));
        $this->load->model('setting/setting');
        $this->load->model('extension/module/netreviews');


        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->model_extension_module_netreviews->validate()) {
            $this->model_setting_setting->editSetting('netreviews', $this->request->post);		
            $this->session->data['success'] = $this->language->get('success');
		}

		if (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
		} else {
            $data['error_warning'] = '';
		}

        // Platforms for Tagjs - frontend display of reviews
        $platformTagjs = array(
                "au" => "www.au.verified-reviews.com",
                "fr" => "www.avis-verifies.com",
                "cl" => "www.cl.opiniones-verificadas.com",
                "br" => "www.opinioes-verificadas.com.br",
                "be" => "www.echte-beoordelingen.com",
                "de" => "www.echte-bewertungen.com",
                "pt" => "www.opinioes-verificadas.com",
                "es" => "www.opiniones-verificadas.com",
                "co" => "www.opiniones-verificadas.com.co",
                "mx" => "www.opiniones-verificadas.com.mx",
                "pe" => "www.opiniones-verificadas.pe",
                "pl" => "www.prawdziwe-opinie.com",
                "it" => "www.recensioni-verificate.com",
                "nz" => "www.verified-reviews.co.nz",
                "gb" => "www.verified-reviews.co.uk",
                "us" => "www.verified-reviews.com"
        );

        $data['platformTagjs'] = $platformTagjs;


        //************ LOAD CSS AND JAVASCRIPT **********************************************
        $this->document->setTitle($this->language->get('heading_title'));
        $url_config = $this->model_extension_module_netreviews->get_url_config('');
        $this->document->addStyle($url_config.'admin/view/stylesheet/stylesheet.css');
        $this->document->addStyle($url_config.'admin/view/stylesheet/netreviews.css');
        $this->document->addScript($url_config.'admin/view/javascript/netreviews.js');

        //************************************************************************************
        //************************ Load Language Variables ***********************************
        //************************************************************************************
        $data['heading_title'] = $this->language->get('heading_title');
        $data['title_conf'] = $this->language->get('title_conf');
        $data['text_data'] = $this->language->get('text_data');
        $data['secret_key'] = $this->language->get('secret_key');
        $data['id_website'] = $this->language->get('id_website');
        $data['yes'] = $this->language->get('yes');
        $data['no'] = $this->language->get('no');
        $data['save'] = $this->language->get('save');
        $data['title_export'] = $this->language->get('title_export');
        $data['text_export'] = $this->language->get('text_export');
        $data['delay'] = $this->language->get('delay');
        $data['week'] = $this->language->get('week');
        $data['weeks'] = $this->language->get('weeks');
        $data['month'] = $this->language->get('month');
        $data['months'] = $this->language->get('months');
        $data['year'] = $this->language->get('year');
        $data['text_product'] = $this->language->get('text_product');
        $data['text_without'] = $this->language->get('text_without');
        $data['text_with'] = $this->language->get('text_with');
        $data['text_status'] = $this->language->get('text_status');
        $data['action_export'] = $this->language->get('action_export');
        $data['text_final'] = $this->language->get('text_final');
        $data['download'] = $this->language->get('download');
        $data['no_orders'] = $this->language->get('no_orders');
        $data['title_check'] = $this->language->get('title_check');
        $data['text_counts'] = $this->language->get('text_counts');
        $data['text_flag'] = $this->language->get('text_flag');
        $data['platforme'] = $this->language->get('platforme');
        $data['advanced'] = $this->language->get('advanced');
        $data['stars_category_text'] = $this->language->get('stars_category_text');
        $data['enabled'] = $this->language->get('enabled');
        $data['disabled'] = $this->language->get('disabled');
        $data['store_list'] = $this->language->get('store_list');
        $data['store_id'] = $this->language->get('store_id');
        $data['store_name'] = $this->language->get('store_name');
        $data['store_url'] = $this->language->get('store_url');
        $data['store_action'] = $this->language->get('store_action');
        $data['multilangue_info'] = $this->language->get('multilangue_info');
        $data['multilangue_enable'] = $this->language->get('multilangue_enable');
        $data['choose_language'] = $this->language->get('choose_language');


        $table_names = array(
            'conf' => 'netreviews_configuration',
            'orders' => 'netreviews_orders'
        );

        $data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], 'SSL')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_module'),
			'href' => $this->url->link('extension/module/netreviews', 'user_token=' . $this->session->data['user_token'], 'SSL')
		);

		if (!isset($this->request->get['module_id'])) {
			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('heading_title'),
				'href' => $this->url->link('extension/module/banner', 'user_token=' . $this->session->data['user_token'], 'SSL')
			);
		} else {
			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('heading_title'),
				'href' => $this->url->link('extension/module/banner', 'user_token=' . $this->session->data['user_token'] . '&module_id=' . $this->request->get['module_id'], 'SSL')
			);
		}


        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        foreach($table_names as $key=>$name) {
            //$data[$key] = $this->model_extension_netreviews_check->check_table_exist($name);
        }


        // **************************************************
        // ****** LOAD STORES *******************************
        // **************************************************
        $this->load->model('setting/store');
        $stores = $this->model_setting_store->getStores();
        $data['list_store'][0] = array(
                    'id'    => '0',
                    'name'  => 'Default',
                    'url'   => $url_config
                );
        if ($stores = $this->model_setting_store->getStores()) {
            $i = 1;
            foreach ($stores as $store) {
                $data['list_store'][$i] = array(
                                        'id'    => $store['store_id'],
                                        'name'  => $store['name'],
                                        'url'   => $store['url']
                                        );
                ++$i;
            }
        }


        $data['admin_url'] = $this->url->link('extension/module/netreviews', 'user_token=' . $this->session->data['user_token'], 'SSL');
        $data['list_stores_url'] = $this->url->link('extension/module/netreviews', 'user_token=' . $this->session->data['user_token'].'&list_stores=' . 'yes', 'SSL');


    //*****************************************************************************
    //***************** End load all the files ************************************
    //*****************************************************************************




    // *********************************************************
    // ***** Display list of stores or just one particular store
    // *********************************************************
    $data['display_list_store'] = false;
    if(isset($this->request->get['list_stores']) || !isset($this->request->get['store_id'])){

            $data['display_list_store'] = true;

    }else{  // Else Display Configuration Setting for a single store


        // **********************************************************
        // *** Get Store ID *****************************************
        // **********************************************************
        $data['current_store'] = null;
        $store_id = null;
        if(isset($this->request->get['store_id'])){
            $store_id = $this->request->get['store_id'];
            $data['current_store'] = "&store_id=".$store_id;



            // ******************************************************************************
            // ******* User wishes to provide advanced configuration settings ***************
            // ******************************************************************************
            if(isset($this->request->post['netreviews_advanced_config'])){

                $language_code = isset($this->request->post['netreviews_advanced_language']) ? $this->request->post['netreviews_advanced_language'] : null;

                if(!empty($language_code) && isset($this->request->post['netreviews_star_category_'.$language_code])){

                    $category_stars = $this->request->post['netreviews_star_category_'.$language_code];
                    echo "category_stars: ".$category_stars;
                    $this->model_extension_module_netreviews->deletePropertyLangSite($store_id, "CATEGORY_STARS", $language_code);

                    $this->model_extension_module_netreviews->insertPropertyLangSite("CATEGORY_STARS", $category_stars,$store_id,$language_code);
                }
            } // End isset($this->request->post['netreviews_advanced_config'])




            // *********************************************************************************************
            // ***************** USER WISHES TO EXPORT ORDERS **********************************************
            // *********************************************************************************************
            if(isset($this->request->post['netreviews_order_states'])){



                //The client wishes to export orders
                if(isset($this->request->post['order_list_status']) && isset($this->request->post['netreviews_lang_code']) && isset($this->request->post['delay_value']) && isset($this->request->post['info_prod'])){

                    $listStatus = array();
                    foreach($this->request->post['order_list_status'] as $status){
                        $listStatus[] = "'".$status."'";
                    }
                    if(!empty($listStatus)){

                        $order_list_status = implode(",", $listStatus);
                        $lang_id = $this->request->post['netreviews_lang_code'];
                        $delay_value = $this->request->post['delay_value'];
                        $info_prod = $this->request->post['info_prod'];

                        $delay_value = $this->model_extension_module_netreviews->get_query_date($delay_value);
                        $results = $this->model_extension_module_netreviews->get_result_export($delay_value, $order_list_status, $store_id, $lang_id);

                        $name_file = DIR_DOWNLOAD."orders-"."storeID".$store_id."langID".$lang_id.'.csv';
                        $url =  $data['list_store'][$store_id]['url'];
                        $data['response'] = $this->create_csv_file($results,$info_prod,$url, $name_file);
                        $data['url_file'] = HTTP_SERVER.'index.php?route=netreviews/download&user_token='.$this->session->data['user_token'];
                        // Output orders to the client
                        if (isset($this->session->data['order_file_location'])) {
                            ob_clean();
                            ob_start();
                            header('Content-type: text/csv'); 
                            header('Content-Disposition: attachment; filename="'.basename($this->session->data['order_file_location']).'"'); 
                            readfile($this->session->data['order_file_location']);
                            ob_end_flush();
                            exit;
                        }

                    }
                }
            }  // End isset($this->request->post['netreviews_order_states'])



            // *********** Load all installed Languages ****************************************
            $this->load->model('localisation/language');
            $data['languages'] = array();
            $results = $this->model_localisation_language->getLanguages();

            foreach ($results as $result) {
                if ($result['status']) {
                    $data['languages'][] = array(
                        'name' => $result['name'],
                        'id_lang' => $result['language_id'],
                        'code' => $result['code']
                    );
                }
            }
            // Default Language for the store that has been choosen

            $default_lang = $this->model_extension_module_netreviews->get_default_lang_store($store_id);
            $data['default_lang'] = $default_lang;

            // ******************************************************************************************************
            // ************* Register New Configuration Settings ****************************************************
            // ******************************************************************************************************
            // Remove previous configuration settings
            // Add new configuration settings
            if(isset($this->request->post['submit_configuration'])){

                    // Remove all Site - Language configuration Settings
                    foreach($data['languages'] as $language){
                        // **** Important ******
                        // Remove IDWebsite, Secret Key, Platform code, mod version for all storefronts in this website before saving new configuration
                        $this->model_extension_module_netreviews->deletePropertyLangSite($store_id,"ID_WEBSITE", $language['id_lang']);
                        $this->model_extension_module_netreviews->deletePropertyLangSite($store_id,"SECRET_KEY", $language['id_lang']);
                        $this->model_extension_module_netreviews->deletePropertyLangSite($store_id,"PLATFORM_CODE", $language['id_lang']);
                        $this->model_extension_module_netreviews->deletePropertyLangSite($store_id,"MODVERSION", $language['id_lang']);
                    }

                    // Remove the store property multilangue before saving user submitted value
                    $this->model_extension_module_netreviews->removePropertySite('AV_MULTILINGUE', $store_id);

                    // which post data to take single language or multilanguage
                    $key = $this->request->post['av_multilangue'] ? 'multi_key' : 'key';
                    $id_web = $this->request->post['av_multilangue'] ? 'multi_id_web' : 'id_web';
                    $client_platform = $this->request->post['av_multilangue'] ? 'multi_platform' : 'platform';

                    // Save new User Submitted Site - Configuration Settings
                    // ************ Secret Key *************************************************
                    // Ensure IdWebsite is not empty
                    foreach($this->request->post[$key] as $id_lang => $secret_key){

                        if(!empty($id_lang) && !empty($secret_key) && !empty($this->request->post[$id_web][$id_lang])){
                            $this->model_extension_module_netreviews->insertPropertyLangSite("SECRET_KEY", $secret_key,$store_id,$id_lang);
                            $this->model_extension_module_netreviews->insertPropertyLangSite('MODVERSION', $model_version,$store_id,$id_lang);
                        }                   
                    }
                    
                    // ************** IdWebsite *************************************************
                    // Ensure Secret Key is not empty
                    foreach($this->request->post[$id_web] as $id_lang => $id_website){
                        if(!empty($id_lang) && !empty($id_website) && !empty($this->request->post[$key][$id_lang])){
                            $this->model_extension_module_netreviews->insertPropertyLangSite("ID_WEBSITE", $id_website,$store_id,$id_lang);
                        }                   
                    }
                    // ************* Platform Code **********************************************
                    // Ensure IdWebsite and SecretKey are not empty
                    foreach($this->request->post[$client_platform] as $id_lang => $platform_code){
                        if(!empty($id_lang) && !empty($platform_code) && !empty($this->request->post[$id_web][$id_lang]) && !empty($this->request->post[$key][$id_lang])){
                            $this->model_extension_module_netreviews->insertPropertyLangSite("PLATFORM_CODE", $platform_code,$store_id,$id_lang);
                        }                   
                    }

                    $this->model_extension_module_netreviews->insertPropertySite('AV_MULTILINGUE', $this->request->post['av_multilangue'], $store_id);


                    // *** Important *** Clean up - remove all properties for Storefronts which are no longer configured
                    // Test if there is a property IDWEBSITE for Store ID and Lang ID combination if not then delete all other properties
                    foreach($data['languages'] as $language){


                        $propertyIDWebsite = $this->model_extension_module_netreviews->getPropertyLangSite("ID_WEBSITE",$store_id, $language['id_lang']);
                        // If no property IDWebsite then remove any other properties for that Storefront i.e. Store + Lang
                        if(empty($propertyIDWebsite)){
                            $this->model_extension_module_netreviews->removeLangSiteSettings($store_id, $language['id_lang']);
                        }
                    }


            }
            // **********************************************************************************************************
            // *********************  END REGISTER NEW CONFIGURATION ****************************************************
            // **********************************************************************************************************



            // ************************************************************************************************************
            // **************** DISPLAY LATEST CONFIGURATION SETTINGS *****************************************************
            // ************************************************************************************************************
            // If Multilangue 
            $array_key = array();
            $array_id_web = array();
            $array_platform = array();

            $data['is_multilangue'] = $this->model_extension_module_netreviews->getPropertySite("AV_MULTILINGUE", $store_id);

            // which data to display single language or multilanguage
            $key = $data['is_multilangue'] ? 'multi_key' : 'key';
            $id_web = $data['is_multilangue'] ? 'multi_id_web' : 'id_web';
            $client_platform = $data['is_multilangue'] ? 'multi_platform' : 'platform';

            if($data['is_multilangue']) {
                foreach($data['languages'] as $language){


                        $array_key[$language['id_lang']] = $this->model_extension_module_netreviews->getPropertyLangSite("SECRET_KEY", $store_id,$language['id_lang']);

                        $array_id_web[$language['id_lang']] = $this->model_extension_module_netreviews->getPropertyLangSite("ID_WEBSITE", $store_id,$language['id_lang']);
                        $array_platform[$language['id_lang']] = $this->model_extension_module_netreviews->getPropertyLangSite("PLATFORM_CODE", $store_id,$language['id_lang']);
                }
            } else {        // Single Language
                $array_key[$data['default_lang']] = $this->model_extension_module_netreviews->getPropertyLangSite("SECRET_KEY", $store_id,$data['default_lang']);
                $array_id_web[$data['default_lang']] = $this->model_extension_module_netreviews->getPropertyLangSite("ID_WEBSITE", $store_id,$data['default_lang']);
                $array_platform[$data['default_lang']] = $this->model_extension_module_netreviews->getPropertyLangSite("PLATFORM_CODE", $store_id,$data['default_lang']);

            }

            $data[$key] = $array_key;
            $data[$id_web] = $array_id_web;
            $data[$client_platform] = $array_platform;

            // ************ Get data for all Store-Language which has been registered *******************
            $config_languages = array();
            $results = $this->model_extension_module_netreviews->get_config_languages($store_id);

            foreach($results as $config_language){

                $language_id = $config_language['id_lang'];

                $data['config_languages'][$config_language['id_lang']]['flag_0'] = $this->model_extension_module_netreviews->get_count_flag('0', $store_id, $language_id);
                $data['config_languages'][$config_language['id_lang']]['flag_1'] = $this->model_extension_module_netreviews->get_count_flag('1', $store_id, $language_id);
                $data['category_stars'][$config_language['id_lang']] = $this->model_extension_module_netreviews->getPropertyLangSite("CATEGORY_STARS", $store_id,$language_id);
            }




            // ********** Get order status list, In Opencart order status are at the level of language *************
            if(isset($data['config_languages'])){ 
                foreach($data['config_languages'] As $language_id => $flag_info){
                    
                    $data['config_languages'][$language_id]['full_order_states'] = $this->model_extension_module_netreviews->get_list_status($language_id);
                    
                }
            }
            // ***************************************************************************************
            // ******************  END DISPLAY LATEST DISPLAY SETTINGS *******************************
            // ***************************************************************************************



        } // End isset($this->request->get['store_id'])
    } // End isset($this->request->get['list_stores'])


        // **********************************************************************************
        $this->response->setOutput($this->load->view('extension/module/netreviews', $data));
    }

    /****************************************************************
                    Controller netreviews: page export 
    ****************************************************************/

    public function create_csv_file($orders,$add_products, $url, $name_file) {
       
        $flag = 0;
        $delimiter = ";";
        $this->session->data['order_file_location'] = $name_file;
        $data['name_export_file'] = $name_file;
        $file_csv = fopen($name_file, 'w+');
        

        $header_csv = array('order_id','store_id','language_id','email','first_name',
                'last_name','order_date','amount_order','order_status','product_id',
                'product_name','url','url_image');
        $store_url = $url;
        
        // If no products have been requested then remove duplicate orders
        if ($add_products == 'no') {

                unset($header_csv[9],$header_csv[10],$header_csv[11],$header_csv[12]);
                $orders_only = array();
                // Start with new empty array, add each order so long as the order_id has not already been added
                foreach($orders as $order){
                    $search_id = $order['order_id'];
                    $add_order = true;
                    foreach($orders_only as $order_only){
                        if($order_only['order_id'] == $search_id){
                            $add_order = false;
                        }
                    }
                    if($add_order){
                        $orders_only[] = $order;
                    }
                }
                $orders = $orders_only;
        }

   
        fprintf($file_csv, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($file_csv, $header_csv, $delimiter);
            foreach($orders as $line) {
                $linetmp['order_id'] = $line['order_id'];

                    $linetmp['store_id'] = $line['store_id'];
                    $linetmp['language_id'] = $line['language_id'];
                    $linetmp['email'] = $line['email'];
                    $linetmp['first_name'] = $line['firstname'];
                    $linetmp['last_name'] = $line['lastname'];
                    $linetmp['order_date'] = $line['order_date'];
                    $linetmp['amount_order'] = (round($line['amount_order'],2) * 100);
                    $linetmp['order_status'] = $line['order_status'];
                    $linetmp['product_id'] = $line['product_id'];
                    $linetmp['product_name'] = $line['product_name'];
                    $linetmp['url'] = $url.'index.php?route=product/product&product_id='.$line['product_id'];
                    $linetmp['url_image'] = $this->model_extension_module_netreviews->getUrl_image($line['product_id'],$url);
                    $linetmp['order_date'] = $this->model_extension_module_netreviews->get_new_format_date($linetmp['order_date']);
                if ($add_products == 'no') {
                    unset($linetmp['product_id'],$linetmp['product_name'],$linetmp['url'],$linetmp['url_image']);
                }
                if (fputcsv($file_csv, $linetmp, $delimiter) != false){
                    $flag = 1;
                }
            }

         
         fclose($file_csv);
         return $flag;
    }















        /****************************************************************
                    Controller netreviews:installation
        ****************************************************************/
    public function install() {
        
            $this->language->load('extension/module/netreviews');
            $this->load->model('extension/module/netreviews');
            $this->load->model('setting/store');
            $data['nr_title'] = $this->language->get('heading_title');
            $this->language->load($this->model_extension_module_netreviews->get_language());
            $data['nr_edit'] = $this->language->get('text_edit');

            $this->model_extension_module_netreviews->install_netreviews();
            //$url_config = $this->model_extension_module_netreviews->get_url_config('');
            // $data['list_store'][0] = array(
            //                         'id'    => '0',
            //                         'name'  => 'Default',
            //                         'url'   => $url_config
            //                     );
            // if ($results = $this->model_setting_store->getStores()) {
            //     $i = 1;
            //     $count = $this->db->query("SELECT COUNT(*) AS value FROM netreviews_configuration");
            //     foreach ($results as $store) {
            //             $index = $i * $count->row['value'];
            //             $this->model_extension_module_netreviews->add_config_store($store['store_id'],$index);
            //             $data['list_store'][$i] = array(
            //                             'id'    => $store['store_id'],
            //                             'name'  => $store['name'],
            //                             'url'   => $store['url']
            //                             );
            //             ++$i;
            //         }
            // }
            // foreach ($data['list_store'] as $store) {
            //         $this->model_extension_module_netreviews->create_pages($store['id'],$store['url']);
            // }           
    }


        public function uninstall() {

            $this->language->load('extension/module/netreviews');
            $this->load->model('extension/module/netreviews');
            $this->load->model('setting/store');
            $data['nr_title'] = $this->language->get('heading_title');
            $this->language->load($this->model_extension_module_netreviews->get_language());
            $data['nr_edit'] = $this->language->get('text_edit');
       		$this->model_extension_module_netreviews->uninstall_netreviews(); 
    }

    


}