Plugin Directory

Changeset 2456862


Ignore:
Timestamp:
01/15/2021 10:54:50 AM (5 years ago)
Author:
phcwordpress
Message:

Build PHC GO

Location:
drivefx-woocommerce/trunk
Files:
1 added
10 edited

Legend:

Unmodified
Added
Removed
  • drivefx-woocommerce/trunk/class.DriveFxWoocommerce.php

    r2092492 r2456862  
    11<?php
    2     set_time_limit(350);
    3 
     2
     3require_once  __DIR__.'/settings/syncro_gate.php';
     4require_once 'PHCLibrary/log.php';
     5require_once 'PHCLibrary/authentication.php';
     6require_once 'PHCLibrary/utils.php';
     7require_once 'PHCLibrary/orders.php';
     8require_once 'PHCLibrary/invoices.php';
    49
    510    class DriveFxWoocommerce {
     
    1015        public $extraurl = "";
    1116
     17        private $logs;
    1218        private $validSettings = false;
     19        private $auth_services;
     20        private $syncro_services;
     21        private $utils_services;
     22        private $orders_services;
     23        private $invoices_services;
    1324
    1425        // backend settings
     
    1728                'username'          => array('label' => 'Username',                                   'type' => 'text',          'required' => true,  'descr' => 'This username allows the backend to accept data sent from this plugin.', 'notice' => 'This can not be empty! Please enter your username...'),
    1829                'password'          => array('label' => 'Password',                                   'type' => 'password',      'required' => true,  'descr' => 'This password allows the backend to accept data sent from this plugin.', 'notice' => 'This can not be empty! Please enter your password...'),     
    19                 'url'               => array('label' => 'Backend URL',                                'type' => 'url',           'required' => true,  'descr' => 'The URL of your Drive FX application.<br>Something like, e.g. https://sisXX.drivefx.net/XPTO/html', 'notice' => 'No backend URL! Please define your backend URL...'),
    20                 'dbname'            => array('label' => 'Database Name',                              'type' => 'text',          'required' => false, 'descr' => 'Enter the name of the Drive FX company where you want save your information.<br>You can leave this empty if you only work with one company.', 'notice' => ''),
     30                'url'               => array('label' => 'Backend URL',                                'type' => 'url',           'required' => true,  'descr' => 'The URL of your PHC GO application.<br>Something like, e.g. https://sisXX.phcgo.net/XPTO/html', 'notice' => 'No backend URL! Please define your backend URL...'),
     31                'dbname'            => array('label' => 'Database Name',                              'type' => 'text',          'required' => false, 'descr' => 'Enter the name of the PHC GO where you want save your information.<br>You can leave this empty if you only work with one company.', 'notice' => ''),
    2132                'createInvoice'     => array('label' => 'Create Orders and Invoices',                 'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Create invoices for orders that come in, otherwise only the client is created (recommended).', 'notice' => ''),
    2233                'sendInvoice'       => array('label' => 'Send Invoice',                               'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Send the client an e-mail with the order invoice attached', 'notice' => ''),
     34                'emailBody'         => array('label' => 'E-mail body content',                        'type' => 'text',          'required' => false, 'descr' => 'Enter the text to be attached to the e-mails sent to the client.', 'notice' => ''),
    2335                'typeOfInvoice'     => array('label' => 'Type of Invoice Document',                   'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the type of invoice document', 'notice' => ''),
    2436                'toSignInvoice'     => array('label' => 'Sign Invoice',                               'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Sign Invoice document after its creation.', 'notice' => ''),
    2537                'fieldNif'          => array('label' => 'NIF Field in Woocommerce',                   'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the nif field of woocommerce', 'notice' => ''),
    26                 'includeTaxonSendCost'          => array('label' => 'Tax included in Shipping Cost?', 'type' => 'select',        'required' => false, 'checkboxDescription' => 'Does the shipping cost has tax already included in price?', 'notice' => ''),
     38                'includeTaxonSendCost'          => array('label' => 'Tax included in products Cost?', 'type' => 'select',        'required' => false, 'checkboxDescription' => 'Does the products cost has tax already included in price?', 'notice' => ''),
     39                'createExemptCl'    => array('label' => 'Create tax-exempt customers?',               'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Create tax-free customers (for foreigners)', 'notice' => ''),
     40                'typeOfReason'      => array('label' => 'Select tax exempt reason',                   'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the reason for the tax exemption', 'notice' => ''),
    2741                'warehouseOrder'    => array('label' => 'Order Warehouse',                            'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose from warehouse do you want import products', 'notice' => ''),
    2842                'typeOfOrder'       => array('label' => 'Type of Order',                              'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose the type of order', 'notice' => ''),
    2943                'toSignOrder'       => array('label' => 'Sign Order',                                 'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Sign Order document after its creation.', 'notice' => ''),
    30                 'numberOfOrder'     => array('label' => 'Field to save number of order in Drive FX',  'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose field in database of Drive FX that you want to save order number', 'notice' => ''),
    31                 'statusOfOrder'     => array('label' => 'Field to save status of order in Drive FX',  'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose field in database of Drive FX that you want to save order status', 'notice' => ''),
     44                'numberOfOrder'     => array('label' => 'Field to save number of order in PHC GO',    'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose field in database of PHC GO that you want to save order number', 'notice' => ''),
     45                'statusOfOrder'     => array('label' => 'Field to save status of order in PHC GO',    'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose field in database of PHC GO that you want to save order status', 'notice' => ''),
     46                'shippingName'      => array('label' => 'Reference for shipping',                     'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose a reference of services to be used for shipping', 'notice' => ''),
     47                'feesName'          => array('label' => 'Reference for fees',                         'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose a reference of services to be used for fees', 'notice' => ''),
    3248                'manageStock'       => array('label' => 'Manage Stock',                               'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Manage stock at your online shop', 'notice' => ''),
    33                 'productPriceColumn'=> array('label' => 'Field to obtain product price in Drive FX',  'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose field in database of Drive FX that you want to obtain product price', 'notice' => ''),
     49                'positiveStock'     => array('label' => 'Products with stock',                        'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Only import products that have stock', 'notice' => ''),
     50                'filterStock'       => array('label' => 'Only available stock',                       'type' => 'checkbox',      'required' => false, 'checkboxDescription' => 'Filter the quantity of stock minus uninvoiced orders', 'notice' => ''),
     51                'productPriceColumn'=> array('label' => 'Field to obtain product price in PHC GO',    'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose field in database of PHC GO that you want to obtain product price', 'notice' => ''),
    3452                'warehouse'         => array('label' => 'Warehouse',                                  'type' => 'select',        'required' => false, 'checkboxDescription' => 'Choose from warehouse do you want import products', 'notice' => '')
    3553            )
     
    4563
    4664        private function __construct () {
     65            $this->logs = new Logs();
     66            $this->auth_services = new AuthentificationService();   
     67            $this->syncro_services = new SyncroService();   
     68            $this->utils_services = new UtilsServices();   
     69            $this->orders_services = new OrdersService();   
     70            $this->invoices_services = new InvoicesServices(); 
     71
    4772            // call init
    4873            $this->init();
     
    5075            // store default BACKEND fields settings
    5176            add_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME, array('backend' => $this->options['backend']));
     77           
    5278        }
    5379       
     
    82108           
    83109            add_action( 'woocommerce_order_status_completed',  array($this, 'completedOrder'),2);
    84            
    85         //  add_action( 'woocommerce_payment_complete',  array($this, 'completedOrder'));
    86            
    87            
    88         //  add_action( 'woocommerce_payment_complete','mysite_woocommerce_payment_complete' );
    89 
    90 
    91 
    92110            add_action( 'woocommerce_order_status_cancelled',  array($this, 'cancelOrder'));
    93111            add_action( 'woocommerce_order_status_failed',  array($this, 'cancelOrder'));
    94112            add_action( 'woocommerce_order_status_refunded',  array($this, 'cancelOrder'));
    95113
    96             //Save field to show status order in Drive FX
     114            //Save field to show status order in PHC
    97115            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    98             //if(!empty($settings['backend']['typeOfOrder'])){
    99                 //add_action('update_option',  array($this, 'saveFieldOrderStatus'));
    100             //} 
    101116
    102117            // handler for form submission
     
    108123
    109124            //If exists GET['fxtoken'], so popup is open to obtain key
     125            if(!isset($_GET["accessToken"]))
     126                return;
    110127            $accessToken = filter_var($_GET['accessToken'], FILTER_SANITIZE_STRING);
    111128           
     
    139156                    }
    140157                }
    141 
    142158                //Close popup and refresh parent page
    143159                echo "<script type='text/javascript'>
     
    153169        }
    154170
    155     function mysite_woocommerce_payment_complete( $order_id ) {
    156     $this->writeFileLog('payment_complete', "Payment has been received for order $order_id");
    157 
    158     }
     171        function mysite_woocommerce_payment_complete( $order_id ) {
     172            $this->logs->writeFileLog('payment_complete', "Payment has been received for order $order_id");
     173
     174        }
     175       
    159176        //Obtain info of plugins and save information
    160177        public function init_plugin() {
     
    179196        public function register_scripts() {
    180197            ?> <script>
    181               var pathPlugin = "<?php echo plugins_url('/' , __FILE__ ); ?>";
     198            var pathPlugin = "<?php echo plugins_url('/' , __FILE__ ); ?>";
    182199            </script> <?php
    183200           
     
    225242        //Show messages of feedback to user in settings
    226243        public function render_notices() {
    227            
     244            if(!isset($_GET["page"]))
     245                return;
    228246            //only run this on woocommerce plugin area
    229247            if ($_GET["page"] !=  "drivefx-woocommerce")
     
    282300            if($verifyWarning != 1) {
    283301                $this->setCommunicationFx();
     302                //$this->comunication_services->setCommunicationFx();
     303
    284304            }
    285305
     
    288308
    289309        //Called from "external files"
    290         public function woocommerce_fx () {
     310        public function woocommerce_fx() {
     311           
    291312            $method = sanitize_text_field( $_POST['method'] );
    292313       
     
    329350            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    330351
    331             //Obtain configuration to make login
    332             $this->paramsLogin();
    333 
    334             //initial request with login data
    335             $ch = curl_init();
    336 
    337             //URL to save cookie "ASP.NET_SessionId"
    338             curl_setopt($ch, CURLOPT_URL, $this->url);
    339             curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    340             curl_setopt($ch, CURLOPT_POST, true);
    341             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    342             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    343             //Parameters passed to POST
    344 
    345             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    346             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    347             curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    348             curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    349             curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
    350             $response = curl_exec($ch);
    351 
    352             // send response as JSON
    353             $response = json_decode($response, true);
    354 
     352                // get Credentials
     353                $credentials = $this->syncro_services->fetchCredentials();                   
     354                //Obtain configuration to make login
     355                $ch = $this->auth_services->PHCLogin($ch, $credentials);       
     356                //initial request with login data
     357                $response = curl_exec($ch);     
     358                // send response as JSON
     359                $response = json_decode($response, true);
     360                // get the temporary token and insert in credentials object
     361                $credentials->token = $response['result'][0]['token']; 
     362       
     363                //$this->logs->writeFileLog('Login response:', $response);
     364       
    355365            if (curl_error($ch)) {
    356                 $this->writeFileLog('setCommunicationFxWooCommerce', $ch);
     366                $this->logs->writeFileLog('setCommunicationFxWooCommerce', $ch);
    357367                unset($_SESSION['username']);
    358368            } else if(empty($response)){
    359               $this->writeFileLog('setCommunicationFxWooCommerce', 'EMPTY RESPONSE');
    360               $this->messagesError("Can't connect to webservice!! There's an empty response");
    361               unset($_SESSION['username']);
     369            $this->logs->writeFileLog('setCommunicationFxWooCommerce', 'EMPTY RESPONSE');
     370            $this->messagesError("Can't connect to webservice!! There's an empty response");
     371            unset($_SESSION['username']);
    362372            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    363               $this->writeFileLog('setCommunicationFxWooCommerce', $response['messages'][0]['messageCodeLocale']);
    364               $this->messagesError(": Wrong Login! Please check your entered data!");
    365               unset($_SESSION['username']);
     373            $this->logs->writeFileLog('setCommunicationFxWooCommerce', $response['messages'][0]['messageCodeLocale']);
     374            $this->messagesError(": Wrong Login! Please check your entered data!");
     375            unset($_SESSION['username']);
    366376            } else {
    367377                //Save data of login to show in backend.php the other fields (type of invoice and type of order)
    368378                $_SESSION['username'] = $response['result'][0]['username'];
    369379               
    370                 //Obtain gama of Drive FX
    371                 $this->paramsGetBackEndInfo();
    372 
    373                 curl_setopt($ch, CURLOPT_URL, $this->url);
    374                 curl_setopt($ch, CURLOPT_POST, false);
    375                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    376                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    377                 $response = curl_exec($ch);
    378                 // send response as JSON
    379                 $response = json_decode($response, true);
     380                    //Obtain gama of PHC
     381                    $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     382       
     383                    //$this->logs->writeFileLog('BackEnd response:', $response);
    380384
    381385                if (curl_error($ch)) {
    382                     $this->writeFileLog('setCommunicationFx2WooCommerce', $ch);
     386                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    383387                } else if(empty($response)){
    384                     $this->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
     388                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
    385389                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    386                     $this->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
     390                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
    387391                } else {
    388392                    $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
     
    390394               
    391395                //Obtain parameter of manage stock
    392                 $this->paramsGetFrontendInfo();
    393 
    394                 curl_setopt($ch, CURLOPT_URL, $this->url);
    395                 curl_setopt($ch, CURLOPT_POST, false);
    396                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    397                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    398                 $response = curl_exec($ch);
    399                 // send response as JSON
    400                 $response = json_decode($response, true);
     396                $response = $this->utils_services->paramsGetFrontendInfo($ch, $credentials);   
     397
     398                //$this->logs->writeFileLog('FrontEnd response:', $response);
    401399               
    402400                if (curl_error($ch)) {
    403                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', $ch);
     401                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $ch);
    404402                } else if(empty($response)){
    405                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', 'EMPTY RESPONSE');
     403                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', 'EMPTY RESPONSE');
    406404                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    407                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
     405                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
    408406                } else {
    409407                    foreach ($response['result'] as $key => $value){
     
    436434                case 'statusOfOrder':
    437435                    if($_SESSION['gamaDRIVEFX'] >= 9) {
    438                         //Obtain status of order presented in Drive FX
     436                        //Obtain status of order presented in PHC
    439437                        return $this->statusOfOrder($selectItems, $typeOfOrder);
    440438                    }
     
    442440                case 'numberOfOrder':
    443441                    if($_SESSION['gamaDRIVEFX'] >= 9) {
    444                         //Obtain status of order presented in Drive FX
     442                        //Obtain status of order presented in PHC
    445443                        return $this->statusOfOrder($selectItems, $typeOfOrder);
    446444                    }
     
    448446                case 'newTypeOfOrder':
    449447                    if($_SESSION['gamaDRIVEFX'] >= 9) {
    450                         //Create new type of order in Drive FX
     448                        //Create new type of order in PHC
    451449                        $this->newTypeOfOrder($nameTypeOfOrder, $manageStock, $warehouse);
    452450                    }
     
    540538            ));
    541539            return apply_filters( 'woocommerce_get_settings_' . $this->id, $settings );
    542         }
    543 
    544         //Write errors in Log File
    545         public function writeFileLog($text_function, $messageResponse) {
    546             $myFile = __DIR__.'/logsErrors/logs.txt';
    547             $date = date('Y/m/d H:i:s');
    548             $message = $text_function . " " . $date . ":  " . print_r($messageResponse, true) . "\r\n";
    549 
    550             if (file_exists($myFile)) {
    551                 $fh = fopen($myFile, 'a');
    552             } else {
    553                 $fh = fopen($myFile, 'w');
    554             }
    555             fwrite($fh, $message);
    556             fclose($fh);
    557         }
     540        }           
     541           
     542        //Lock System       
     543        public function lockStart() {
     544            $this->logs->writeFileLog('lockStart', "Entrei" );
     545
     546
     547            $maxAttempt=10;
     548           
     549            for($attempt=0;$attempt<$maxAttempt;$attempt++){
     550                $lockFilePath =  __DIR__.'/logsErrors/tim.lock';
     551                $date = new DateTime();
     552                $time =  $date->getTimestamp();
     553                   
     554                if (!file_exists($lockFilePath)){
     555                    @file_put_contents($lockFilePath, $time);
     556                    if (!file_exists($lockFilePath)){
     557                        sleep(1);
     558                        continue;
     559                    }
     560                   
     561                    $this->logs->writeFileLog('lockStart', "Sai" );
     562           
     563                    return true;
    558564       
    559        
    560        
    561        
    562         //Lock System
    563          
    564 
    565     public function lockStart() {
    566     $this->writeFileLog('lockStart', "Entrei" );
    567         $maxAttempt=10;
    568        
    569         for($attempt=0;$attempt<$maxAttempt;$attempt++){
    570             $lockFilePath =  __DIR__.'/logsErrors/tim.lock';
    571             $date = new DateTime();
    572             $time =  $date->getTimestamp();
     565                }
     566           
     567                $contents = file_get_contents($lockFilePath);
     568
     569                $lockedtime = (int)$contents;
    573570               
    574             if (!file_exists($lockFilePath)){
    575                  @file_put_contents($lockFilePath, $time);
    576                   if (!file_exists($lockFilePath)){
     571                if($time-$lockedtime>10){
     572                   
     573                    unlink($lockFilePath);
     574                    @file_put_contents($lockFilePath, $time);
     575                    if (!file_exists($lockFilePath)){
     576                        sleep(1);
     577                        continue;
     578                    }
     579                    $this->logs->writeFileLog('lockStart', "Sai" );
     580                    return true;
     581                }else{
     582                   
    577583                    sleep(1);
    578584                    continue;
    579                   }
    580                  
    581                 $this->writeFileLog('lockStart', "Sai" );
     585                }
     586               
     587           
     588            }
     589            $this->logs->writeFileLog('lockStart', "Sair");
     590            return true;
     591
    582592       
    583                 return true;
    584      
    585             }
    586        
    587             $contents = file_get_contents($lockFilePath);
    588 
    589             $lockedtime = (int)$contents;
    590            
    591             if($time-$lockedtime>10){
    592                  
    593                  unlink($lockFilePath);
    594                  @file_put_contents($lockFilePath, $time);
    595                  if (!file_exists($lockFilePath)){
    596                     sleep(1);
    597                     continue;
    598                  }
    599                  $this->writeFileLog('lockStart', "Sai" );
    600                  return true;
    601             }else{
    602                
    603                 sleep(1);
    604                 continue;
    605             }
    606            
    607        
    608         }
    609         $this->writeFileLog('lockStart', "Sair");
    610         return true;
    611 
    612        
    613     }
    614 
    615     public function lockEnd() {
    616             $this->writeFileLog('lockEnd', "Entrei" );
    617         $lockFilePath =  __DIR__.'/logsErrors/tim.lock';
    618         unlink($lockFilePath);
    619         $this->writeFileLog('lockEnd', "Sai" );
    620         return true;
    621     }
    622        
    623        
    624        
    625        
    626        
    627        
    628        
    629        
    630        
    631        
    632        
    633 
    634         //Header to make login
    635         public function paramsLogin(){
    636            
    637             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    638                    
    639             global $wpdb;
    640             $table_name = $wpdb->prefix."postmeta";
    641             $query = "SELECT meta_value FROM %s WHERE meta_key = %s";
    642             $resultDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, '_token')));
    643 
    644             // build our web service full URL
    645             if(is_array($settings['backend']['url'])){
    646                 $settings['backend']['url'] = '';
    647             } else {
    648                 $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    649                 $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    650                 $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    651             }
    652 
    653             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/UserLoginWS/userLoginCompany";
    654 
    655             // Create map with request parameters
    656             $this->params = array(  'userCode' => $settings['backend']['username'],
    657                                     'password' => $settings['backend']['password'],
    658                                     'applicationType' => $resultDB->meta_value,
    659                                     'company' => $settings['backend']['dbname']
    660                                 );
    661             // Build Http query using params
    662             $this->query = http_build_query ($this->params);
    663         }
    664      
    665         //Header to create Query of entityName called
    666         public function paramsQuery($entityName, $filterItem = null, $valueItem = null){
    667             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    668             // build our web service full URL
    669             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    670             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    671             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    672             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/SearchWS/QueryAsEntities";
    673             // Create map with request parameters
    674             $this->params =  array('itemQuery' => '{"groupByItems":[],
    675                                                     "lazyLoaded":false,
    676                                                     "joinEntities":[],
    677                                                     "orderByItems":[],
    678                                                     "SelectItems":[],
    679                                                     "entityName":"'.$entityName.'",
    680                                                     "filterItems":[{
    681                                                                     "comparison":0,
    682                                                                     "filterItem":"'.$filterItem.'",
    683                                                                     "valueItem":"'.$valueItem.'",
    684                                                                     "groupItem":1,
    685                                                                     "checkNull":false,
    686                                                                     "skipCheckType":false,
    687                                                                     "type":"Number"
    688                                                                   }]}'
    689                                 );
    690             // Build Http query using params
    691             $this->query = http_build_query ($this->params);
    692         }
    693 
    694         //Header to create Query of webservice called
    695         public function paramsQuery2($entityName){
    696             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    697             // build our web service full URL
    698             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    699             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    700             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    701             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/SearchWS/QueryAsEntities";
    702             // Create map with request parameters
    703             $this->params =  array ('itemQuery' => '{"groupByItems":[],
    704                                                     "lazyLoaded":false,
    705                                                     "joinEntities":[],
    706                                                     "orderByItems":[],
    707                                                     "SelectItems":[],
    708                                                     "entityName":"'.$entityName.'",
    709                                                     "filterItems":[]
    710                                                     }'
    711                              );
    712             // Build Http query using params
    713             $this->query = http_build_query ($this->params);
    714         }
    715 
    716         //Header to create Query of webservice called
    717         public function paramsQuery3($entityName, $filterItems){
    718             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    719             // build our web service full URL
    720             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    721             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    722             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    723             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/SearchWS/QueryAsEntities";
    724             // Create map with request parameters
    725             $this->params =  array ('itemQuery' => '{"groupByItems":[],
    726                                                     "lazyLoaded":false,
    727                                                     "joinEntities":[],
    728                                                     "orderByItems":[],
    729                                                     "SelectItems":[],
    730                                                     "entityName":"'.$entityName.'",
    731                                                     "filterItems":['.$filterItems.']
    732                                                     }'
    733                              );
    734             // Build Http query using params
    735             $this->query = http_build_query ($this->params);
    736         }
    737 
    738         //Header to create Query of webservice called
    739         public function paramsQuery4($entityName, $selectItems, $valueItem){
    740             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    741             // build our web service full URL
    742             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    743             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    744             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    745             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/SearchWS/QueryAsEntities";
    746             // Create map with request parameters
    747             $this->params =  array ('itemQuery' => '{"groupByItems":[],
    748                                                     "lazyLoaded":false,
    749                                                     "joinEntities":[],
    750                                                     "orderByItems":[],
    751                                                     "SelectItems":["'.$selectItems.'"],
    752                                                     "entityName":"'.$entityName.'",
    753                                                     "filterItems":[{
    754                                                                     "comparison":0,
    755                                                                     "filterItem":"ndos",
    756                                                                     "valueItem":'.$valueItem.',
    757                                                                     "groupItem":1,
    758                                                                     "checkNull":false,
    759                                                                     "skipCheckType":false,
    760                                                                     "type":"Number"
    761                                                                   }]}'
    762                              );
    763 
    764             // Build Http query using params
    765             $this->query = http_build_query ($this->params);
    766         }
    767 
    768         //Header to create Query of webservice called
    769         public function paramsGetBackEndInfo(){
    770             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    771             // build our web service full URL
    772             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    773             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    774             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    775             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/UserLoginWS/getBackEndInfo";
    776             // Create map with request parameters
    777             $this->params =  array ('loginInfoVO' => '{"userCode": "' . $settings['backend']['username'] . '",
    778                                                      "password": "' . $settings['backend']['password'] . '",
    779                                                      "company":  "' . $settings['backend']['dbname'] . '",
    780                                                      "language": "",
    781                                                      "hash": ""
    782                                                     }'
    783                                    );
    784 
    785             // Build Http query using params
    786             $this->query = http_build_query ($this->params);
    787         }
    788 
    789         //Header to create a new instance of webservice called
    790         public function paramsNewInstance($webservice, $ndos){
    791             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    792             // build our web service full URL
    793             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    794             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    795             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    796             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/{$webservice}/getNewInstance";
    797             // Create map with request parameters
    798             $this->params =  array ('ndos' => $ndos);
    799             // Build Http query using params
    800             $this->query = http_build_query ($this->params);
    801         }
    802      
    803         //Header to create a new instance by ref of webservice called
    804         public function paramsNewInstanceByRef($webservice, $webserviceMethod, $fieldWs, $fieldWsEditing, $stamp, $listOfRefs){
    805             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    806             // build our web service full URL
    807             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    808             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    809             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    810             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/{$webservice}/{$webserviceMethod}";
    811             //Create references list
    812             if (is_array($listOfRefs)){
    813                 foreach ($listOfRefs as $key => $value){
    814                     if($key == 0){
    815                         $listOfRefs = $value;
    816                     } else {
    817                         $listOfRefs .= "\", \"" . $value;
    818                     }
    819                 }
    820             }
    821             // Create map with request parameters
    822             $this->params = array($fieldWs => $stamp,
    823                                     'refsIds' => '["'. $listOfRefs . '"]',
    824                                     $fieldWsEditing => ""
    825                                 );
    826             // Build Http query using params
    827             $this->query = http_build_query ($this->params);
    828         }
    829 
    830         //Header to create a new instance from reference of webservice called
    831         public function paramsNewInstanceFromReference($boStamp){
    832             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    833             // build our web service full URL
    834             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    835             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    836             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    837             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/FtWS/getNewInstanceFromReference";
    838             // Create map with request parameters
    839             $this->params =  array ('parameters' => '[{"key":"origin",
    840                                                       "value":"BO"
    841                                                       },
    842                                                       {"key":"originstamp",
    843                                                       "value":"'.$boStamp.'"
    844                                                       },
    845                                                       {"key":"docid",
    846                                                       "value":"'.$settings['backend']['typeOfInvoice'].'"
    847                                                       }
    848                                                     ]'
    849                                     );
    850             // Build Http query using params
    851             $this->query = http_build_query ($this->params);
    852         }
    853 
    854         //Header to save information of webservice called
    855         public function paramsSave($webservice, $response){
    856             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    857             // build our web service full URL
    858             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    859             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    860             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    861             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/{$webservice}/Save";
    862             // Create map with request parameters
    863             $this->params =  array ('itemVO' => json_encode($response['result'][0]),
    864                               'runWarningRules' => 'false');
    865             // Build Http query using params
    866             $this->query = http_build_query ($this->params);
    867         }
    868        
    869         //Header to save information of webservice called
    870         public function paramsGetFrontendInfo(){
    871             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    872             // build our web service full URL
    873             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    874             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    875             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    876             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/ParameterWS/getFrontEndParameters";
    877             // Create map with request parameters
    878             $this->params =  array ('loginInfoVO' =>'{ "userCode": "' . $settings['backend']['username'] . '",
    879                                                         "password": "' . $settings['backend']['password'] . '",
    880                                                         "company":  "' . $settings['backend']['dbname'] . '",
    881                                                         "language": "",
    882                                                         "hash": ""
    883                                                     }'
    884                                    );
    885 
    886             // Build Http query using params
    887             $this->query = http_build_query ($this->params);
    888        
    889         }
    890 
    891         //Header to sign FT
    892         public function paramsSignDocument($ftstamp){
    893             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    894             // build our web service full URL
    895             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    896             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    897             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    898             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/FtWS/signDocument";
    899             // Create map with request parameters
    900             $this->params =  array ('ftstamp' => $ftstamp);
    901             // Build Http query using params
    902             $this->query = http_build_query ($this->params);
    903         }
    904 
    905         //Header to sign BO
    906         public function paramsSignOrder($bostamp){
    907             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    908             // build our web service full URL
    909             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    910             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    911             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    912             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/BoWS/signDocument";
    913             // Create map with request parameters
    914             $this->params =  array ('bostamp' => $bostamp);
    915             // Build Http query using params
    916             $this->query = http_build_query ($this->params);
    917         }
    918 
    919         //Header to sign FT
    920         public function paramsGetReportForPrint(){
    921             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    922             // build our web service full URL
    923             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    924             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    925             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    926             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/reportws/getReportsForPrint";
    927             // Create map with request parameters
    928             $this->params =  array ('entityname' => 'ft',
    929                                     'numdoc' => $settings['backend']['typeOfInvoice']);
    930             // Build Http query using params
    931             $this->query = http_build_query ($this->params);
    932         }
    933 
    934         //Header to sign FT
    935         public function paramsSendReportEmail($repstamp, $ftstamp, $emailTo, $emailFrom, $docId, $reference){
    936             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    937             // build our web service full URL
    938             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    939             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    940             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    941             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/reportws/print";
    942             // Create map with request parameters
    943            
    944        
    945                 // Create map with request parameters
    946             $this->params =  array ('options' => '{"docId":'.$docId.',
    947                                             "emailConfig":
    948                                             {"bcc":"",
    949                                             "body":"",
    950                                             "cc":"",
    951                                             "isBodyHtml":false,
    952                                             "sendFrom":"'.$emailFrom.'",
    953                                             "sendTo":"'.$emailTo.'",
    954                                             "sendToMyself":false,
    955                                             "subject": "Invoice Document of Order '.$reference.'"},
    956                                             "generateOnly":false,
    957                                             "isPreview":false,
    958                                             "outputType":2,
    959                                             "printerId":"",
    960                                             "records":[{"docId":'.$docId.',
    961                                             "entityType":"Ft",
    962                                             "stamp":"'.$ftstamp.'"}],
    963                                             "reportStamp":"'.$repstamp.'",
    964                                             "sendToType":0,"serie":0}');                                       
    965                                
    966                                
    967                                
    968             // Build Http query using params
    969             $this->query = http_build_query ($this->params);
    970         }
    971 
    972         //Header to make logout
    973         public function paramsLogout(){
    974             // build our web service full URL
    975             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    976             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    977             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    978             $this->url = "{$settings['backend']['url']}".$this->extraurl."/REST/UserLoginWS/userLogout";
    979         }
     593        }
     594
     595        public function lockEnd() {
     596                $this->logs->writeFileLog('lockEnd', "Entrei" );
     597            $lockFilePath =  __DIR__.'/logsErrors/tim.lock';
     598            unlink($lockFilePath);
     599            $this->logs->writeFileLog('lockEnd', "Sai" );
     600            return true;
     601        }
     602           
    980603
    981604        /** Order Status **/
     
    1010633        }
    1011634
    1012         //Communicate with FX backend and obtain type of invoice document and type of order
    1013         public function setCommunicationFx () {
    1014         //  $this->lockStart();
     635
     636        //Communicate with FX backend and obtain type of invoice document and type of order
     637        public function setCommunicationFx() {
     638            session_start();
     639       
    1015640            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    1016 
     641            // get Credentials
     642            $credentials = $this->syncro_services->fetchCredentials();     
    1017643            //Obtain configuration to make login
    1018             $this->paramsLogin();
    1019 
     644            $ch = $this->auth_services->PHCLogin($ch, $credentials);       
    1020645            //initial request with login data
    1021             $ch = curl_init();
    1022 
    1023             //URL to save cookie "ASP.NET_SessionId"
    1024             curl_setopt($ch, CURLOPT_URL, $this->url);
    1025             curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    1026             curl_setopt($ch, CURLOPT_POST, true);
    1027             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    1028             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1029             //Parameters passed to POST
    1030 
    1031             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    1032             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    1033             curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    1034             curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    1035             curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
    1036646            $response = curl_exec($ch);
    1037 
    1038647            // send response as JSON
    1039648            $response = json_decode($response, true);
     649            // get the temporary token and insert in credentials object
     650            $credentials->token = $response['result'][0]['token'];
     651
     652            //$this->logs->writeFileLog('Login response_1:', $response);
    1040653
    1041654            if (curl_error($ch)) {
    1042                 $this->writeFileLog('setCommunicationFx', $ch);
     655                $this->logs->writeFileLog('setCommunicationFx', $ch);
    1043656                unset($_SESSION['username']);
    1044657            } else if(empty($response)){
    1045                 $this->writeFileLog('setCommunicationFx', 'EMPTY RESPONSE');
     658                $this->logs->writeFileLog('setCommunicationFx', 'EMPTY RESPONSE');
    1046659                $this->messagesError("Can't connect to webservice!! There's an empty response");
    1047660                unset($_SESSION['username']);
    1048661            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1049                 $this->writeFileLog('setCommunicationFx', $response['messages'][0]['messageCodeLocale']);
     662                $this->logs->writeFileLog('setCommunicationFx', $response['messages'][0]['messageCodeLocale']);
    1050663                $this->messagesError(": Wrong Login! Please check your entered data!");
    1051664                unset($_SESSION['username']);
     
    1089702                  $_SESSION['fieldNif'] .= "<option value='address_2'>Address 2</option><br>";
    1090703                  $_SESSION['fieldNif'] .= "<option value='state'  >State</option><br>";
    1091                    $_SESSION['fieldNif'] .= "<option value='nif' selected >Billing Nif (Plugin)</option><br>";
     704                   $_SESSION['fieldNif'] .= "<option value='nif' selected >Billing Nif (Plugin)</option><br>"; 
     705                }
     706
     707                //Obtain gama of PHC
     708                $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
    1092709               
    1093                
    1094                 }
    1095 
    1096                 //Obtain gama of Drive FX
    1097                 $this->paramsGetBackEndInfo();
    1098 
    1099                 curl_setopt($ch, CURLOPT_URL, $this->url);
    1100                 curl_setopt($ch, CURLOPT_POST, false);
    1101                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1102                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1103                 $response = curl_exec($ch);
    1104                 // send response as JSON
    1105            
    1106                 $response = json_decode($response, true);
     710                //$this->logs->writeFileLog('BackEnd response:', $response);
    1107711
    1108712                if (curl_error($ch)) {
    1109                     $this->writeFileLog('setCommunicationFx2', $ch);
     713                    $this->logs->writeFileLog('setCommunicationFx2', $ch);
    1110714                } else if(empty($response)){
    1111                     $this->writeFileLog('setCommunicationFx2', 'EMPTY RESPONSE');
     715                    $this->logs->writeFileLog('setCommunicationFx2', 'EMPTY RESPONSE');
    1112716                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1113                     $this->writeFileLog('setCommunicationFx2', $response['messages'][0]['messageCodeLocale']);
     717                    $this->logs->writeFileLog('setCommunicationFx2', $response['messages'][0]['messageCodeLocale']);
    1114718                } else {
    1115719                    $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
     
    1117721               
    1118722                //Obtain parameter of manage stock
    1119                 $this->paramsGetFrontendInfo();
    1120 
    1121                 curl_setopt($ch, CURLOPT_URL, $this->url);
    1122                 curl_setopt($ch, CURLOPT_POST, false);
    1123                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1124                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1125                 $response = curl_exec($ch);
    1126                 // send response as JSON
    1127                 $response = json_decode($response, true);
    1128                
     723                $response = $this->utils_services->paramsGetFrontendInfo($ch, $credentials);   
     724
     725                //$this->logs->writeFileLog('FrontEnd response:', $response);
     726
    1129727                if (curl_error($ch)) {
    1130                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', $ch);
     728                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $ch);
    1131729                } else if(empty($response)){
    1132                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', 'EMPTY RESPONSE');
     730                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', 'EMPTY RESPONSE');
    1133731                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1134                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
     732                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
    1135733                } else {
    1136734                    foreach ($response['result'] as $key => $value){
     
    1142740
    1143741                //Obtain type invoices
    1144                 $this->paramsQuery('Td', 'inactivo', 0);
    1145 
    1146                 curl_setopt($ch, CURLOPT_URL, $this->url);
    1147                 curl_setopt($ch, CURLOPT_POST, false);
    1148                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1149                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1150                 $response = curl_exec($ch);
    1151                 // send response as JSON
    1152                 $response = json_decode($response, true);
     742                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Td', 'inactivo', 0);   
     743                       
     744                //$this->logs->writeFileLog('TypeInvoice response:', $response);
    1153745
    1154746                if (curl_error($ch)) {
    1155                     $this->writeFileLog('setCommunicationFx3', $ch);
     747                    $this->logs->writeFileLog('setCommunicationFx3', $ch);
    1156748                } else if(empty($response)){
    1157                     $this->writeFileLog('setCommunicationFx3', 'EMPTY RESPONSE');
     749                    $this->logs->writeFileLog('setCommunicationFx3', 'EMPTY RESPONSE');
    1158750                    $this->messagesError("Can't connect to webservice!! There's an empty response");
    1159751                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1160                     $this->writeFileLog('setCommunicationFx3', $response['messages'][0]['messageCodeLocale']);
     752                    $this->logs->writeFileLog('setCommunicationFx3', $response['messages'][0]['messageCodeLocale']);
    1161753                    $this->messagesError(" obtain dropdown with type of invoices! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
    1162754                } else {
     
    1178770                        }
    1179771                    }
    1180                    
    1181                     //If gama is equal or higher of STAR
     772                    #Obtain tax free reason list
     773                    $response = $this->utils_services->entityName_Query($ch, $credentials, 'Miseimp'); 
     774                                       
     775                    //$this->logs->writeFileLog('Miseimp response:', $response);
     776
     777                    if (curl_error($ch)) {
     778                        $this->logs->writeFileLog('setCommunication3.2', $ch);
     779                    } else if(empty($response)){
     780                        $this->logs->writeFileLog('setCommunication3.2', 'EMPTY RESPONSE');
     781                        $this->messagesError("Can't connect to webservice!! There's an empty response");
     782                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
     783                        $this->logs->writeFileLog('setCommunication3.2', $response['messages'][0]['messageCodeLocale']);
     784                        $this->messagesError(" obtain dropdown with tax free reason list! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
     785                    } else {
     786                        //Create options of dropdownlist reasons list
     787                        $i = 0;
     788                        $typeInvoice = array();
     789                        $_SESSION['typeOfReason'] = '';
     790                       
     791                        foreach ($response['result'] as $key => $value){                       
     792                            if($settings['backend']['typeOfReason'] == $value['codigo']){
     793                                $selected_dropdown = 'selected';
     794                            } else {
     795                                $selected_dropdown = '';
     796                            }
     797                           
     798                            $_SESSION['typeOfReason'] .= "<option value=" . $value['codigo'] . " " . $selected_dropdown . ">" . $value['descricao'] ."</option><br>";         
     799                            ++$i;
     800                        }
     801                    }
     802
     803                    #Obtain services name list
     804                    $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0', 'stns', '1');   
     805                                           
     806                    if (curl_error($ch)) {
     807                        $this->logs->writeFileLog('setCommunication3.2', $ch);
     808                    } else if(empty($response)){
     809                        $this->logs->writeFileLog('setCommunication3.2', 'EMPTY RESPONSE');
     810                        $this->messagesError("Can't connect to webservice!! There's an empty response");
     811                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
     812                        $this->logs->writeFileLog('setCommunication3.2', $response['messages'][0]['messageCodeLocale']);
     813                        $this->messagesError(" obtain dropdown with tax free reason list! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
     814                    } else {
     815                        //Create options of dropdownlist services list for shipping reference
     816                        $i = 0;
     817                        $_SESSION['shippingName'] = '';
     818                       
     819                        foreach ($response['result'] as $key => $value){                       
     820                            if($settings['backend']['shippingName'] == $value['ref']){
     821                                $selected_dropdown = 'selected';
     822                            } else {
     823                                $selected_dropdown = '';
     824                            }
     825                           
     826                            $_SESSION['shippingName'] .= "<option value=" . $value['ref'] . " " . $selected_dropdown . ">" . $value['design'] ."</option><br>";         
     827                            ++$i;
     828                        }
     829                        //Create options of dropdownlist services list for fees reference
     830                        $i = 0;
     831                        $_SESSION['feesName'] = '';
     832                       
     833                        foreach ($response['result'] as $key => $value){                       
     834                            if($settings['backend']['feesName'] == $value['ref']){
     835                                $selected_dropdown = 'selected';
     836                            } else {
     837                                $selected_dropdown = '';
     838                            }
     839                           
     840                            $_SESSION['feesName'] .= "<option value=" . $value['ref'] . " " . $selected_dropdown . ">" . $value['design'] ."</option><br>";         
     841                            ++$i;
     842                        }
     843                    }
     844
     845                    #If gama is equal or higher of STAR
    1182846                    if($_SESSION['gamaDRIVEFX'] >= 9){
    1183                         //Obtain type orders
    1184                         $this->paramsQuery('Ts', 'inactivo', 0);
    1185                         curl_setopt($ch, CURLOPT_URL, $this->url);
    1186                         curl_setopt($ch, CURLOPT_POST, false);
    1187                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1188                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1189                        
    1190                         $response = curl_exec($ch);
    1191                         // send response as JSON
    1192                         $response = json_decode($response, true);
     847                        //Obtain type orders   
     848                        $response = $this->utils_services->doubleFilter($ch, $credentials, 'Ts', 'bdempresas', 'CL', 'trfa', '0'); 
     849                                           
     850                        //$this->logs->writeFileLog('OrderType response:', $response);
    1193851
    1194852                        if (curl_error($ch)) {
    1195                             $this->writeFileLog('setCommunicationFx4', $ch);
     853                            $this->logs->writeFileLog('setCommunicationFx4', $ch);
    1196854                        } else if(empty($response)){
    1197                             $this->writeFileLog('setCommunicationFx4', 'EMPTY RESPONSE');
     855                            $this->logs->writeFileLog('setCommunicationFx4', 'EMPTY RESPONSE');
    1198856                            $this->messagesError("Can't connect to webservice!! There's an empty response");
    1199857                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1200                             $this->writeFileLog('setCommunicationFx4', $response['messages'][0]['messageCodeLocale']);
     858                            $this->logs->writeFileLog('setCommunicationFx4', $response['messages'][0]['messageCodeLocale']);
    1201859                            $this->messagesError(" obtain dropdown with type of documents! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
    1202860                        } else {
     
    1217875                                    } else if ($key == "nmdos"){
    1218876                                        //Obtain type orders
    1219                                         $this->paramsQuery('Bo', 'nmdos', $value);
    1220 
    1221                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    1222                                         curl_setopt($ch, CURLOPT_POST, false);
    1223                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1224                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1225                        
    1226                                         $response2 = curl_exec($ch);
    1227                                         // send response as JSON
    1228                                         $response2 = json_decode($response2, true); 
     877                                        $response2 = $this->utils_services->getInternalDoc($ch, $credentials, 'Bo', 'nmdos', $value);   
     878
     879                                       // $this->logs->writeFileLog('InternalDoc response:', $response2);
    1229880
    1230881                                        if (curl_error($ch)) {
    1231                                           $this->writeFileLog('setCommunicationFx5', $ch);
     882                                          $this->logs->writeFileLog('setCommunicationFx5', $ch);
    1232883                                        } else if(empty($response)){
    1233                                           $this->writeFileLog('setCommunicationFx5', 'EMPTY RESPONSE');
     884                                          $this->logs->writeFileLog('setCommunicationFx5', 'EMPTY RESPONSE');
    1234885                                          $this->messagesError("Can't connect to webservice!! There's an empty response");
    1235886                                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1236                                           $this->writeFileLog('setCommunicationFx5', $response2['messages'][0]['messageCodeLocale']);
     887                                          $this->logs->writeFileLog('setCommunicationFx5', $response2['messages'][0]['messageCodeLocale']);
    1237888                                          $this->messagesError(" obtain dropdown with type of documents! Message from Backend: " . $response2['messages'][0]['messageCodeLocale']);
    1238889                                        } else {
    1239                                             //Put the same number of order in Drive FX
     890                                            //Put the same number of order in PHC
    1240891                                            global $wpdb;
    1241892                                            $table_name = $wpdb->prefix."postmeta";
     
    1265916                   
    1266917                        //Obtain warehouses
    1267                         $this->paramsQuery2('Sa');
    1268                         curl_setopt($ch, CURLOPT_URL, $this->url);
    1269                         curl_setopt($ch, CURLOPT_POST, false);
    1270                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1271                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1272                        
    1273                         $response = curl_exec($ch);
    1274                         // send response as JSON
    1275                         $response = json_decode($response, true);
     918                        $response = $this->utils_services->entityName_Query($ch, $credentials, 'Sa');   
     919
     920                        //$this->logs->writeFileLog('Warehouses response:', $response);
    1276921
    1277922                        if (curl_error($ch)) {
    1278                             $this->writeFileLog('setCommunicationFx6', $ch);
     923                            $this->logs->writeFileLog('setCommunicationFx6', $ch);
    1279924                        } else if(empty($response)){
    1280                           $this->writeFileLog('setCommunicationFx6', 'EMPTY RESPONSE');
     925                          $this->logs->writeFileLog('setCommunicationFx6', 'EMPTY RESPONSE');
    1281926                          $this->messagesError("Can't connect to webservice!! There's an empty response");
    1282927                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1283                             $this->writeFileLog('setCommunicationFx6', $response['messages'][0]['messageCodeLocale']);
     928                            $this->logs->writeFileLog('setCommunicationFx6', $response['messages'][0]['messageCodeLocale']);
    1284929                            $this->messagesError(" obtain dropdown with type of documents! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
    1285930                        } else {
     
    1322967                    if(isset($settings['backend']['typeOfInvoice']) && $settings['backend']['createInvoice'] == 'on' && $settings['backend']['typeOfInvoice'] > 0 && isset($settings['backend']['sendInvoice'])){
    1323968                        //Obtain type invoices
    1324                         $this->paramsGetReportForPrint();
    1325 
    1326                         curl_setopt($ch, CURLOPT_URL, $this->url);
    1327                         curl_setopt($ch, CURLOPT_POST, false);
    1328                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1329                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1330                         $response = curl_exec($ch);
    1331                         // send response as JSON
    1332                         $response = json_decode($response, true);
     969                        $response = $this->utils_services->paramsGetReportForPrint($ch, $credentials); 
     970
     971                        //$this->logs->writeFileLog('ReportPrint response:', $response);
    1333972
    1334973                        if (curl_error($ch)) {
    1335                             $this->writeFileLog('setCommunicationFx8', $ch);
     974                            $this->logs->writeFileLog('setCommunicationFx8', $ch);
    1336975                        } else if(empty($response)){
    1337                             $this->writeFileLog('setCommunicationFx8', 'EMPTY RESPONSE');
     976                            $this->logs->writeFileLog('setCommunicationFx8', 'EMPTY RESPONSE');
    1338977                            $this->messagesError("Can't connect to webservice!! There's an empty response");
    1339978                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1340                             $this->writeFileLog('setCommunicationFx8', $response['messages'][0]['messageCodeLocale']);
     979                            $this->logs->writeFileLog('setCommunicationFx8', $response['messages'][0]['messageCodeLocale']);
    1341980                            $this->messagesError(" in configuration of send email with FT! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
    1342981                        } else {
     
    1355994                            }
    1356995                            //If not exists template as default
    1357                             if($sendEmail == false){
    1358                                 $this->writeFileLog('setCommunicationFx5', 'It is not possible to send email. Please verify your configuration reports of Drive FX');
    1359                                 $this->messagesError(": It is not possible to send email. Please verify your configuration reports of Drive FX because does not exists any default template");
    1360                             }
     996                             if($sendEmail == false){
     997                                $this->logs->writeFileLog('setCommunicationFx5', 'It is not possible to send email. Please verify your configuration reports of PHC');
     998                                $this->messagesError(": It is not possible to send email. Please verify your configuration reports of PHC because does not exists any default template");
     999                            } 
    13611000                        }
    13621001                    }
     
    13641003               
    13651004                //Obtain currency coin of company
    1366                 $this->paramsQuery('E1', 'estab', 0);
    1367                 curl_setopt($ch, CURLOPT_URL, $this->url);
    1368                 curl_setopt($ch, CURLOPT_POST, false);
    1369                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1370                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1371                 $response = curl_exec($ch);
    1372                
    1373                 // send response as JSON
    1374                 $response = json_decode($response, true);
     1005                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);   
     1006                       
     1007                //$this->logs->writeFileLog('E1 response:', $response);
    13751008
    13761009                if (curl_error($ch)) {
    1377                     $this->writeFileLog('setCommunicationFx9', $ch);
     1010                    $this->logs->writeFileLog('setCommunicationFx9', $ch);
    13781011                } else if(empty($response)){
    1379                     $this->writeFileLog('setCommunicationFx9', 'EMPTY RESPONSE');
     1012                    $this->logs->writeFileLog('setCommunicationFx9', 'EMPTY RESPONSE');
    13801013                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1381                     $this->writeFileLog('setCommunicationFx9', $response['messages'][0]['messageCodeLocale']);
     1014                    $this->logs->writeFileLog('setCommunicationFx9', $response['messages'][0]['messageCodeLocale']);
    13821015                } else {
    13831016                    if($response['result'][0]['moeda'] != get_option('woocommerce_currency')){
    1384                         $this->messagesInformation("Please configure currency in shop according to Drive FX");
     1017                        $this->messagesInformation("Please configure currency in shop according to PHC");
    13851018                        unset($_SESSION['username']);
    13861019                    }
     
    13881021            }
    13891022            //Logout
    1390             $this->paramsLogout();
    1391             curl_setopt($ch, CURLOPT_URL, $this->url);
    1392             curl_setopt($ch, CURLOPT_POST, false);
    1393             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1394             $response = curl_exec($ch);
    1395             curl_close ( $ch );
    1396     //      $this->lockEnd();
     1023            $this->auth_services->PHCLogout($ch, $credentials);
     1024           
    13971025        }
    13981026
     
    14011029           
    14021030            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     1031            // get Credentials
     1032            $credentials = $this->syncro_services->fetchCredentials();         
    14031033            //Obtain configuration to make login
    1404             $this->paramsLogin();
     1034            $ch = $this->auth_services->PHCLogin($ch, $credentials);   
    14051035            //initial request with login data
    1406             $ch = curl_init();
    1407             //URL to save cookie "ASP.NET_SessionId"
    1408             curl_setopt($ch, CURLOPT_URL, $this->url);
    1409             curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    1410             curl_setopt($ch, CURLOPT_POST, true);
    1411             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    1412             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1413             //Parameters passed to POST
    1414             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    1415             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    1416             curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    1417             curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    1418             curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
    1419             $response = curl_exec($ch);
     1036            $response = curl_exec($ch); 
    14201037            // send response as JSON
    14211038            $response = json_decode($response, true);
     1039            // get the temporary token and insert in credentials object
     1040            $credentials->token = $response['result'][0]['token'];
     1041
     1042            //$this->logs->writeFileLog('completedOrder Login:', $response);
    14221043
    14231044            if (curl_error($ch)) {
    1424                 $this->writeFileLog('updateTypeOfOrders', $ch);
     1045                $this->logs->writeFileLog('updateTypeOfOrders', $ch);
    14251046            } else if(empty($response)){
    1426                 $this->writeFileLog('updateTypeOfOrders', 'EMPTY RESPONSE');
     1047                $this->logs->writeFileLog('updateTypeOfOrders', 'EMPTY RESPONSE');
    14271048            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1428                 $this->writeFileLog('updateTypeOfOrders', $response['messages'][0]['messageCodeLocale']);
     1049                $this->logs->writeFileLog('updateTypeOfOrders', $response['messages'][0]['messageCodeLocale']);
    14291050            } else {
    14301051                //Obtain type orders
    1431                 $this->paramsQuery('Ts', 'inactivo', 0);
    1432                 curl_setopt($ch, CURLOPT_URL, $this->url);
    1433                 curl_setopt($ch, CURLOPT_POST, false);
    1434                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1435                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1436                    
    1437                 $response = curl_exec($ch);
    1438                 // send response as JSON
    1439                 $response = json_decode($response, true);
     1052                 $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Ts', 'inactivo', 0);   
     1053                   
     1054                 //$this->logs->writeFileLog('OrderType response:', $response);
    14401055           
    14411056                if (curl_error($ch)) {
    1442                     $this->writeFileLog('updateTypeOfOrders2', $ch);
     1057                    $this->logs->writeFileLog('updateTypeOfOrders2', $ch);
    14431058                } else if(empty($response)){
    1444                     $this->writeFileLog('updateTypeOfOrders2', 'EMPTY RESPONSE');
     1059                    $this->logs->writeFileLog('updateTypeOfOrders2', 'EMPTY RESPONSE');
    14451060                    $this->messagesError("Can't connect to webservice!! There's an empty response");
    14461061                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1447                     $this->writeFileLog('updateTypeOfOrders2', $response['messages'][0]['messageCodeLocale']);
     1062                    $this->logs->writeFileLog('updateTypeOfOrders2', $response['messages'][0]['messageCodeLocale']);
    14481063                    $this->messagesError(" obtain dropdown with type of documents! Message from Backend: " . $response['messages'][0]['messageCodeLocale']);
    14491064                } else {
     
    14641079                            } else if ($key == "nmdos"){
    14651080                                //Obtain type orders
    1466                                 $this->paramsQuery('Bo', 'nmdos', $value);
    1467                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    1468                                 curl_setopt($ch, CURLOPT_POST, false);
    1469                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1470                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1471                        
    1472                                 $response2 = curl_exec($ch);
    1473                                 // send response as JSON
    1474                                 $response2 = json_decode($response2, true); 
     1081                                $response2 = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', 'nmdos', $value);
     1082
     1083                                // $this->logs->writeFileLog('Bo response:', $response2);
    14751084
    14761085                                if (curl_error($ch)) {
    1477                                     $this->writeFileLog('updateTypeOfOrders3', $ch);
     1086                                    $this->logs->writeFileLog('updateTypeOfOrders3', $ch);
    14781087                                } else if(empty($response)){
    1479                                     $this->writeFileLog('updateTypeOfOrders3', 'EMPTY RESPONSE');
     1088                                    $this->logs->writeFileLog('updateTypeOfOrders3', 'EMPTY RESPONSE');
    14801089                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1481                                     $this->writeFileLog('updateTypeOfOrders3', $response2['messages'][0]['messageCodeLocale']);
     1090                                    $this->logs->writeFileLog('updateTypeOfOrders3', $response2['messages'][0]['messageCodeLocale']);
    14821091                                } else {
    1483                                     //Put the same number of order in Drive FX
     1092                                    //Put the same number of order in PHC
    14841093                                    global $wpdb;
    14851094                                    $table_name = $wpdb->prefix."postmeta";
     
    14991108                                }
    15001109                               
    1501                                 /*
    1502                                 if($response['result'][$i]['bdempresas'] == 'CL'){
    1503                                     $typeInvoice[$i]["nmdos"] = $value;     
    1504                                 }
    1505                                 */
    15061110                            }
    15071111                        }
     
    15151119            }
    15161120            //Logout
    1517             $this->paramsLogout();
    1518             curl_setopt($ch, CURLOPT_URL, $this->url);
    1519             curl_setopt($ch, CURLOPT_POST, false);
    1520             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1521             $response = curl_exec($ch);
    1522            
    1523         }
    1524 
    1525         //Obtain value of field to Drive FX
     1121            $this->auth_services->PHCLogout($ch, $credentials);     
     1122        }
     1123
     1124        //Obtain value of field to PHC
    15261125        public function statusOfOrder($selectItems, $typeOfOrder){
    15271126           
    15281127            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     1128
     1129            // get Credentials
     1130            $credentials = $this->syncro_services->fetchCredentials();     
    15291131            //Obtain configuration to make login
    1530             $this->paramsLogin();
     1132            $ch = $this->auth_services->PHCLogin($ch, $credentials);
    15311133            //initial request with login data
    1532             $ch = curl_init();
    1533             //URL to save cookie "ASP.NET_SessionId"
    1534             curl_setopt($ch, CURLOPT_URL, $this->url);
    1535             curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    1536             curl_setopt($ch, CURLOPT_POST, true);
    1537             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    1538             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1539             //Parameters passed to POST
    1540             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    1541             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    1542             curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    1543             curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    1544             curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
    1545             $response = curl_exec($ch);
     1134            $response = curl_exec($ch); 
    15461135            // send response as JSON
    15471136            $response = json_decode($response, true);
     1137            // get the temporary token and insert in credentials object
     1138            $credentials->token = $response['result'][0]['token'];
     1139     
     1140            //$this->logs->writeFileLog('completedOrder Login:', $response);
    15481141
    15491142            if (curl_error($ch)) {
    1550                 $this->writeFileLog('statusOfOrder', $ch);
     1143                $this->logs->writeFileLog('statusOfOrder', $ch);
    15511144            } else if(empty($response)){
    1552                 $this->writeFileLog('statusOfOrder', 'EMPTY RESPONSE');
     1145                $this->logs->writeFileLog('statusOfOrder', 'EMPTY RESPONSE');
    15531146            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1554                 $this->writeFileLog('statusOfOrder', $response['messages'][0]['messageCodeLocale']);
     1147                $this->logs->writeFileLog('statusOfOrder', $response['messages'][0]['messageCodeLocale']);
    15551148            } else {
    15561149                //Obtain type invoices
    1557                 $this->paramsQuery4('Ts', $selectItems, $typeOfOrder);
    1558 
    1559                 curl_setopt($ch, CURLOPT_URL, $this->url);
    1560                 curl_setopt($ch, CURLOPT_POST, false);
    1561                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1562                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1563                 $response = curl_exec($ch);
    1564                 // send response as JSON
    1565                 $response = json_decode($response, true);
     1150                $response = $this->utils_services->paramsQuery4($ch, $credentials, 'Ts', $selectItems, $typeOfOrder);   
     1151               
     1152                //$this->logs->writeFileLog('Type Invoices:', $response);
    15661153
    15671154                if (curl_error($ch)) {
    1568                     $this->writeFileLog('statusOfOrder2', $ch);
     1155                    $this->logs->writeFileLog('statusOfOrder2', $ch);
    15691156                } else if(empty($response)){
    1570                     $this->writeFileLog('statusOfOrder2', 'EMPTY RESPONSE');
     1157                    $this->logs->writeFileLog('statusOfOrder2', 'EMPTY RESPONSE');
    15711158                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1572                     $this->writeFileLog('statusOfOrder2', $response['messages'][0]['messageCodeLocale']);
     1159                    $this->logs->writeFileLog('statusOfOrder2', $response['messages'][0]['messageCodeLocale']);
    15731160                } else {
    15741161                    echo $response['result'][0][$selectItems];
     
    15761163            }
    15771164            //Logout
    1578             $this->paramsLogout();
    1579             curl_setopt($ch, CURLOPT_URL, $this->url);
    1580             curl_setopt($ch, CURLOPT_POST, false);
    1581             $response = curl_exec($ch);
    1582            
    1583         }
    1584 
    1585         //Create dropdownlist of names that are presented in Drive FX hardcoded
    1586         public function genericFieldsList($field){
    1587             switch ($field) {
    1588                 case 'nmdesc':
    1589                     $field = 'obranome';
    1590                     break;
    1591                 case 'texto1':
    1592                     $field = 'trab1';
    1593                     break;
    1594                 case 'texto2':
    1595                     $field = 'trab2';
    1596                     break;
    1597                 case 'texto3':
    1598                     $field = 'trab3';
    1599                     break;
    1600                 case 'tmodelo':
    1601                     $field = 'maquina';
    1602                     break;
    1603                 case 'tmarca':
    1604                     $field = 'marca';
    1605                     break;
    1606                 case 'tserie':
    1607                     $field = 'serie';
    1608                     break;
    1609                 default:
    1610                     $field = '';
    1611                     break;
    1612             }
    1613             return $field;
    1614         }
    1615 
    1616         //Add new order in Drive FX
     1165            $this->auth_services->PHCLogout($ch, $credentials);
     1166           
     1167        }
     1168
     1169        //Add new order in Phc Software
    16171170        public function addNewOrder($orderid){
    1618                 $this->lockStart();
    1619                 $this->writeFileLog('addNewOrder', "Entrei" . $orderid);
     1171            $this->lockStart();
     1172            $this->logs->writeFileLog('addNewOrder', "Entrei" . $orderid);
     1173
    16201174            session_start();
    1621             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    1622            
    1623            
    1624             //tera que sair pais tarde
    1625             global $wpdb;
    1626                 $table_name = $wpdb->prefix."postmeta";
    1627                 $query = "SELECT meta_key, meta_value FROM %s where post_id = %d";
    1628                 $docid = $wpdb->get_results(str_replace("'", "", $wpdb->prepare($query, $table_name, sanitize_text_field($orderid))));
    1629 
    1630                 $nifName = '_billing_'.$settings['backend']['fieldNif'];
    1631                
    1632                    
    1633                 foreach ($docid as $key => $value) {
    1634                     if($value->meta_key == '_billing_country'){
    1635                         $_REQUEST['_billing_country'] = $value->meta_value;
    1636                     } else if($value->meta_key == '_billing_first_name') {
    1637                         $_REQUEST['_billing_first_name'] = $value->meta_value;
    1638                     } else if($value->meta_key == '_billing_last_name') {
    1639                         $_REQUEST['_billing_last_name'] = $value->meta_value;
    1640                     } else if($value->meta_key == '_billing_address_1') {
    1641                         $_REQUEST['_billing_address_1'] = $value->meta_value;
    1642                     } else if($value->meta_key == '_billing_city') {
    1643                         $_REQUEST['_billing_city'] = $value->meta_value;
    1644                     } else if($value->meta_key == '_billing_postcode') {
    1645                         $_REQUEST['_billing_postcode'] = $value->meta_value;
    1646                     } else if($value->meta_key == $nifName) {
    1647                         $_REQUEST[$nifName] = $value->meta_value;
    1648                     } else if($value->meta_key == '_billing_email') {
    1649                         $_REQUEST['_billing_email'] = $value->meta_value;
    1650                     } else if($value->meta_key == '_billing_phone') {
    1651                         $_REQUEST['_billing_phone'] = $value->meta_value;
    1652                     } else if($value->meta_key == '_shipping_country') {
    1653                         $_REQUEST['_shipping_country'] = $value->meta_value;
    1654                     } else if($value->meta_key == '_shipping_address_1') {
    1655                         $_REQUEST['_shipping_address_1'] = $value->meta_value;
    1656                     } else if($value->meta_key == '_shipping_city') {
    1657                         $_REQUEST['_shipping_city'] = $value->meta_value;
    1658                     } else if($value->meta_key == '_shipping_postcode') {
    1659                         $_REQUEST['_shipping_postcode'] = $value->meta_value;
    1660                     }
    1661                 }
    1662                
    1663            
    1664             //Obtain configuration to make login
    1665             $this->paramsLogin();
    1666             //initial request with login data
    1667             $ch = curl_init();
    1668             //URL to save cookie "ASP.NET_SessionId"
    1669             curl_setopt($ch, CURLOPT_URL, $this->url);
    1670             curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    1671             curl_setopt($ch, CURLOPT_POST, true);
    1672             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    1673             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1674             //Parameters passed to POST
    1675             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    1676             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    1677             curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    1678             curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    1679             curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
    1680             $response = curl_exec($ch);
    1681             // send response as JSON
    1682             $response = json_decode($response, true);
    1683 
    1684             if (curl_error($ch)) {
    1685                 $this->writeFileLog('addNewOrder', $ch);
    1686             } else if(empty($response)){
    1687                 $this->writeFileLog('addNewOrder', 'EMPTY RESPONSE');
    1688             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1689                 $this->writeFileLog('addNewOrder', $response['messages'][0]['messageCodeLocale']);
    1690             } else {
    1691                 //Obtain gama of Drive FX
    1692                 $this->paramsGetBackEndInfo();
    1693 
    1694                 curl_setopt($ch, CURLOPT_URL, $this->url);
    1695                 curl_setopt($ch, CURLOPT_POST, false);
    1696                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1697                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1698                 $response = curl_exec($ch);
    1699                 // send response as JSON
    1700                 $response = json_decode($response, true);
    1701 
    1702                 if (curl_error($ch)) {
    1703                     $this->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    1704                 } else if(empty($response)){
    1705                     $this->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
    1706                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1707                     $this->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
    1708                 } else {
    1709                     $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
    1710                 }
    1711                    
    1712                    
    1713                
    1714                 if($_SESSION['gamaDRIVEFX'] >= 9) {
    1715                     //Obtain billing country
    1716                     $billing_country = sanitize_text_field( $_REQUEST['billing_country'] );
    1717                     $billing_country_ = sanitize_text_field( $_REQUEST['_billing_country'] );
    1718 
    1719                    
    1720                     if($billing_country != ''){
    1721                         $this->paramsQuery('Countries', 'nomeabrv', $billing_country);
    1722                     }else if($billing_country_ != '') {
    1723                         $this->paramsQuery('Countries', 'nomeabrv', $billing_country_);
    1724                     }else{
    1725                         $this->paramsQuery('Countries', 'nomeabrv', "PT");
    1726                     }
    1727                    
    1728                     if($billing_country=="GB" ){
    1729                         $this->paramsQuery('Countries', 'nomeabrv', "UK");
    1730                     }else if($billing_country_=="GB"){
    1731                         $this->paramsQuery('Countries', 'nomeabrv', "UK");
    1732                     }
    1733                    
    1734                     curl_setopt($ch, CURLOPT_URL, $this->url);
    1735                     curl_setopt($ch, CURLOPT_POST, false);
    1736                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1737                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1738                     $response = curl_exec($ch);
    1739                     $response = json_decode($response, true);
    1740 
    1741                     if (curl_error($ch)) {
    1742                         $this->writeFileLog('addNewOrder2', $ch);
    1743                     } else if(empty($response)){
    1744                         $this->writeFileLog('addNewOrder2', 'EMPTY RESPONSE');
    1745                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1746                         $this->writeFileLog('addNewOrder2', $response['messages'][0]['messageCodeLocale']);
    1747                     } else {
    1748                         $paisesstamp = $response['result'][0]['paisesstamp'];
    1749                         $nomePais = $response['result'][0]['nome'];
    1750                     }
    1751 
    1752                     //Obtain shipping country
    1753                     $shipping_country = sanitize_text_field( $_REQUEST['shipping_country'] );
    1754                     $shipping_country_ = sanitize_text_field( $_REQUEST['_shipping_country'] );
    1755 
    1756                     if($shipping_country != ''){
    1757                         $this->paramsQuery('Countries', 'nomeabrv', $shipping_country);
    1758                     } else if($shipping_country_ != ''){
    1759                         $this->paramsQuery('Countries', 'nomeabrv', $shipping_country_);
    1760                     }else{
    1761                         $this->paramsQuery('Countries', 'nomeabrv', "PT");
    1762                     }
    1763 
    1764                     curl_setopt($ch, CURLOPT_URL, $this->url);
    1765                     curl_setopt($ch, CURLOPT_POST, false);
    1766                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1767                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1768                     $response = curl_exec($ch);
    1769                     $response = json_decode($response, true);
    1770 
    1771                     if (curl_error($ch)) {
    1772                         $this->writeFileLog('addNewOrder3', $ch);
    1773                     } else if(empty($response)){
    1774                         $this->writeFileLog('addNewOrder3', 'EMPTY RESPONSE');
    1775                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1776                         $this->writeFileLog('addNewOrder3', $response['messages'][0]['messageCodeLocale']);
    1777                     } else {
    1778                         $paisesstampShipping = $response['result'][0]['paisesstamp'];
    1779                         $nomePaisShipping = $response['result'][0]['nome'];
    1780                     }
    1781 
    1782                     //Used to verify coin of Drive FX and woocommerce
    1783                     $this->paramsQuery('E1', 'estab', 0);
    1784                     curl_setopt($ch, CURLOPT_URL, $this->url);
    1785                     curl_setopt($ch, CURLOPT_POST, false);
    1786                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1787                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1788                     $response = curl_exec($ch);
    1789                     $response = json_decode($response, true);
    1790 
    1791                     if (curl_error($ch)) {
    1792                         $this->writeFileLog('addNewOrder4', $ch);
    1793                     } else if(empty($response)){
    1794                         $this->writeFileLog('addNewOrder4', 'EMPTY RESPONSE');
    1795                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1796                         $this->writeFileLog('addNewOrder4', $response['messages'][0]['messageCodeLocale']);
    1797                     } else {
    1798                
    1799                         //Verify if currency of shop corresponds to Drive FX
    1800                         if($response['result'][0]['moeda'] == get_option('woocommerce_currency')){
    1801                    
    1802                             $order_received = get_option('woocommerce_checkout_order_received_endpoint');   
    1803                            
    1804                             unset($_SESSION['listOfSku']);
    1805                             unset($_SESSION['listOfQuantity']);
    1806                             unset($_SESSION['listOfValueItem']);           
    1807 
    1808                             if (is_array(WC()->cart->cart_contents)){
    1809                                                        
    1810                
    1811                                 $i = 0;
    1812                                 //Obtain key of wordpress thtat identified the different products in  cart
    1813                                 foreach (WC()->cart->cart_contents as $key => $value){
    1814                                     $productsOrder[$i] = $key;       
    1815                                     ++$i;
    1816                                 }
    1817                                 $i = 0;
    1818                                 $count = count(WC()->cart->cart_contents);
    1819                                
    1820                            
    1821                                 //Wordpress function to obtain information of cart items
    1822                                 while ($i < $count) {
    1823                                     //Obtain info about products in cart
    1824                                     $productData = WC()->cart->cart_contents[$productsOrder[$i]];
    1825                                     //obtain reference items in cart
    1826                                     if($productData['variation_id']!='' && $productData['variation_id'] != 0){
    1827                                         $productReference = wc_get_product( $productData['variation_id'] );
    1828                                     } else {
    1829                                         $productReference = wc_get_product( $productData['product_id'] );
    1830                                     }
    1831 
    1832                                     $sku[$i] = $productReference->get_sku();
    1833                                     //Obtain quantity of the product in cart
    1834                                     $quantity[$i] = $productData['quantity'];
    1835                                     if($settings['backend']['includeTaxonSendCost']=="true")
    1836                                         $valueItem[$i] = $productData['line_total'] + $productData['line_tax'];
    1837                                     else
    1838                                         $valueItem[$i] = $productData['line_total'];
    1839                                     ++$i;
    1840                                 }
    1841                                 //Save items of cart
    1842                                 $_SESSION['listOfSku'] = $sku;
    1843                                 $_SESSION['listOfQuantity'] = $quantity;
    1844                                 $_SESSION['listOfValueItem'] = $valueItem;
    1845                             }                   
    1846                        
    1847                             if(empty($_SESSION['listOfSku'])){
    1848                                 //Obtain id of order and products
    1849                                
    1850                                
    1851                                 $order = new WC_Order($orderid);
    1852                            
    1853                                 $i = 0;
    1854                                
    1855                                 foreach($order->get_items() as $key => $value){
    1856                                    
    1857                                     if($value['variation_id'] != '' && $value['variation_id'] != 0){
    1858                                         $product = new WC_Product_Variation($value['variation_id']);
    1859                                     } else {
    1860                                         $product = new WC_Product($value['product_id']);
    1861                                     }
    1862                                
    1863                                     $sku[$i] = $product->get_sku();
    1864                                     $quantity[$i] = $value['qty'];
    1865                                     if($settings['backend']['includeTaxonSendCost']=="true")
    1866                                         $valueItem[$i] = $value['line_total'] + $value['line_tax'];
    1867                                     else
    1868                                         $valueItem[$i] = $value['line_total'];
    1869                                     ++$i;
    1870                                 }
    1871                                    
    1872                        
    1873                                 //Save items of cart
    1874                                 $_SESSION['listOfSku'] = $sku;
    1875                                 $_SESSION['listOfQuantity'] = $quantity;
    1876                                 $_SESSION['listOfValueItem'] = $valueItem;
    1877                             }
     1175            $credentials = $this->syncro_services->fetchCredentials();
     1176            $wooOrder = $this->syncro_services->fetchOrderData($orderid);
     1177            $prodPack = $this->syncro_services->processProducts($orderid);
     1178            $dataPack = $this->syncro_services->transformWcToPhcData($wooOrder, $prodPack, $ftprodPack);
     1179            $response = $this->orders_services->processOrder($credentials, $dataPack, $this->fieldStatus);
     1180            //add to table postmeta a key of order and stamp of internal document
     1181            add_post_meta($dataPack->order->nextPostId, '_docid', $response['bostamp']);
     1182
     1183            $this->logs->writeFileLog('addNewOrder', "Sai" . $orderid);
     1184            $this->lockEnd();
     1185
     1186            return $response;
     1187
     1188        }
    18781189       
    1879                             //Obtain login of user
    1880                             global $current_user;
    1881                             $tip_button = false;
    1882                            
    1883                             //Verify if client already exists in bd
    1884                             $billing_email_ = sanitize_text_field( $_REQUEST['_billing_email'] );
    1885                             $billing_email = sanitize_text_field( $_REQUEST['billing_email'] );
    1886                             if($billing_email_ == '' && $billing_email == ''){
    1887                                 //Obtain customer ID to obtain email in Woocommerce Users
    1888                                 global $wpdb;
    1889                                 $table_name = $wpdb->prefix."users";
    1890                                 //Obtain next post_id of order in MySQL
    1891                                 $query = "SELECT user_email FROM %s WHERE id = %d";
    1892                                 $docid = $wpdb->get_results(str_replace("'", "", $wpdb->prepare($query, $table_name, sanitize_text_field($_REQUEST['customer_user']))));           
    1893                                 $billing_email = $docid[0]->user_email;
    1894                             }
    1895                                
    1896                             if($current_user->user_email != ''){
    1897                                    
    1898                    
    1899                                 //Verify if client logged exists
    1900                                 if( $billing_email != ''){
    1901                                     $this->paramsQuery('Cl', 'email', $billing_email);
    1902                                 } else if ($billing_email_ != ''){
    1903                                     $this->paramsQuery('Cl', 'email', $billing_email_);
    1904                                 } else {
    1905                                     $tip_button = true;
    1906                                 }
    1907                            
    1908                                 if($tip_button == false){
    1909                                     curl_setopt($ch, CURLOPT_URL, $this->url);
    1910                                     curl_setopt($ch, CURLOPT_POST, false);
    1911                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1912                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1913                                     $response = curl_exec($ch);
    1914                                     $response = json_decode($response, true);       
    1915 
    1916                                     if (curl_error($ch)) {
    1917                                         $this->writeFileLog('addNewOrder5', $ch);
    1918                                     } else if(empty($response)){
    1919                                         $this->writeFileLog('addNewOrder5', 'EMPTY RESPONSE');               
    1920                                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1921                                         $this->writeFileLog('addNewOrder5', $response['messages'][0]['messageCodeLocale']);               
    1922                                     } else {
    1923 
    1924                                         //$this->writeFileLog('ENTROU', $_SESSION);
    1925                            
    1926                                         //Have client in Drive FX
    1927                                         if(is_array($response['result'][0])){
    1928                                            
    1929                                            
    1930                                             //Save number id of client
    1931                                             $_SESSION['nrClient'] = $response['result'][0]['no'];
    1932 
    1933                                             $billing_first_name = sanitize_text_field( $_REQUEST['billing_first_name'] );
    1934                                             $billing_last_name = sanitize_text_field( $_REQUEST['billing_last_name'] );
    1935                                             $billing_address_1 = sanitize_text_field( $_REQUEST['billing_address_1'] );
    1936                                             $billing_city = sanitize_text_field( $_REQUEST['billing_city'] );
    1937                                             $billing_phone = sanitize_text_field( $_REQUEST['billing_phone'] ); 
    1938                                             $billing_postcode = sanitize_text_field( $_REQUEST['billing_postcode'] );
    1939                                             $billing_nif = sanitize_text_field( $_REQUEST['billing_'.$settings['backend']['fieldNif']] );
    1940 
    1941                                             $billing_first_name_ = sanitize_text_field( $_REQUEST['_billing_first_name'] );
    1942                                             $billing_last_name_ = sanitize_text_field( $_REQUEST['_billing_last_name'] );
    1943                                             $billing_address_1_ = sanitize_text_field( $_REQUEST['_billing_address_1'] );
    1944                                             $billing_city_ = sanitize_text_field( $_REQUEST['_billing_city'] );
    1945                                             $billing_phone_ = sanitize_text_field( $_REQUEST['_billing_phone'] ); 
    1946                                             $billing_postcode_ = sanitize_text_field( $_REQUEST['_billing_postcode'] );               
    1947                                             $billing_nif_ = sanitize_text_field( $_REQUEST['_billing_'.$settings['backend']['fieldNif']] );
    1948                                            
    1949                                             //Used in frontend
    1950                                             if($billing_email_ == ''){
    1951                                                 $response['result'][0]['morada'] = $billing_address_1;
    1952                                                 $response['result'][0]['local'] = $billing_city;
    1953                                                 $response['result'][0]['provincia'] = $billing_city;
    1954                                                 $response['result'][0]['telefone'] = $billing_phone;
    1955                                                 $response['result'][0]['codpost'] = $billing_postcode;
    1956                                                 $response['result'][0]['ncont'] = $billing_nif;
    1957                                             } else { //Used in backend
    1958                                                 $response['result'][0]['morada'] = $billing_address_1_;
    1959                                                 $response['result'][0]['local'] = $billing_city_;
    1960                                                 $response['result'][0]['provincia'] = $billing_city_;
    1961                                                 $response['result'][0]['telefone'] = $billing_phone_;
    1962                                                 $response['result'][0]['codpost'] = $billing_postcode_;
    1963                                                 $response['result'][0]['ncont'] = $billing_nif_;
    1964                                             }
    1965                                            
    1966                                             $response['result'][0]['paisesstamp'] = $paisesstamp;
    1967                                             $response['result'][0]['pais'] = $nomePais;
    1968                                             $response['result'][0]['Operation'] = 2;
    1969                                                                                    
    1970                                             //Save data of client in Drive FX
    1971                                             $this->paramsSave('ClWS', $response);
    1972            
    1973                                             curl_setopt($ch, CURLOPT_URL, $this->url);
    1974                                             curl_setopt($ch, CURLOPT_POST, false);
    1975                                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    1976                                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    1977                                             $response = curl_exec($ch);
    1978                                             // send response as JSON
    1979                                             $response = json_decode($response, true);
    1980 
    1981                                             if (curl_error($ch)) {
    1982                                                 $this->writeFileLog('addNewOrder6', $ch);
    1983                                             } else if(empty($response)){
    1984                                                 $this->writeFileLog('addNewOrder6', 'EMPTY RESPONSE');                   
    1985                                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    1986                                                 $this->writeFileLog('addNewOrder6', $response['messages'][0]['messageCodeLocale']);
    1987                                                 if($_SESSION['nrClient'] != ''){
    1988                                                     //Inserted client in bd
    1989                                                     $createClientSuccess = 1;
    1990                                                 }                   
    1991                                             } else {
    1992                                                 //Inserted client in bd
    1993                                                 $createClientSuccess = 1;
    1994                                             }
    1995                                         } else {
    1996                                             //Dont have client in Drive FX
    1997                                            
    1998                                             //Obtain new instance of client
    1999                                             $this->paramsNewInstance('ClWS', 0);
    2000                                             curl_setopt($ch, CURLOPT_URL, $this->url);
    2001                                             curl_setopt($ch, CURLOPT_POST, false);
    2002                                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2003                                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2004                                             $response = curl_exec($ch);
    2005                                             // send response as JSON
    2006                                             $response = json_decode($response, true);
    2007 
    2008                                             if (curl_error($ch)) {
    2009                                                 $this->writeFileLog('addNewOrder7', $ch);
    2010                                             } else if(empty($response)){
    2011                                                 $this->writeFileLog('addNewOrder7', 'EMPTY RESPONSE');                   
    2012                                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2013                                                 $this->writeFileLog('addNewOrder7', $response['messages'][0]['messageCodeLocale']);                   
    2014                                             } else {                 
    2015                                                 //Save number id of client
    2016                                                 $_SESSION['nrClient'] = $response['result'][0]['no'];
    2017 
    2018                                                 $billing_first_name = sanitize_text_field( $_REQUEST['billing_first_name'] );
    2019                                                 $billing_last_name = sanitize_text_field( $_REQUEST['billing_last_name'] );
    2020                                                 $billing_email = sanitize_text_field( $_REQUEST['billing_email'] );
    2021                                                 $billing_address_1 = sanitize_text_field( $_REQUEST['billing_address_1'] );
    2022                                                 $billing_city = sanitize_text_field( $_REQUEST['billing_city'] );
    2023                                                 $billing_phone = sanitize_text_field( $_REQUEST['billing_phone'] ); 
    2024                                                 $billing_postcode = sanitize_text_field( $_REQUEST['billing_postcode'] );
    2025                                                 $billing_nif = sanitize_text_field( $_REQUEST['billing_'.$settings['backend']['fieldNif']] );
    2026                                                
    2027                                                 $billing_first_name_ = sanitize_text_field( $_REQUEST['_billing_first_name'] );
    2028                                                 $billing_last_name_ = sanitize_text_field( $_REQUEST['_billing_last_name'] );
    2029                                                 $billing_email_ = sanitize_text_field( $_REQUEST['_billing_email'] );
    2030                                                 $billing_address_1_ = sanitize_text_field( $_REQUEST['_billing_address_1'] );
    2031                                                 $billing_city_ = sanitize_text_field( $_REQUEST['_billing_city'] );
    2032                                                 $billing_phone_ = sanitize_text_field( $_REQUEST['_billing_phone'] ); 
    2033                                                 $billing_postcode_ = sanitize_text_field( $_REQUEST['_billing_postcode'] );   
    2034                                                 $billing_nif_ = sanitize_text_field( $_REQUEST['_billing_'.$settings['backend']['fieldNif']] );                                                 
    2035 
    2036                                                 //Used in frontend
    2037                                                 if($billing_email_ == ''){
    2038                                                     $response['result'][0]['nome'] = $billing_first_name . " " . $billing_last_name;
    2039                                                     $response['result'][0]['email'] = $billing_email;
    2040                                                     $response['result'][0]['morada'] = $billing_address_1;
    2041                                                     $response['result'][0]['local'] = $billing_city;
    2042                                                     $response['result'][0]['provincia'] = $billing_city;
    2043                                                     $response['result'][0]['telefone'] = $billing_phone;
    2044                                                     $response['result'][0]['codpost'] = $billing_postcode;
    2045                                                     $response['result'][0]['ncont'] = $billing_nif;
    2046                                                 } else { //Used in backend
    2047                                                     $response['result'][0]['nome'] = $billing_first_name_ . " " . $billing_last_name_;
    2048                                                     $response['result'][0]['email'] = $billing_email_;
    2049                                                     $response['result'][0]['morada'] = $billing_address_1_;
    2050                                                     $response['result'][0]['local'] = $billing_city_;
    2051                                                     $response['result'][0]['provincia'] = $billing_city_;
    2052                                                     $response['result'][0]['telefone'] = $billing_phone_;
    2053                                                     $response['result'][0]['codpost'] = $billing_postcode_;
    2054                                                     $response['result'][0]['ncont'] = $billing_nif_;
    2055                                                 }
    2056                                                 $response['result'][0]['paisesstamp'] = $paisesstamp;
    2057                                                 $response['result'][0]['pais'] = $nomePais;
    2058                                                
    2059                                                 $response['result'][0]['preco'] = intval(str_replace('epv', '', $settings['backend']['productPriceColumn']));
    2060                                                
    2061                                                 //Save data of client in Drive FX
    2062                                                 $this->paramsSave('ClWS', $response);
    2063 
    2064                                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    2065                                                 curl_setopt($ch, CURLOPT_POST, false);
    2066                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2067                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2068                                                 $response = curl_exec($ch);
    2069                                                 // send response as JSON
    2070                                                 $response = json_decode($response, true);
    2071 
    2072                                                 if (curl_error($ch)) {
    2073                                                     $this->writeFileLog('addNewOrder8', $ch);
    2074                                                 } else if(empty($response)){
    2075                                                     $this->writeFileLog('addNewOrder8', 'EMPTY RESPONSE');                     
    2076                                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2077                                                     $this->writeFileLog('addNewOrder8', $response['messages'][0]['messageCodeLocale']);
    2078                                                     if($_SESSION['nrClient'] != ''){
    2079                                                         //Inserted client in bd
    2080                                                         $createClientSuccess = 1;
    2081                                                     }                     
    2082                                                 } else {
    2083                                                     //Inserted client in bd
    2084                                                     $createClientSuccess = 1;
    2085                                                 }
    2086                                             }
    2087                                         }
    2088                                     }
    2089                                 }
    2090                            
    2091                             } else {
    2092                            
    2093                                 //Verify if existis generic client
    2094                                 $this->paramsQuery('Cl', 'clivd', '1');
    2095                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    2096                                 curl_setopt($ch, CURLOPT_POST, false);
    2097                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2098                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2099                                 $response = curl_exec($ch);
    2100                                 // send response as JSON
    2101                                 $response = json_decode($response, true);             
    2102 
    2103                                 if (curl_error($ch)) {
    2104                                     $this->writeFileLog('addNewOrder9', $ch);
    2105                                 } else if(empty($response)){
    2106                                     $this->writeFileLog('addNewOrder9', 'EMPTY RESPONSE');             
    2107                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2108                                     $this->writeFileLog('addNewOrder9', $response['messages'][0]['messageCodeLocale']);             
    2109                                 } else { 
    2110                                     //Have generic client
    2111                                     if(is_array($response['result'][0])){
    2112                                         //Save number id of client
    2113                                         $_SESSION['nrClient'] = $response['result'][0]['no'];
    2114                                         //Obtain client from Drive FX
    2115                                         $createClientSuccess = 1;
    2116                                     //Dont have generic client
    2117                                     } else {
    2118                                         //Obtain new instance of client
    2119                                         $this->paramsNewInstance('ClWS', 0);
    2120                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    2121                                         curl_setopt($ch, CURLOPT_POST, false);
    2122                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2123                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2124                                         $response = curl_exec($ch);
    2125                                         // send response as JSON
    2126                                         $response = json_decode($response, true);
    2127 
    2128                                         if (curl_error($ch)) {
    2129                                             $this->writeFileLog('addNewOrder10', $ch);
    2130                                         } else if(empty($response)){
    2131                                             $this->writeFileLog('addNewOrder10', 'EMPTY RESPONSE');
    2132                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2133                                             $this->writeFileLog('addNewOrder10', $response['messages'][0]['messageCodeLocale']);
    2134                                         } else {
    2135                                             $response['result'][0]['nome'] = 'Cliente Genérico';
    2136                                             $response['result'][0]['clivd'] = true;
    2137                                             $response['result'][0]['preco'] = intval(str_replace('epv', '', $settings['backend']['productPriceColumn']));
    2138                                      
    2139                                             //Save number id of client
    2140                                             $_SESSION['nrClient'] = $response['result'][0]['no'];
    2141 
    2142                                             //Save data of client in Drive FX
    2143                                             $this->paramsSave('ClWS', $response);
    2144 
    2145                                             curl_setopt($ch, CURLOPT_URL, $this->url);
    2146                                             curl_setopt($ch, CURLOPT_POST, false);
    2147                                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2148                                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2149                                             $response = curl_exec($ch);
    2150                                             // send response as JSON
    2151                                             $response = json_decode($response, true);
    2152 
    2153                                             if (curl_error($ch)) {
    2154                                                 $this->writeFileLog('addNewOrder11.1', $ch);
    2155                                             } else if(empty($response)){
    2156                                                 $this->writeFileLog('addNewOrder11.1', 'EMPTY RESPONSE');                   
    2157                                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2158                                                 $this->writeFileLog('addNewOrder11.1', $response['messages'][0]['messageCodeLocale']);
    2159                                                 if($_SESSION['nrClient'] != ''){
    2160                                                     //Inserted client in bd
    2161                                                     $createClientSuccess = 1;
    2162                                                 }                   
    2163                                             } else {
    2164                                                 //Inserted client in bd
    2165                                                 $createClientSuccess = 1;
    2166                                             }
    2167                                         }
    2168                                     }
    2169                                 }
    2170                             }
    2171 
    2172                             //If client is created/obtained with success
    2173                             if($createClientSuccess == 1){
    2174                
    2175                                 //If in settings of backoffice is checked option "create invoice"
    2176                                 if($settings['backend']['createInvoice'] == 'on'){
    2177                                     //See if type of order is configured
    2178                                     if(!empty($settings['backend']['typeOfOrder']) && $settings['backend']['typeOfOrder'] != 0){
    2179                                         $post_ID = sanitize_text_field( $_REQUEST['post_ID'] );
    2180            
    2181                                         if($post_ID == ''){
    2182                                             $post_ID = sanitize_text_field( $_REQUEST['order_id'] );
    2183                                         }                                   
    2184                                         //Obtain stamp of internal document based in order
    2185                                         $docid = get_post_meta($post_ID);
    2186                                         $filterItem = "bostamp";
    2187                                         $valueItem = $docid['_docid'][0];
    2188                                        
    2189                                         //Verify if exists in bd
    2190                                         $this->paramsQuery('Bo', $filterItem, $valueItem);
    2191 
    2192                                                                    
    2193                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    2194                                         curl_setopt($ch, CURLOPT_POST, false);
    2195                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2196                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2197                                         $response = curl_exec($ch);
    2198                                         // send response as JSON
    2199                                         $response = json_decode($response, true);   
    2200 
    2201                                         //$this->writeFileLog('master query', $response['result'][0]);
    2202                                        
    2203                                         if (curl_error($ch)) {
    2204                                             $this->writeFileLog('addNewOrder12', $ch);
    2205                                         } else if(empty($response)){
    2206                                             $this->writeFileLog('addNewOrder12', 'EMPTY RESPONSE');                   
    2207                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2208                                             $this->writeFileLog('addNewOrder12', $response['messages'][0]['messageCodeLocale']);                   
    2209                                         } else {
    2210                                            
    2211                                            
    2212                                             //If internal document doesn't exists
    2213                                             if(empty($response['result'][0])){
    2214                                                 //Obtain new instance of Bo
    2215                                                 $this->paramsNewInstance('BoWS', $settings['backend']['typeOfOrder']);
    2216 
    2217                                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    2218                                                 curl_setopt($ch, CURLOPT_POST, false);
    2219                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2220                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2221                                                 $response = curl_exec($ch);
    2222                                                 // send response as JSON
    2223                                                 $response = json_decode($response, true);
    2224 
    2225                                                 if (curl_error($ch)) {
    2226                                                     $this->writeFileLog('addNewOrder13', $ch);
    2227                                                 } else if(empty($response)){
    2228                                                     $this->writeFileLog('addNewOrder13', 'EMPTY RESPONSE');                       
    2229                                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2230                                                     $this->writeFileLog('addNewOrder13', $response['messages'][0]['messageCodeLocale']);                       
    2231                                                 } else {
    2232                                                    
    2233                                                     $response['result'][0]['no'] = $_SESSION['nrClient'];
    2234                                                    
    2235                                                     // build our web service full URL
    2236                                                     $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    2237                                                     $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    2238                                                     $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    2239                                                     $urlBo = $settings['backend']['url'] . $this->extraurl . "/REST/BoWS/actEntity";
    2240                                                     // Create map with request parameters
    2241                                                     $paramsBo =  array ('entity' => json_encode($response['result'][0]),
    2242                                                                         'code' => 0,
    2243                                                                         'newValue' => "{}");
    2244                                                     // Build Http query using params
    2245                                                     $queryBo = http_build_query($paramsBo);
    2246                                                     curl_setopt($ch, CURLOPT_URL, $urlBo);
    2247                                                     curl_setopt($ch, CURLOPT_POST, false);
    2248                                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $queryBo);
    2249                                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2250                                                     $response = curl_exec($ch);
    2251                                                     // send response as JSON
    2252                                                     $response = json_decode($response, true);
    2253                                                    
    2254                                                     if (curl_error($ch)) {
    2255                                                         $this->writeFileLog('addNewOrder13.1', $ch);
    2256                                                     } else if(empty($response)){
    2257                                                         $this->writeFileLog('addNewOrder13.1', 'EMPTY RESPONSE');                         
    2258                                                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2259                                                         $this->writeFileLog('addNewOrder13.1', $response['messages'][0]['messageCodeLocale']);                         
    2260                                                     } else {
    2261                                                    
    2262                                                         //Obtain name and price of delivery
    2263                                                             //Put the same number of order in Drive FX
    2264                                                         global $wpdb;
    2265                                                        
    2266                                                         $table_name = $wpdb->prefix."postmeta";
    2267                                                         //Obtain next post_id of order in MySQL
    2268                                                         $query = "SELECT MAX(post_id) as nextPostId FROM %s";
    2269                                                         $docid = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name)));
    2270 
    2271                                                         if($response['result'][0]['isconfiguredtosign'] == true){
    2272 
    2273                                                             $numberOfOrder = $this->genericFieldsList($settings['backend']['numberOfOrder']);
    2274                                                             if(!empty($numberOfOrder)){
    2275                                                                 $response['result'][0][$numberOfOrder] = $docid->nextPostId;
    2276                                                             }
    2277                                                         }
    2278                                                         else {
    2279                                                            
    2280                                                             $response['result'][0]['obrano'] = $docid->nextPostId;
    2281                                                         }
    2282 
    2283                                                         //get taxes from drive fx
    2284                                                         $url = $settings['backend']['url'] . $this->extraurl . "/REST/SearchWS/QueryAsEntities";
    2285                                                                                                                
    2286                                                                                                                
    2287                                                         $params =  array('itemQuery' => '{"distinct": true,
    2288                                                                                 "groupByItems": [],
    2289                                                                                 "orderByItems": [
    2290                                                                                     {
    2291                                                                                         "OrderItem": "dataini",
    2292                                                                                         "OrderType": 1
    2293                                                                                     }
    2294                                                                                     ],
    2295                                                                                 "SelectItems": [],
    2296                                                                                 "entityName": "TaxasIVA",
    2297                                                                                 "filterItems": [],
    2298                                                                                 "joinEntities": []
    2299                                                                             }'
    2300                                                                     );
    2301                                                        
    2302                                                         $queryActEntity = http_build_query($params);
    2303                                                         curl_setopt($ch, CURLOPT_URL, $url);
    2304                                                         curl_setopt($ch, CURLOPT_POST, false);
    2305                                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2306                                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $queryActEntity);
    2307                                                         curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
    2308                                                         $responseQueryAsEntities = curl_exec($ch);
    2309 
    2310                                                        
    2311                                                         $responseQueryAsEntities = json_decode($responseQueryAsEntities, true);
    2312                                            
    2313                                                            
    2314                                                         $table_name = $wpdb->prefix."woocommerce_order_items";
    2315                                                         $query = "SELECT * FROM %s WHERE order_id = %s and order_item_type = 'shipping'";
    2316                                                         $resultShipping = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $docid->nextPostId)));
    2317                                                        
    2318                                                         //get tax value for shipping
    2319                                                         $table_name = $wpdb->prefix."woocommerce_order_itemmeta";
    2320                                                         $query = "SELECT * FROM %s WHERE order_item_id = %s and meta_key = 'total_tax'";
    2321                                                         $resultTax = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultShipping->order_item_id)));       
    2322    
    2323                                                         $table_name = $wpdb->prefix."woocommerce_order_itemmeta";
    2324                                                         $query = "SELECT * FROM %s WHERE order_item_id = %s and meta_key = 'cost'";
    2325                                                         $resultDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultShipping->order_item_id)));
    2326          
    2327 
    2328                                                         //Obtain VO with updated Bo
    2329                                                         //addNewBIsByRef is obsulet, push Bis to Bo and Then ActEntity
    2330                                                    
    2331                                                         foreach ($_SESSION['listOfSku'] as $key => $value) {
    2332                                                             if($_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0){
    2333                                                                 $bi = new stdClass();
    2334                                                                 $bi->ref = $value;
    2335                                                                 // Da sugestão 139643 - Alterou-se a variável a usar na query, uma vez que em casos que o carrinho possua mais que um item
    2336                                                                 //estamos a passar um array para a query. Como a varia $sku é igual a $_SESSION['listOfSku'], sobre o qual se está a iterar
    2337                                                                 //basta passar para a query a variável $value
    2338                                                                 //$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
    2339                                                                 $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $value ) );
    2340                                                                 $getproducttype = wc_get_product($product_id);
    2341                                                                 $typeproduct = $getproducttype->get_type();
    2342                                                                 if ($typeproduct == 'variation'){
    2343                                                                     if ( $product_id ) $product =  new WC_Product_Variation( $product_id );
    2344                                                                 }
    2345                                                                 else {
    2346                                                                     if ( $product_id ) $product =  new WC_Product( $product_id );
    2347                                                                 }
    2348                                                                 $bi->design = $product->get_name();
    2349                                                                 $response['result'][0]['bis'][] = $bi;
    2350                                                             }
    2351                                                         }
    2352                                         foreach ($_SESSION['listOfSku'] as $key => $value) {   
    2353                                                            
    2354                                                             //shipping
    2355                                                             $bi= new stdClass();
    2356                                                             $bi->design = $resultShipping->order_item_name;
    2357                                                             $bi->qtt = 1;
    2358                                                             $bi->edebito = $bi->ettdeb = $resultDB->meta_value;
    2359                                                             if($settings['backend']['includeTaxonSendCost']=="true") {
    2360                                                                  $bi->ivaincl=true;
    2361                                                             }
    2362                                                                                                                    
    2363 
    2364                                                             // get IVA
    2365                                                             foreach ($responseQueryAsEntities['result'] as $tax) {
    2366                                                             if ($resultTax->total_tax == $tax['taxa'] && 'PT' == $tax['regiao']) {
    2367                                                                         $bi->iva = $tax['taxa'];
    2368                                                                     $bi->tabiva = $tax['codigo'];       
    2369                                                         }
    2370                                                         }
    2371                                                             if($bi->edebito == 0){
    2372                                                                 $bi->qtt = 0;
    2373                                                                 $bi->ivaincl = false;
    2374                                                                 }   
    2375                                                             $response['result'][0]['bis'][]= $bi;       
    2376                                                 }
    2377 
    2378                                               //shipping - OLD version :
    2379                                             /*          $bi= new stdClass();
    2380                                                         $bi->design = $resultShipping->order_item_name;;
    2381                                                         $bi->qtt = 1;
    2382                                                         $bi->edebito = $bi->ettdeb = $resultDB->meta_value;
    2383                                                         if($settings['backend']['includeTaxonSendCost']=="true") {
    2384                                                             $bi->ivaincl=true;
    2385                                                         }
    2386                                                         //TODO get IVA
    2387                                                         if($bi->edebito == 0){
    2388                                                             $bi->qtt = 0;
    2389                                                             $bi->ivaincl = false;
    2390                                                         }   
    2391                                                        
    2392                                                         $response['result'][0]['bis'][]= $bi;  */
    2393                                            
    2394                                                      
    2395                                                        
    2396                                                         $urlBo = $settings['backend']['url'] . $this->extraurl . "/REST/BoWS/actEntity";
    2397                                                         // Create map with request parameters
    2398                                                         $paramsBo =  array ('entity' => json_encode($response['result'][0]),
    2399                                                                             'code' => 0,
    2400                                                                             'newValue' => "{}");
    2401                                                         // Build Http query using params
    2402                                                         $queryBo = http_build_query($paramsBo);
    2403                                                         curl_setopt($ch, CURLOPT_URL, $urlBo);
    2404                                                         curl_setopt($ch, CURLOPT_POST, false);
    2405                                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $queryBo);
    2406                                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2407                                                         $response = curl_exec($ch);
    2408                                                         // send response as JSON
    2409                                                        
    2410                                                         $response = json_decode($response, true);
    2411                                                        
    2412                                                        
    2413                                                
    2414                                                        
    2415                                                        
    2416                                                         //$this->writeFileLog('addNewOrder14.0',  $response['result'][0]);
    2417                                                         /*$this->paramsNewInstanceByRef('BoWS', 'addNewBIsByRef', 'IdBoStamp', 'biStampEditing', $response['result'][0]['bostamp'], $_SESSION['listOfSku']);
    2418                                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    2419                                                         curl_setopt($ch, CURLOPT_POST, false);
    2420                                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2421                                                         $response = curl_exec($ch);
    2422                                                         // send response as JSON
    2423                                                         $response = json_decode($response, true); */
    2424 
    2425                                                         if (curl_error($ch)) {
    2426                                                             $this->writeFileLog('addNewOrder14', $ch);
    2427                                                         } else if(empty($response)){
    2428                                                             $this->writeFileLog('addNewOrder14', 'EMPTY RESPONSE');                         
    2429                                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2430                                                             $this->writeFileLog('addNewOrder14', $response['messages'][0]['messageCodeLocale']);                         
    2431                                                         } else {
    2432                                                            
    2433                                                            
    2434                                                            
    2435                                                                
    2436                                                             //Obtain VO with updated Bi and Bo
    2437                                                             //Update list of Quantity
    2438                                                             if (is_array($_SESSION['listOfQuantity'])){
    2439                                                                 foreach ($_SESSION['listOfQuantity'] as $key => $value){
    2440                                                                    
    2441                                                                     if( $_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0 && $response['result'][0]['bis'][$key]['qtt'] != $value){
    2442                                                                         $response['result'][0]['bis'][$key]['qtt'] = $value;
    2443                                                                     }
    2444                                                                 }
    2445                                                             }
    2446 
    2447                                                             //Update list of Value Item
    2448                                                             if (is_array($_SESSION['listOfValueItem'])){
    2449                                                               foreach ($_SESSION['listOfValueItem'] as $key => $value){
    2450                                                                 if( $_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0 && $response['result'][0]['bis'][$key]['ettdeb'] != $value){
    2451                                                                   $response['result'][0]['bis'][$key]['ettdeb'] = $value;
    2452                                                                 }
    2453                                                               }
    2454                                                             }
    2455                                                            
    2456                                                            
    2457                                                             //Eliminate comercial discount
    2458                                                             if (is_array($_SESSION['listOfSku'])){
    2459                                                                 foreach ($_SESSION['listOfSku'] as $key => $value){
    2460                                                                  if( $_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0){
    2461                                                                     //Eliminate discount in field "desconto"
    2462                                                                     $response['result'][0]['bis'][$key]['desconto'] = 0;
    2463                                                                     //Eliminate discount in field "desconto"
    2464                                                                     $response['result'][0]['bis'][$key]['desc2'] = 0;
    2465                                                                     //Eliminate discount in field "desc2"
    2466                                                                     $response['result'][0]['bis'][$key]['desc2'] = 0;
    2467                                                                     //Eliminate discount in field "desc3"
    2468                                                                     $response['result'][0]['bis'][$key]['desc3'] = 0;
    2469                                                                     //Eliminate discount in field "desc4"
    2470                                                                     $response['result'][0]['bis'][$key]['desc4'] = 0;
    2471                                                                     //Eliminate discount in field "desc5"
    2472                                                                     $response['result'][0]['bis'][$key]['desc5'] = 0;
    2473                                                                     //Eliminate discount in field "desc6"
    2474                                                                     $response['result'][0]['bis'][$key]['desc6'] = 0;
    2475                                                                     //Eliminate discount in field "desc6"
    2476                                                                     $response['result'][0]['bis'][$key]['desc6'] = 0;
    2477                                                                  }
    2478                                                                 }
    2479                                                             }
    2480                                                            
    2481                            
    2482                                                    
    2483                                                         /* 
    2484                                                             foreach ($_SESSION['listOfSku'] as $key => $value){
    2485                                                                 if($_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]==0){
    2486                                                                     unset( $response['result'][0]['bis'][$key] );
    2487            
    2488            
    2489                                                                 }
    2490 
    2491                                                             }
    2492                                                             */
    2493                                                            
    2494                                                         //  print_r($response['result'][0]['bis'] );
    2495                                                            
    2496                                                            
    2497                                                         //  $response['result'][0]['bis'] = array_values( $response['result'][0]['bis'] );
    2498                                                             //If VO yet exists
    2499                                                            
    2500                                                            
    2501                                                         //  print_r($response['result'][0]['bis'] );
    2502                                                            
    2503                                                            
    2504                                                            
    2505                                                             if(isset($response['result'][0])){
    2506                                                                 //Obtain field in Drive FX to put status order
    2507                                                                 $statusOrderShop = $this->genericFieldsList($settings['backend']['statusOfOrder']);
    2508                                                                 if(!empty($statusOrderShop)){
    2509                                                                     $response['result'][0][$statusOrderShop] = $this->fieldStatus;
    2510                                                                 }
    2511                                                                
    2512                                                                
    2513                                                                 /*para ir buscar o tipo de envio*/
    2514                                                                 $post = get_post( $_REQUEST['shipping_method'][0] );
    2515 
    2516                                                                 $title = isset( $post->post_title ) ? $post->post_title : '';
    2517                                                                 $response['result'][0]['trab1']= $title;
    2518                                                                 $response['result'][0]['edescc']=WC()->cart->coupon_discount_amounts['saco'];
    2519 
    2520                                                                 /*notas de cliente*/
    2521                                                                 $response['result'][0]['obs']= $_REQUEST['order_comments'] ;
    2522                    
    2523                                                                 $response['result'][0]['paisesstampto'] = $paisesstampShipping;
    2524                                                                 $response['result'][0]['paisto'] = $nomePaisShipping;
    2525                    
    2526                                                                 $shipping_address_1 = sanitize_text_field( $_REQUEST['shipping_address_1'] );
    2527                                                                 $shipping_address_1_ = sanitize_text_field( $_REQUEST['_shipping_address_1'] );
    2528 
    2529                                                                 if($shipping_address_1 != ''){
    2530                                                                     $response['result'][0]['moradato'] = $shipping_address_1;
    2531                                                                 } else if ($shipping_address_1_ != ''){
    2532                                                                     $response['result'][0]['moradato'] = $shipping_address_1_;
    2533                                                                 }   
    2534 
    2535                                                                 $shipping_city = sanitize_text_field( $_REQUEST['shipping_city'] );
    2536                                                                 $shipping_city_ = sanitize_text_field( $_REQUEST['_shipping_city'] );
    2537 
    2538                                                                 if($shipping_city != ''){
    2539                                                                     $response['result'][0]['localto'] = $shipping_city;
    2540                                                                 } else if ($shipping_city_ != ''){
    2541                                                                     $response['result'][0]['localto'] = $shipping_city_;
    2542                                                                 }
    2543 
    2544                                                                 $shipping_postcode = sanitize_text_field( $_REQUEST['shipping_postcode'] );
    2545                                                                 $shipping_postcode_ = sanitize_text_field( $_REQUEST['_shipping_postcode'] );
    2546 
    2547                                                                 if($shipping_postcode != ''){
    2548                                                                     $response['result'][0]['codpostto'] = $shipping_postcode;
    2549                                                                 } else if ($shipping_postcode_ != ''){
    2550                                                                     $response['result'][0]['codpostto'] = $shipping_postcode_;
    2551                                                                 }
    2552 
    2553                                                                 $billing_address_1 = sanitize_text_field( $_REQUEST['billing_address_1'] );
    2554                                                                 $billing_city = sanitize_text_field( $_REQUEST['billing_city'] );
    2555                                                                 $billing_phone = sanitize_text_field( $_REQUEST['billing_phone'] ); 
    2556                                                                 $billing_postcode = sanitize_text_field( $_REQUEST['billing_postcode'] );
    2557                                                                 $billing_nif = sanitize_text_field( $_REQUEST['billing_'.$settings['backend']['fieldNif']] );
    2558 
    2559                                                                 $billing_address_1_ = sanitize_text_field( $_REQUEST['_billing_address_1'] );
    2560                                                                 $billing_city_ = sanitize_text_field( $_REQUEST['_billing_city'] );
    2561                                                                 $billing_phone_ = sanitize_text_field( $_REQUEST['_billing_phone'] ); 
    2562                                                                 $billing_postcode_ = sanitize_text_field( $_REQUEST['_billing_postcode'] );     
    2563                                                                 $billing_nif_ = sanitize_text_field( $_REQUEST['_billing_'.$settings['backend']['fieldNif']] );                                                             
    2564 
    2565                                                                
    2566                                                                
    2567                                                                
    2568                                                                 //Used in frontend
    2569                                                                 if($billing_email_ == ''){
    2570                                                                     $response['result'][0]['morada'] = $billing_address_1;
    2571                                                                     $response['result'][0]['local'] = $billing_city;
    2572                                                                     $response['result'][0]['provincia'] = $billing_city;
    2573                                                                     $response['result'][0]['telefone'] = $billing_phone;
    2574                                                                     $response['result'][0]['codpost'] = $billing_postcode;
    2575                                                                     $response['result'][0]['ncont'] = $billing_nif;
    2576                                                                 } else { //Used in backend
    2577                                                                     $response['result'][0]['morada'] = $billing_address_1_;
    2578                                                                     $response['result'][0]['local'] = $billing_city_;
    2579                                                                     $response['result'][0]['provincia'] = $billing_city_;
    2580                                                                     $response['result'][0]['telefone'] = $billing_phone_;
    2581                                                                     $response['result'][0]['codpost'] = $billing_postcode_;
    2582                                                                     $response['result'][0]['ncont'] = $billing_nif_;
    2583                                                                 }
    2584                                                                
    2585                                                                
    2586                                                                 //get taxes from drive fx
    2587                                                                 $url = $settings['backend']['url'] . $this->extraurl . "/REST/SearchWS/QueryAsEntities";
    2588                                                                
    2589                                                                
    2590                                                                 $params =  array('itemQuery' => '{"distinct": true,
    2591                                                                                         "groupByItems": [],
    2592                                                                                         "orderByItems": [
    2593                                                                                             {
    2594                                                                                               "OrderItem": "dataini",
    2595                                                                                               "OrderType": 1
    2596                                                                                             }
    2597                                                                                           ],
    2598                                                                                         "SelectItems": [],
    2599                                                                                         "entityName": "TaxasIVA",
    2600                                                                                         "filterItems": [],
    2601                                                                                         "joinEntities": []
    2602                                                                                     }'
    2603                                                                             );
    2604                                                                
    2605                                                                 $queryActEntity = http_build_query($params);
    2606                                                                 curl_setopt($ch, CURLOPT_URL, $url);
    2607                                                                 curl_setopt($ch, CURLOPT_POST, false);
    2608                                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2609                                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $queryActEntity);
    2610                                                                 curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
    2611                                                                 $responseQueryAsEntities = curl_exec($ch);
    2612 
    2613                                                                
    2614                                                                 $responseQueryAsEntities = json_decode($responseQueryAsEntities, true);
    2615 
    2616                                                                
    2617                                                                 if (is_array($_SESSION['listOfSku'])){
    2618                                                                     foreach ($_SESSION['listOfSku'] as $key => $value){
    2619                                                                          if( $_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0){
    2620                                                                             //get product id from sku
    2621                                                                             $getProductId = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $value ) );
    2622                                                                            
    2623                                                                             //get product From id
    2624                                                                             $getProduct = wc_get_product($getProductId);
    2625                                                                            
    2626                                                                             //get product tax rate 
    2627                                                                             $getProductTax = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate FROM ".$wpdb->prefix."woocommerce_tax_rates WHERE tax_rate_class='%s' LIMIT 1", $getProduct->get_tax_class() ) );
    2628                                                                             //get product tax rate country
    2629                                                                             $getTaxCountry = $wpdb->get_var( $wpdb->prepare( "SELECT tax_rate_country FROM ".$wpdb->prefix."woocommerce_tax_rates WHERE tax_rate_class='%s' LIMIT 1", $getProduct->get_tax_class() ) );
    2630                                                                    
    2631                                                                             foreach ($responseQueryAsEntities['result'] as $tax) {
    2632                                                                                
    2633                                                                                  If ($getProductTax == $tax['taxa'] && $getTaxCountry == $tax['regiao'] ) {
    2634                                                                                     $response['result'][0]['bis'][$key]['iva'] = $tax['taxa'];
    2635                                                                                     $response['result'][0]['bis'][$key]['tabiva'] = $tax['codigo'];
    2636                                                                                    
    2637                                                                                     break;
    2638                                                                                  }
    2639                                                                             }
    2640                                                                            
    2641                                                                         }
    2642                                                                     }
    2643                                                                 }
    2644                                                                
    2645                                                                
    2646                                                                 $urlActEntity = $settings['backend']['url'] . $this->extraurl . "/REST/BoWS/actEntity";
    2647                                                                 // Create map with request parameters
    2648                                                                
    2649                                                                 $paramsActEntity =  array ('entity' => json_encode($response['result'][0]),
    2650                                                                                 'code' => 0,
    2651                                                                                 'newValue' => "{}");
    2652                                                                 // Build Http query using params
    2653                                                            
    2654                                                        
    2655                                                                 $queryActEntity = http_build_query($paramsActEntity);
    2656                                                                 curl_setopt($ch, CURLOPT_URL, $urlActEntity);
    2657                                                                 curl_setopt($ch, CURLOPT_POST, false);
    2658                                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $queryActEntity);
    2659                                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2660                                                                 $response = curl_exec($ch);
    2661                                                                 // send response as JSON
    2662                                                                 $response = json_decode($response, true);
    2663                
    2664                                                                 if (curl_error($ch)) {
    2665                                                                     $this->writeFileLog('addNewOrder14.1', $ch);
    2666                                                                 } else if(empty($response)){
    2667                                                                     $this->writeFileLog('addNewOrder14.1', 'EMPTY RESPONSE');
    2668                                                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2669                                                                     $this->writeFileLog('addNewOrder14.1', $response['messages'][0]['messageCodeLocale']);
    2670                                                                 } else {
    2671                                                                
    2672                                                                     //Insert
    2673                                                                     $response['result'][0]['Operation'] = 1;
    2674 
    2675                                                                     //Put the same number of order in Drive FX if document is not of type SAFT
    2676 
    2677                                                                     global $wpdb;
    2678                                                                     $table_name = $wpdb->prefix."postmeta";
    2679                                                                     //Obtain next post_id of order in MySQL
    2680                                                                     $query = "SELECT MAX(post_id) as nextPostId FROM %s";
    2681                                                                     $docid = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name)));
    2682 
    2683 
    2684                                                                     if($response['result'][0]['isconfiguredtosign'] == true){
    2685 
    2686                                                                         $numberOfOrder = $this->genericFieldsList($settings['backend']['numberOfOrder']);
    2687                                                                         if(!empty($numberOfOrder)){
    2688                                                                             $response['result'][0][$numberOfOrder] = $docid->nextPostId;
    2689                                                                         }
    2690                                                                     }
    2691                                                                     else {                                                                     
    2692                                                                         $response['result'][0]['obrano'] = $docid->nextPostId;
    2693                                                                     }
    2694 
    2695                                                                    
    2696                                                          
    2697                                                                     //Save internal document
    2698                                                                     $this->paramsSave('BoWS', $response);
    2699                                                                     curl_setopt($ch, CURLOPT_URL, $this->url);
    2700                                                                     curl_setopt($ch, CURLOPT_POST, false);
    2701                                                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2702                                                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2703                                                                     $response = curl_exec($ch);
    2704                                                                     // send response as JSON
    2705                                                                     $response = json_decode($response, true);
    2706                                                            
    2707                                                                     if (curl_error($ch)) {
    2708                                                                         $this->writeFileLog('addNewOrder15', $ch);
    2709                                                                     } else if(empty($response)){
    2710                                                                         $this->writeFileLog('addNewOrder15', 'EMPTY RESPONSE');                             
    2711                                                                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2712                                                                         $this->writeFileLog('addNewOrder15', $response['messages'][0]['messageCodeLocale']);
    2713                                                                     } else {
    2714                                                                         $response['result'][0]['paisesstampto'] = $paisesstampShipping;
    2715                                                                         $response['result'][0]['paisto'] = $nomePaisShipping;
    2716 
    2717                                                                         $shipping_address_1 = sanitize_text_field( $_REQUEST['shipping_address_1'] );
    2718                                                                         $shipping_address_1_ = sanitize_text_field( $_REQUEST['_shipping_address_1'] );
    2719 
    2720                                                                         if($shipping_address_1 != ''){
    2721                                                                             $response['result'][0]['moradato'] = $shipping_address_1;
    2722                                                                         } else if ($shipping_address_1_ != ''){
    2723                                                                             $response['result'][0]['moradato'] = $shipping_address_1_;
    2724                                                                         }     
    2725 
    2726                                                                         $shipping_city = sanitize_text_field( $_REQUEST['shipping_city'] );
    2727                                                                         $shipping_city_ = sanitize_text_field( $_REQUEST['_shipping_city'] );
    2728 
    2729                                                                         if($shipping_city != ''){
    2730                                                                             $response['result'][0]['localto'] = $shipping_city;
    2731                                                                         } else if ($shipping_city_ != ''){
    2732                                                                             $response['result'][0]['localto'] = $shipping_city_;
    2733                                                                         }
    2734 
    2735                                                                         $shipping_postcode = sanitize_text_field( $_REQUEST['shipping_postcode'] );
    2736                                                                         $shipping_postcode_ = sanitize_text_field( $_REQUEST['_shipping_postcode'] );
    2737 
    2738                                                                         if($shipping_postcode != ''){
    2739                                                                             $response['result'][0]['codpostto'] = $shipping_postcode;
    2740                                                                         } else if ($shipping_postcode_ != ''){
    2741                                                                             $response['result'][0]['codpostto'] = $shipping_postcode_;
    2742                                                                         }
    2743                                                                         //Update
    2744                                                                         $response['result'][0]['Operation'] = 2;
    2745 
    2746                                                                         //Save internal document
    2747                                                                         $this->paramsSave('BoWS', $response);
    2748                                                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    2749                                                                         curl_setopt($ch, CURLOPT_POST, false);
    2750                                                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2751                                                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2752                                                                         $response = curl_exec($ch);
    2753                                                                         // send response as JSON
    2754                                                                         $response = json_decode($response, true);
    2755 
    2756                                                                         if (curl_error($ch)) {
    2757                                                                             $this->writeFileLog('addNewOrder16', $ch);
    2758                                                                         } else if(empty($response)){
    2759                                                                             $this->writeFileLog('addNewOrder16', 'EMPTY RESPONSE');                               
    2760                                                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2761                                                                             $this->writeFileLog('addNewOrder16', $response['messages'][0]['messageCodeLocale']);                               
    2762                                                                         } else {
    2763                                                                             $response = $response['result'][0];                                                                         
    2764 
    2765                                                                             if($response['isconfiguredtosign'] == true && $response['draftRecord'] == 1 && $settings['backend']['toSignOrder'] == 'on'){
    2766 
    2767                                                                                 $this->paramsSignOrder($response['bostamp']);
    2768                                                                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    2769                                                                                 curl_setopt($ch, CURLOPT_POST, false);
    2770                                                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2771                                                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2772                                                                                 $response = curl_exec($ch);
    2773                                                                                 // send response as JSON
    2774                                                                                 $response = json_decode($response, true);
    2775 
    2776                                                                                 if (curl_error($ch)) {
    2777                                                                                     $this->writeFileLog('addNewOrder17', $ch);
    2778                                                                                 } else if(empty($response)){
    2779                                                                                     $this->writeFileLog('addNewOrder17', 'EMPTY RESPONSE');                               
    2780                                                                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2781                                                                                     $this->writeFileLog('addNewOrder17', $response['messages'][0]['messageCodeLocale']);                               
    2782                                                                                 } else {
    2783                                                                                     $response = $response['result'][0];
    2784                                                                                     $this->writeFileLog('addNewOrder17', "Signed document " . $response['obrano'] );   
    2785                                                                                 }
    2786                                                                             }
    2787 
    2788                                                                             global $wpdb;
    2789                                                                             $table_name = $wpdb->prefix."postmeta";
    2790                                                                             //Obtain next post_id of order in MySQL
    2791                                                                             $query = "SELECT MAX(post_id) as nextPostId FROM %s";
    2792                                                                             $docid = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name)));
    2793 
    2794                                                                             //add to table postmeta a key of order and stamp of internal document
    2795                                                                             add_post_meta($docid->nextPostId, '_docid', $response['bostamp']);
    2796 
    2797                                                                             //Save data of Bo to save FT
    2798                                                                             $_SESSION['responseBo'] = $response;
    2799                                                                         }   
    2800                                                                     }
    2801                                                                 }
    2802                                                             }
    2803                                                         }
    2804                                                     }
    2805                                                 }
    2806                                             //If internal document exists in system
    2807                                             } else if($response['result'][0]['isconfiguredtosign'] == false || ($response['result'][0]['isconfiguredtosign'] == true &&
    2808                                     $response['result'][0]['draftRecord'] == 1)) {
    2809                                
    2810                                                 $billing_email_ = sanitize_text_field( $_REQUEST['_billing_email'] );
    2811                                                 $billing_first_name_ = sanitize_text_field( $_REQUEST['_billing_first_name'] );
    2812                                                 $billing_last_name_ = sanitize_text_field( $_REQUEST['_billing_last_name'] );
    2813                                                 $billing_address_1_ = sanitize_text_field( $_REQUEST['_billing_address_1'] );
    2814                                                 $billing_city_ = sanitize_text_field( $_REQUEST['_billing_city'] );
    2815                                                 $billing_phone_ = sanitize_text_field( $_REQUEST['_billing_phone'] ); 
    2816                                                 $billing_postcode_ = sanitize_text_field( $_REQUEST['_billing_postcode'] );
    2817                                                 $billing_nif_ = sanitize_text_field( $_REQUEST['_billing_'.$settings['backend']['fieldNif']] );
    2818 
    2819                                                 $billing_first_name = sanitize_text_field( $_REQUEST['billing_first_name'] );
    2820                                                 $billing_last_name = sanitize_text_field( $_REQUEST['billing_last_name'] );
    2821                                                 $billing_email = sanitize_text_field( $_REQUEST['billing_email'] );
    2822                                                 $billing_address_1 = sanitize_text_field( $_REQUEST['billing_address_1'] );
    2823                                                 $billing_city = sanitize_text_field( $_REQUEST['billing_city'] );
    2824                                                 $billing_phone = sanitize_text_field( $_REQUEST['billing_phone'] ); 
    2825                                                 $billing_postcode = sanitize_text_field( $_REQUEST['billing_postcode'] );
    2826                                                 $billing_nif = sanitize_text_field( $_REQUEST['billing_'.$settings['backend']['fieldNif']] );
    2827 
    2828                                                 //Used in frontend
    2829                                                 if($billing_email_ == ''){
    2830                                                     $response['result'][0]['nome2'] = $billing_first_name . " " . $billing_last_name;
    2831                                                     $response['result'][0]['email'] = $billing_email;
    2832                                                     $response['result'][0]['morada'] = $billing_address_1;
    2833                                                     $response['result'][0]['local'] = $billing_city;
    2834                                                     $response['result'][0]['provincia'] = $billing_city;
    2835                                                     $response['result'][0]['telefone'] = $billing_phone;
    2836                                                     $response['result'][0]['codpost'] = $billing_postcode;
    2837                                                     $response['result'][0]['ncont'] = $billing_nif;
    2838                                                 } else { //Used in backend
    2839                                                     $response['result'][0]['nome2'] = $billing_first_name_ . " " . $billing_last_name_;
    2840                                                     $response['result'][0]['email'] = $billing_email_;
    2841                                                     $response['result'][0]['morada'] = $billing_address_1_;
    2842                                                     $response['result'][0]['local'] = $billing_city_;
    2843                                                     $response['result'][0]['provincia'] = $billing_city_;
    2844                                                     $response['result'][0]['telefone'] = $billing_phone_;
    2845                                                     $response['result'][0]['codpost'] = $billing_postcode_;
    2846                                                     $response['result'][0]['ncont'] = $billing_nif_;
    2847                                                 }
    2848                                                 $response['result'][0]['pais'] = $nomePais;
    2849                                                 $response['result'][0]['paisesstamp'] = $paisesstamp;   
    2850 
    2851                                                 $result['result'][0]['paisesstampfrom'] = $paisesstampShipping;
    2852                                                 $result['result'][0]['paisto'] = $nomePaisShipping;
    2853 
    2854                                                 $shipping_address_1 = sanitize_text_field( $_REQUEST['shipping_address_1'] );
    2855                                                 $shipping_address_1_ = sanitize_text_field( $_REQUEST['_shipping_address_1'] );
    2856 
    2857                                                 if($shipping_address_1 != ''){
    2858                                                     $result['result'][0]['moradato'] = $shipping_address_1;
    2859                                                 } else if ($shipping_address_1_ != ''){
    2860                                                     $result['result'][0]['moradato'] = $shipping_address_1_;
    2861                                                 }
    2862 
    2863                                                 $shipping_city = sanitize_text_field( $_REQUEST['shipping_city'] );
    2864                                                 $shipping_city_ = sanitize_text_field( $_REQUEST['_shipping_city'] );
    2865 
    2866                                                 if($shipping_city != ''){
    2867                                                     $result['result'][0]['localto'] = $shipping_city;
    2868                                                 } else if ($shipping_city_ != ''){
    2869                                                     $result['result'][0]['localto'] = $shipping_city_;
    2870                                                 }
    2871 
    2872                                                 $shipping_postcode = sanitize_text_field( $_REQUEST['shipping_postcode'] );
    2873                                                 $shipping_postcode_ = sanitize_text_field( $_REQUEST['_shipping_postcode'] );
    2874 
    2875                                                 if($shipping_postcode != ''){
    2876                                                     $result['result'][0]['codpostto'] = $shipping_postcode;
    2877                                                 } else if ($shipping_postcode_ != ''){
    2878                                                     $result['result'][0]['codpostto'] = $shipping_postcode_;
    2879                                                 }
    2880 
    2881                                                 //Obtain VO with updated Bi and Bo
    2882                                                 if (is_array($_SESSION['listOfQuantity'])){
    2883                                                     foreach ($_SESSION['listOfQuantity'] as $key => $value){
    2884                                                         if($response['result'][0]['bis'][$key]['qtt'] != $value){
    2885                                                             // build our web service full URL
    2886                                                             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    2887                                                             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    2888                                                             $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    2889                                                             $urlBi = $settings['backend']['url'] . $this->extraurl . "/REST/BoWS/actEntity";
    2890                                                             // Create map with request parameters
    2891                                                             $paramsBi =  array ('entity' => json_encode($response['result'][0]),
    2892                                                                                 'code' => 0,
    2893                                                                                 'newValue' => "{}");
    2894                                                             // Build Http query using params
    2895                                                             $queryBi = http_build_query($paramsBi);
    2896                                                             curl_setopt($ch, CURLOPT_URL, $urlBi);
    2897                                                             curl_setopt($ch, CURLOPT_POST, false);
    2898                                                             curl_setopt($ch, CURLOPT_POSTFIELDS, $queryBi);
    2899                                                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2900                                                             $response = curl_exec($ch);
    2901                                                             // send response as JSON
    2902                                                             $response = json_decode($response, true);         
    2903 
    2904                                                             if (curl_error($ch)) {
    2905                                                                 $this->writeFileLog('addNewOrder11', $ch);
    2906                                                             } else if(empty($response)){
    2907                                                                 $this->writeFileLog('addNewOrder11', 'EMPTY RESPONSE');
    2908                                                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2909                                                                 $this->writeFileLog('addNewOrder11', $response['messages'][0]['messageCodeLocale']);
    2910                                                             }
    2911                                                         }
    2912                                                     }
    2913                                                 }
    2914 
    2915                                                 //Obtain status
    2916                                                 $statusOrderShop = $this->genericFieldsList($settings['backend']['statusOfOrder']);
    2917 
    2918                                                 //write in VO the status
    2919                                                 if(!empty($statusOrderShop)){
    2920                                                     $response['result'][0][$statusOrderShop] = $this->fieldStatus;
    2921                                                 }
    2922                                                 $response['result'][0]['Operation'] = 2;
    2923 
    2924                                                 $this->paramsQuery('Cl', 'no', $_SESSION['nrClient']);
    2925                                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    2926                                                 curl_setopt($ch, CURLOPT_POST, false);
    2927                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2928                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2929                                                 $response2 = curl_exec($ch);
    2930                                                 // send response as JSON
    2931                                                 $response2 = json_decode($response2, true);
    2932 
    2933                                                 if (curl_error($ch)) {
    2934                                                     $this->writeFileLog('addNewOrder18', $ch);
    2935                                                 } else if(empty($response2)){
    2936                                                     $this->writeFileLog('addNewOrder18', 'EMPTY RESPONSE');
    2937                                                 } else if(isset($response2['messages'][0]['messageCodeLocale'])){
    2938                                                     $this->writeFileLog('addNewOrder18', $response2['messages'][0]['messageCodeLocale']);
    2939                                                 } else {
    2940                                                     $response['result'][0]['nome'] = $response2['result'][0]['nome'];
    2941                                                 }
    2942                                        
    2943                                                 if(isset($response)){
    2944                                                     //Save internal document
    2945                                                     $this->paramsSave('BoWS', $response);
    2946                                                     curl_setopt($ch, CURLOPT_URL, $this->url);
    2947                                                     curl_setopt($ch, CURLOPT_POST, false);
    2948                                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2949                                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2950                                                     $response = curl_exec($ch);
    2951                                                     // send response as JSON
    2952                                                     $response = json_decode($response, true);
    2953 
    2954                                                     if (curl_error($ch)) {
    2955                                                         $this->writeFileLog('addNewOrder19', $ch);
    2956                                                     } else if(empty($response)){
    2957                                                         $this->writeFileLog('addNewOrder19', 'EMPTY RESPONSE');                         
    2958                                                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    2959                                                         $this->writeFileLog('addNewOrder19', $response['messages'][0]['messageCodeLocale']);                         
    2960                                                     } else {
    2961                                                         $response = $response['result'][0];
    2962 
    2963                                                         /*global $wpdb;
    2964                                                         $table_name = $wpdb->prefix."postmeta";
    2965                                                         //Obtain next post_id of order in MySQL
    2966                                                         $query = "SELECT MAX(post_id)+1 as nextPostId FROM %s";
    2967                                                         $docid = $wpdb->get_row(str_replace("'", "", $wpdb->prepare($query, $table_name)));
    2968 
    2969                                                         //add to table postmeta a key of order and stamp of internal document
    2970                                                         add_post_meta($docid->nextPostId, '_docid', $response['bostamp']);*/
    2971 
    2972                                                         //Save data of Bo to save FT
    2973                                                         $_SESSION['responseBo'] = $response;
    2974                                                     }
    2975                                                 }
    2976                                             }
    2977                                         }
    2978                                     }
    2979                                 }
    2980                             } else if(($createClientSuccess == '' || $createClientSuccess == 0) && ($tip_button == true || $tip_button == 1)){
    2981                                 //Verify if exists in bd
    2982                                 if($_REQUEST['order_id'] == ''){
    2983                                     $_REQUEST['order_id'] = $_REQUEST['post_ID'];
    2984                                 }
    2985                                
    2986                                 $this->paramsQuery('Bo', 'obrano', sanitize_text_field( $_REQUEST['order_id'] ));
    2987                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    2988                                 curl_setopt($ch, CURLOPT_POST, false);
    2989                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    2990                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    2991                                 $response = curl_exec($ch);
    2992                                 // send response as JSON
    2993                                 $response = json_decode($response, true);   
    2994 
    2995                                 if (curl_error($ch)) {
    2996                                   $this->writeFileLog('addNewOrder20', $ch);
    2997                                 } else if(empty($response)){
    2998                                   $this->writeFileLog('addNewOrder20', 'EMPTY RESPONSE');               
    2999                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3000                                   $this->writeFileLog('addNewOrder20', $response['messages'][0]['messageCodeLocale']);               
    3001                                 } else {
    3002                                     $hasBoOrder = false;
    3003                                     foreach($response['result'] as $key => $value){
    3004                                       if($value['ndos'] == $settings['backend']['typeOfOrder']){
    3005                                         $hasBoOrder = true;
    3006                                         $hasBoOrderKey = $key;
    3007                                         break;
    3008                                       }
    3009                                     }
    3010 
    3011                                     if($hasBoOrder && $response['result'][$hasBoOrderKey]['isconfiguredtosign'] == false|| ($response['result'][$hasBoOrderKey]['isconfiguredtosign'] == true &&
    3012                                     $response['result'][$hasBoOrderKey]['draftRecord'] == 1)){                         
    3013                                         //Obtain status
    3014                                         $statusOrderShop = $this->genericFieldsList($settings['backend']['statusOfOrder']);
    3015                                        
    3016                                         //write in VO the status
    3017                                         if(!empty($statusOrderShop)){
    3018                                             $response['result'][$hasBoOrderKey][$statusOrderShop] = $this->fieldStatus;
    3019                                         }
    3020                                         $response['result'][$hasBoOrderKey]['Operation'] = 2;
    3021 
    3022                                         //Save internal document
    3023                                         $this->paramsSave('BoWS', $response);
    3024                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    3025                                         curl_setopt($ch, CURLOPT_POST, false);
    3026                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3027                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3028                                         $response = curl_exec($ch);
    3029                                         // send response as JSON
    3030                                         $response = json_decode($response, true);
    3031 
    3032                                         if (curl_error($ch)) {
    3033                                             $this->writeFileLog('addNewOrder21', $ch);
    3034                                         } else if(empty($response)){
    3035                                             $this->writeFileLog('addNewOrder21', 'EMPTY RESPONSE');                 
    3036                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3037                                             $this->writeFileLog('addNewOrder21', $response['messages'][0]['messageCodeLocale']);                 
    3038                                         }
    3039                                     }
    3040                                 }
    3041                             }
    3042                         } else {
    3043                           //Show message with error in Wordpress
    3044                           $this->messagesInformation("Please configure currency in shop according to Drive FX");
    3045                           $this->writeFileLog('coin', 'Please configure currency in shop according to Drive FX');   
    3046                           unset($_SESSION['username']);
    3047                         }
    3048                     }
    3049                 }
    3050                 //Logout
    3051                 $this->paramsLogout();
    3052                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3053                 curl_setopt($ch, CURLOPT_POST, false);
    3054                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3055                 $response = curl_exec($ch);
    3056             }
    3057             $this->writeFileLog('addNewOrder', "Sai" . $orderid);
    3058             $this->lockEnd();
    3059         }
    3060 
    30611190        //If status of order is cancelled or failed
    30621191        public function cancelOrder($order_id){
    30631192            $this->lockStart();
    30641193            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     1194
     1195            // get Credentials
     1196            $credentials = $this->syncro_services->fetchCredentials();     
    30651197            //Obtain configuration to make login
    3066             $this->paramsLogin();
     1198            $ch = $this->auth_services->PHCLogin($ch, $credentials);   
    30671199            //initial request with login data
    3068             $ch = curl_init();
    3069             //URL to save cookie "ASP.NET_SessionId"
    3070             curl_setopt($ch, CURLOPT_URL, $this->url);
    3071             curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    3072             curl_setopt($ch, CURLOPT_POST, true);
    3073             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    3074             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3075             //Parameters passed to POST
    3076             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    3077             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    3078             curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    3079             curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    3080             curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
    3081             $response = curl_exec($ch);
     1200            $response = curl_exec($ch);     
    30821201            // send response as JSON
    30831202            $response = json_decode($response, true);
     1203            // get the temporary token and insert in credentials object
     1204            $credentials->token = $response['result'][0]['token'];
     1205           
     1206            //$this->logs->writeFileLog('cancelOrder Login:', $response);
    30841207
    30851208            if (curl_error($ch)) {
    3086                 $this->writeFileLog('addNewOrder', $ch);
     1209                $this->logs->writeFileLog('addNewOrder', $ch);
    30871210            } else if(empty($response)){
    3088                 $this->writeFileLog('addNewOrder', 'EMPTY RESPONSE');
     1211                $this->logs->writeFileLog('addNewOrder', 'EMPTY RESPONSE');
    30891212            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3090                 $this->writeFileLog('addNewOrder', $response['messages'][0]['messageCodeLocale']);
     1213                $this->logs->writeFileLog('addNewOrder', $response['messages'][0]['messageCodeLocale']);
    30911214            } else {
    3092                 //Obtain gama of Drive FX
    3093                 $this->paramsGetBackEndInfo();
    3094 
    3095                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3096                 curl_setopt($ch, CURLOPT_POST, false);
    3097                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3098                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3099                 $response = curl_exec($ch);
    3100                 // send response as JSON
    3101                 $response = json_decode($response, true);
    3102 
     1215                 //Obtain gama of PHC
     1216                 $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     1217
     1218                 //$this->logs->writeFileLog('cancelOrder BackEnd:', $response);
     1219                 
    31031220                if (curl_error($ch)) {
    3104                     $this->writeFileLog('setCommunicationFx2WooCommerce', $ch);
     1221                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    31051222                } else if(empty($response)){
    3106                     $this->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
     1223                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
    31071224                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3108                     $this->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
     1225                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
    31091226                } else {
    31101227                    $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
     
    31121229               
    31131230                if($_SESSION['gamaDRIVEFX'] >= 9) {             
    3114                     //Obtain type invoices
    3115                     $this->paramsQuery('E1', 'estab', 0);
    3116                     curl_setopt($ch, CURLOPT_URL, $this->url);
    3117                     curl_setopt($ch, CURLOPT_POST, false);
    3118                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3119                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3120                     $response = curl_exec($ch);
    3121                     // send response as JSON
    3122                     $response = json_decode($response, true);
     1231                    //Obtain currency coin of company
     1232                    $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);   
     1233                   
     1234                    //$this->logs->writeFileLog('E1 response:', $response);
     1235       
    31231236
    31241237                    if (curl_error($ch)) {
    3125                         $this->writeFileLog('cancelOrder2', $ch);
     1238                        $this->logs->writeFileLog('cancelOrder2', $ch);
    31261239                    } else if(empty($response)){
    3127                         $this->writeFileLog('cancelOrder2', 'EMPTY RESPONSE');
     1240                        $this->logs->writeFileLog('cancelOrder2', 'EMPTY RESPONSE');
    31281241                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3129                         $this->writeFileLog('cancelOrder2', $response['messages'][0]['messageCodeLocale']);
     1242                        $this->logs->writeFileLog('cancelOrder2', $response['messages'][0]['messageCodeLocale']);
    31301243                    } else {
    3131                         //Verify if currency of shop corresponds to Drive FX
     1244                        //Verify if currency of shop corresponds to PHC
    31321245                        if($response['result'][0]['moeda'] == get_option('woocommerce_currency')){
    31331246                            $post_ID = sanitize_text_field( $order_id );
     
    31381251                         
    31391252                            //Verify if exists in bd
    3140                             $this->paramsQuery('Bo', $filterItem, $valueItem);
    3141                             curl_setopt($ch, CURLOPT_URL, $this->url);
    3142                             curl_setopt($ch, CURLOPT_POST, false);
    3143                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3144                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3145                             $response = curl_exec($ch);
    3146                             // send response as JSON
    3147                             $response = json_decode($response, true);     
     1253                            $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', $filterItem, $valueItem); 
     1254                   
     1255                            //$this->logs->writeFileLog('Bo response:', $response);
    31481256
    31491257                            if (curl_error($ch)) {
    3150                                 $this->writeFileLog('cancelOrder3', $ch);
     1258                                $this->logs->writeFileLog('cancelOrder3', $ch);
    31511259                            } else if(empty($response)){
    3152                                 $this->writeFileLog('cancelOrder3', 'EMPTY RESPONSE');
     1260                                $this->logs->writeFileLog('cancelOrder3', 'EMPTY RESPONSE');
    31531261                            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3154                                 $this->writeFileLog('cancelOrder3', $response['messages'][0]['messageCodeLocale']);
     1262                                $this->logs->writeFileLog('cancelOrder3', $response['messages'][0]['messageCodeLocale']);
    31551263                            } else {
    31561264
     
    31601268
    31611269                                    //Obtain status
    3162                                     $statusOrderShop = $this->genericFieldsList($settings['backend']['statusOfOrder']);
     1270                                    $statusOrderShop = $this->utils_services->genericFieldsList($settings['backend']['statusOfOrder']);
    31631271                                    //write in VO the status
    31641272                                    if(!empty($statusOrderShop)){
     
    31681276                                    $response['result'][0]['Operation'] = 2;
    31691277
    3170                                     //Save internal document
    3171                                     $this->paramsSave('BoWS', $response);
    3172                                     curl_setopt($ch, CURLOPT_URL, $this->url);
    3173                                     curl_setopt($ch, CURLOPT_POST, false);
    3174                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3175                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3176                                     $response = curl_exec($ch);
    3177                                     // send response as JSON
    3178                                     $response = json_decode($response, true);
     1278                                    $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);   
     1279                   
     1280                                    //$this->logs->writeFileLog('BoWs Save:', $response);                                   
    31791281
    31801282                                    if (curl_error($ch)) {
    3181                                         $this->writeFileLog('cancelOrder4', $ch);
     1283                                        $this->logs->writeFileLog('cancelOrder4', $ch);
    31821284                                    } else if(empty($response)){
    3183                                         $this->writeFileLog('cancelOrder4', 'EMPTY RESPONSE');
     1285                                        $this->logs->writeFileLog('cancelOrder4', 'EMPTY RESPONSE');
    31841286                                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3185                                         $this->writeFileLog('cancelOrder4', $response['messages'][0]['messageCodeLocale']);
     1287                                        $this->logs->writeFileLog('cancelOrder4', $response['messages'][0]['messageCodeLocale']);
    31861288                                    }
    31871289                                }
     
    31921294                }
    31931295                //Logout
    3194                 $this->paramsLogout();
    3195                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3196                 curl_setopt($ch, CURLOPT_POST, false);
    3197                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3198                 $response = curl_exec($ch);
     1296                $this->auth_services->PHCLogout($ch, $credentials);
    31991297            }
    32001298            $this->lockEnd();
     
    32041302        public function completedOrder( $order_id ){
    32051303            $this->lockStart();
    3206             $this->writeFileLog('completedOrder', "Entrei" . $order_id);
     1304            $this->logs->writeFileLog('completedOrder', "Entrei" . $order_id);
    32071305            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     1306
     1307            // get Credentials
     1308            $credentials = $this->syncro_services->fetchCredentials();         
    32081309            //Obtain configuration to make login
    3209             $this->paramsLogin();
     1310            $ch = $this->auth_services->PHCLogin($ch, $credentials);
    32101311            //initial request with login data
    3211             $ch = curl_init();
    3212             //URL to save cookie "ASP.NET_SessionId"
    3213             curl_setopt($ch, CURLOPT_URL, $this->url);
    3214             curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    3215             curl_setopt($ch, CURLOPT_POST, true);
    3216             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    3217             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3218             //Parameters passed to POST
    3219             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    3220             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    3221             curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    3222             curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    3223             curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
    32241312            $response = curl_exec($ch);
    32251313            // send response as JSON
    3226             $response = json_decode($response, true);
     1314            $response = json_decode($response, true);   
     1315            // get the temporary token and insert in credentials object
     1316            $credentials->token = $response['result'][0]['token'];   
    32271317
    32281318            if (curl_error($ch)) {
    3229                 $this->writeFileLog('completedOrder', $ch);
     1319                $this->logs->writeFileLog('completedOrder', $ch);
    32301320            } else if(empty($response)){
    3231                 $this->writeFileLog('completedOrder', 'EMPTY RESPONSE');     
     1321                $this->logs->writeFileLog('completedOrder', 'EMPTY RESPONSE');     
    32321322            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3233                 $this->writeFileLog('completedOrder', $response['messages'][0]['messageCodeLocale']);     
     1323                $this->logs->writeFileLog('completedOrder', $response['messages'][0]['messageCodeLocale']);     
    32341324            } else {
    32351325                //Obtain information from company
    3236                 $this->paramsQuery('E1', 'estab', 0);
    3237                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3238                 curl_setopt($ch, CURLOPT_POST, false);
    3239                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3240                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3241                 $response = curl_exec($ch);
    3242                 // send response as JSON
    3243                 $response = json_decode($response, true);
    3244 
     1326                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'E1', 'estab', 0);   
     1327   
    32451328                if (curl_error($ch)) {
    3246                     $this->writeFileLog('completedOrder2', $ch);
     1329                    $this->logs->writeFileLog('completedOrder2', $ch);
    32471330                } else if(empty($response)){
    3248                     $this->writeFileLog('completedOrder2', 'EMPTY RESPONSE');
     1331                    $this->logs->writeFileLog('completedOrder2', 'EMPTY RESPONSE');
    32491332                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3250                     $this->writeFileLog('completedOrder2', $response['messages'][0]['messageCodeLocale']);
     1333                    $this->logs->writeFileLog('completedOrder2', $response['messages'][0]['messageCodeLocale']);
    32511334                } else {
    3252                     //Verify if currency of shop corresponds to Drive FX
     1335                    //Verify if currency of shop corresponds to PHC
    32531336                    if($response['result'][0]['moeda'] == get_option('woocommerce_currency')){
    32541337                   
     
    32571340                            //Obtain stamp of internal document based in order
    32581341                            $docid = get_post_meta($order_id);
    3259                            
     1342               
    32601343                            $filterItem = "bostamp";
    32611344                            $valueItem = $docid['_docid'][sizeof($docid['_docid'])-1];
     
    32751358                                $valueItem = $docid['_docid'][sizeof($docid['_docid'])-1];
    32761359                            }
    3277                        
    3278                             //Obtain gama of Drive FX
    3279                             $this->paramsGetBackEndInfo();
    3280 
    3281                             curl_setopt($ch, CURLOPT_URL, $this->url);
    3282                             curl_setopt($ch, CURLOPT_POST, false);
    3283                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3284                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3285                             $response = curl_exec($ch);
    3286                             // send response as JSON
    3287                             $response = json_decode($response, true);
     1360                           
     1361                             //Obtain gama of PHC
     1362                             $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
    32881363
    32891364                            if (curl_error($ch)) {
    3290                                 $this->writeFileLog('setCommunicationFx2WooCommerce', $ch);
     1365                                $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    32911366                            } else if(empty($response)){
    3292                                 $this->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
     1367                                $this->logs->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
    32931368                            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3294                                 $this->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
     1369                                $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
    32951370                            } else {
    32961371                                $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
     
    32991374                            if($_SESSION['gamaDRIVEFX'] >= 9) {                     
    33001375                                //Verify if exists in bd
    3301                            
    3302                                 $this->paramsQuery('Bo', $filterItem, $valueItem);
    3303                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3304                                 curl_setopt($ch, CURLOPT_POST, false);
    3305                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3306                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3307                                 $response = curl_exec($ch);
    3308                                 // send response as JSON
    3309                                 $response = json_decode($response, true);
    3310                        
     1376                                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Bo', $filterItem, $valueItem); 
     1377                   
    33111378                                if (curl_error($ch)) {
    3312                                     $this->writeFileLog('completedOrder3', $ch);
     1379                                    $this->logs->writeFileLog('completedOrder3', $ch);
    33131380                                } else if(empty($response)){
    3314                                     $this->writeFileLog('completedOrder3', 'EMPTY RESPONSE');             
     1381                                    $this->logs->writeFileLog('completedOrder3', 'EMPTY RESPONSE');             
    33151382                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3316                                     $this->writeFileLog('completedOrder3', $response['messages'][0]['messageCodeLocale']);             
     1383                                    $this->logs->writeFileLog('completedOrder3', $response['messages'][0]['messageCodeLocale']);             
    33171384                                } else { 
    33181385
     
    33231390                                        if(!empty($response['result'][0])){         
    33241391                                            //Obtain status
    3325                                             $statusOrderShop = $this->genericFieldsList($settings['backend']['statusOfOrder']);
     1392                                            $statusOrderShop = $this->utils_services->genericFieldsList($settings['backend']['statusOfOrder']);
    33261393                                            //write in VO the status
    33271394                                            if(!empty($statusOrderShop)){
     
    33321399
    33331400                                            //Save internal document
    3334                                             $this->paramsSave('BoWS', $response);
    3335                                             curl_setopt($ch, CURLOPT_URL, $this->url);
    3336                                             curl_setopt($ch, CURLOPT_POST, false);
    3337                                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3338                                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3339                                             $response = curl_exec($ch);
    3340                                             // send response as JSON
    3341                                             $response = json_decode($response, true);
     1401                                            $response = $this->utils_services->paramsSave($ch, $credentials, 'BoWS', $response);             
    33421402                                           
    33431403                                            if (curl_error($ch)) {
    3344                                                 $this->writeFileLog('completedOrder4', $ch);
     1404                                                $this->logs->writeFileLog('completedOrder4', $ch);
    33451405                                            } else if(empty($response)){
    3346                                                 $this->writeFileLog('completedOrder4', 'EMPTY RESPONSE');
     1406                                                $this->logs->writeFileLog('completedOrder4', 'EMPTY RESPONSE');
    33471407                                            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3348                                                 $this->writeFileLog('completedOrder4', $response['messages'][0]['messageCodeLocale']);
     1408                                                $this->logs->writeFileLog('completedOrder4', $response['messages'][0]['messageCodeLocale']);
    33491409                                            }
    33501410                                        }
     
    33521412                                   
    33531413                                    $response = $response['result'][0];
     1414                                   
    33541415                                    if(!empty($response['bostamp'])){
    33551416                                        //Create Invoice only if is configurated type of invoices
    33561417                                        if(isset($settings['backend']['typeOfInvoice']) && $settings['backend']['typeOfInvoice'] > 0){
    33571418                                            //Add FT from Bo
    3358                                             $this->addInternalDocumentInvoice($response, $ch,$order_id);
     1419                                            $this->addInternalDocumentInvoice($response, $ch,$order_id, $credentials);
    33591420                                        }
    33601421                                    } else {
    33611422                                        //Add Ft without Bo
    3362                                         $this->addSimpleFT($ch,$order_id);
     1423                                        $this->addSimpleFT($ch,$order_id, $credentials);
    33631424                                    }
    33641425                                }
    33651426                            } else {
    33661427                                //Add Ft
    3367                                 $this->addSimpleFT($ch,$order_id);
     1428                                $this->addSimpleFT($ch,$order_id, $credentials);
    33681429                            }
    33691430                        }
     
    33721433            }
    33731434            //Logout
    3374             $this->paramsLogout();
     1435            $this->auth_services->PHCLogout($ch, $credentials);
    33751436            //session_destroy();
    3376             curl_setopt($ch, CURLOPT_URL, $this->url);
    3377             curl_setopt($ch, CURLOPT_POST, false);
    3378             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3379             $response = curl_exec($ch);
    3380             $this->writeFileLog('completedOrder', "Sair" . $order_id);
     1437            $this->logs->writeFileLog('completedOrder', "Sair" . $order_id);
    33811438            $this->lockEnd();
    33821439        }   
    33831440
    33841441        //Convert internal document to invoice
    3385         public function addInternalDocumentInvoice($response, $ch,$order_id){
    3386            
    3387                 $this->writeFileLog('addInternalDocumentInvoice', "Entrei addInternalDocumentInvoice ft:" . $order_id);
     1442        public function addInternalDocumentInvoice($response, $ch,$order_id, $credentials){
     1443
     1444            $this->logs->writeFileLog('addInternalDocumentInvoice', "Entrei addInternalDocumentInvoice ft:" . $order_id);
     1445           
     1446            $wooOrder = $this->syncro_services->fetchOrderData($orderid);
     1447            $ftprodPack = $this->syncro_services->processFtProducts($orderid);
     1448            $dataPack = $this->syncro_services->transformWcToPhcData($wooOrder, $prodPack, $ftprodPack);
     1449            $response = $this->invoices_services->addInternalDocInvoice($response, $ch, $credentials, $dataPack);
     1450
     1451            //Manage stock & send Email to customer
     1452            $this->manageStock($ch, $credentials, $response);
     1453            $this->sendEmail($ch, $credentials, $response);
     1454           
     1455            $this->logs->writeFileLog('addInternalDocumentInvoice', "sai addInternalDocumentInvoice ft:" . $order_id);
     1456        }
     1457
     1458        //Insert new invoice without internal document
     1459        public function addSimpleFT($ch,$orderid, $credentials){
     1460
     1461            $this->logs->writeFileLog('addSimpleft', "Entrei simple ft:" . $orderid);
     1462           
     1463            $wooOrder = $this->syncro_services->fetchOrderData($orderid);
     1464            $ftprodPack = $this->syncro_services->processFtProducts($orderid);
     1465            $dataPack = $this->syncro_services->transformWcToPhcData($wooOrder, $prodPack, $ftprodPack);
     1466            $response = $this->invoices_services->addSimpleInvoice($ch, $credentials, $dataPack);
     1467
     1468            //Manage stock & send Email to customer
     1469            $this->manageStock($ch, $credentials, $response);
     1470            $this->sendEmail($ch, $credentials, $response);
     1471           
     1472            $this->logs->writeFileLog('addSimpleft', "Sai simple ft:" . $orderid);
     1473        }
     1474
     1475        //Manage stock
     1476        public function manageStock($ch, $credentials, $response){
     1477           
     1478            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     1479       
     1480            # Manage stock
     1481            if($_SESSION['gamaDRIVEFX'] >= 9) {
     1482                if($settings['backend']['manageStock'] == 'on'){
     1483                                   
     1484                    $post_ID = sanitize_text_field( $_REQUEST['post_ID'] );
     1485                    $order_received = get_option('woocommerce_checkout_order_received_endpoint');
     1486
     1487                    if(empty($order_received)){
     1488                        $order = new WC_Order( $post_ID );
     1489                    } else {
     1490                        $order = new WC_Order( $order_received );
     1491                    }
    33881492               
    3389             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    3390             //See if type of order is configured
    3391             if(empty($settings['backend']['typeOfInvoice']) || $settings['backend']['typeOfInvoice'] == 0){
    3392                 $this->writeFileLog('addInternalDocumentInvoice', 'Empty type of invoice');
    3393             } else {     
    3394                 //Obtain new instance of FT based in Bo(bostamp)
    3395                 $this->paramsNewInstanceFromReference($response['bostamp']);
    3396                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3397                 curl_setopt($ch, CURLOPT_POST, false);
    3398                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3399                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3400                 $response = curl_exec($ch);     
    3401                 // send response as JSON
    3402                 $response = json_decode($response, true);
    3403 
    3404                 if (curl_error($ch)) {
    3405                     $this->writeFileLog('addInternalDocumentInvoice2', $ch);
    3406                 } else if(empty($response)){
    3407                     $this->writeFileLog('addInternalDocumentInvoice2', 'EMPTY RESPONSE');       
    3408                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3409                     $this->writeFileLog('addInternalDocumentInvoice2', $response['messages'][0]['messageCodeLocale']);       
    3410                 } else {
    3411                     //Save id of client
    3412                     $_SESSION['numberClient'] = $response['result'][0]['no'];
    3413                     //Save vo with products
    3414                     $_SESSION['voProducts'] = $response['result'][0];
    3415                     //Save FT
    3416                     $this->paramsSave('FtWS', $response);
    3417                     curl_setopt($ch, CURLOPT_URL, $this->url);
    3418                     curl_setopt($ch, CURLOPT_POST, false);
    3419                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3420                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3421                     $response = curl_exec($ch);
    3422                     // send response as JSON
    3423                     $response = json_decode($response, true);
    3424 
    3425                     if (curl_error($ch)) {
    3426                         $this->writeFileLog('addInternalDocumentInvoice3', $ch);
    3427                     } else if(empty($response)){
    3428                         $this->writeFileLog('addInternalDocumentInvoice3', 'EMPTY RESPONSE');         
    3429                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3430                         $this->writeFileLog('addInternalDocumentInvoice3', $response['messages'][0]['messageCodeLocale']);         
    3431                     } else {
    3432                         //Enable to sign Document
    3433                         if($response['result'][0]['draftRecord'] == 1){
    3434                            
    3435                             $this->writeFileLog('addInternalDocumentInvoice3', 'GOING TO SIGN');       
    3436                             if($settings['backend']['toSignInvoice'] == 'on'){
    3437                            
    3438                                 $_SESSION['ftstamp'] = $response['result'][0]['ftstamp'];
    3439                                 $this->paramsSignDocument($response['result'][0]['ftstamp']);
    3440                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3441                                 curl_setopt($ch, CURLOPT_POST, false);
    3442                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3443                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3444                                 $response = curl_exec($ch);
    3445                                 // send response as JSON
    3446                                 $response = json_decode($response, true);
    3447 
    3448                             }
    3449                            
    3450                             if (curl_error($ch)) {
    3451                                 $this->writeFileLog('addInternalDocumentInvoice4', $ch);
    3452                             } else if(empty($response)){
    3453                                 $this->writeFileLog('addInternalDocumentInvoice4', 'EMPTY RESPONSE');             
    3454                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3455                                 $this->writeFileLog('addInternalDocumentInvoice4', $response['messages'][0]['messageCodeLocale']);             
    3456                             } else {                           
    3457                                 //Manage stock
    3458                                 if($settings['backend']['manageStock'] == 'on'){
    3459                                     $post_ID = sanitize_text_field( $order_id);
    3460                                     $order_received = get_option('woocommerce_checkout_order_received_endpoint');
    3461 
    3462                                     if(!empty($post_ID)){
    3463                                         $order = new WC_Order( $post_ID );
    3464                                     } else {
    3465                                         $order = new WC_Order( $order_received );
    3466                                     }
    3467                                    
    3468                                     $i = 0;
    3469                                     foreach($order->get_items() as $key => $value){
    3470                                       $productReference = wc_get_product( $value->get_id() );
    3471                            
    3472                                       $sku[$i] = $productReference->get_sku();             
    3473                                       $productID[$sku[$i]] =  $value->get_id();
    3474                                     }
    3475 
    3476                                     $i = 0;
    3477                                     $count = count($_SESSION['voProducts']['fis']);
    3478                                     while ($i < $count) {
    3479                                         foreach ($_SESSION['voProducts']['fis'][$i] as $key => $value){
    3480                                             //Obtain product from reference
    3481                                             $this->paramsQuery('St', 'ref', $_SESSION['voProducts']['fis'][$i]['ref']);
    3482                                             curl_setopt($ch, CURLOPT_URL, $this->url);
    3483                                             curl_setopt($ch, CURLOPT_POST, false);
    3484                                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3485                                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3486                                             $response = curl_exec($ch);
    3487                                             // send response as JSON
    3488                                             $response = json_decode($response, true);
    3489 
    3490                                             if (curl_error($ch)) {
    3491                                                 $this->writeFileLog('addInternalDocumentInvoice5', $ch);
    3492                                             } else if(empty($response)){
    3493                                                 $this->writeFileLog('addInternalDocumentInvoice5', 'EMPTY RESPONSE');                     
    3494                                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3495                                                 $this->writeFileLog('addInternalDocumentInvoice5', $response['messages'][0]['messageCodeLocale']);                     
    3496                                             } else {
    3497                                                 //If find reference, update stock
    3498                                                 if (is_array($sku)){
    3499                                                     foreach ($sku as $key => $value) {
    3500                                                         if($_SESSION['voProducts']['fis'][$i]['ref'] == $value){
    3501                                                             update_post_meta($productID[$value],'_stock',$response['result'][0]['stock']);
    3502                                                         }
    3503                                                     }
    3504                                                 }
    3505                                             }   
    3506                                         }
    3507                                         ++$i;
     1493                    $i = 0;
     1494                    foreach($order->get_items() as $key => $value){
     1495                        $productReference = wc_get_product( $value['item_meta']['_product_id'][0] );
     1496                        $sku[$i] = $productReference->get_sku();
     1497
     1498                        $productID[$sku[$i]] = $value['item_meta']['_product_id'][0];
     1499                    }
     1500
     1501                    ###
     1502                    $fisProducts =  $_SESSION['voProducts']['fis'];
     1503
     1504                   
     1505                    $i = 0;
     1506                    $count = count($fisProducts);
     1507                    //$this->logs->writeFileLog('response:', $count);   
     1508                    while ($i < $count) {
     1509                        foreach ($fisProducts[$i] as $key => $value){
     1510                                #Obtain product from reference
     1511                                $response = $this->utils_services->filterItem_Query($ch, $credentials, 'St', 'ref', $fisProducts[$i]['ref']);
     1512
     1513                                //$this->logs->writeFileLog('stock:', $response);
     1514
     1515                                if (curl_error($ch)) {
     1516                                    $this->logs->writeFileLog('addSimpleFT16', $ch);
     1517                                } else if(empty($response)){
     1518                                    $this->logs->writeFileLog('addSimpleFT16', 'EMPTY RESPONSE');                           
     1519                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
     1520                                    $this->logs->writeFileLog('addSimpleFT16', $response['messages'][0]['messageCodeLocale']);                           
     1521                                } else {
     1522                                #If find ref, update stock
     1523                                foreach ($sku as $key => $value) {
     1524                                    if($fisProducts[$i]['ref'] == $value){
     1525                                        $updatedStock = update_post_meta($productID[$value],'_stock',$response['result'][0]['stock']);
     1526                                        //$this->logs->writeFileLog('updatedStock', $updatedStock);
     1527
    35081528                                    }
    35091529                                }
    3510                                 //Verify if are selected type of internal document and send invoice checkbox
    3511                                 if(isset($settings['backend']['typeOfInvoice']) && $settings['backend']['createInvoice'] == 'on' && $settings['backend']['typeOfInvoice'] > 0 && isset($settings['backend']['sendInvoice'])){
    3512                                     //Obtain reports for print
    3513                                     $this->paramsGetReportForPrint();
    3514                                     curl_setopt($ch, CURLOPT_URL, $this->url);
    3515                                     curl_setopt($ch, CURLOPT_POST, false);
    3516                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3517                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3518                                     $response = curl_exec($ch);
    3519                                     // send response as JSON
    3520                                     $response = json_decode($response, true);
    3521 
    3522                                     if (curl_error($ch)) {
    3523                                         $this->writeFileLog('addInternalDocumentInvoice6', $ch);
    3524                                     } else if(empty($response)){
    3525                                         $this->writeFileLog('addInternalDocumentInvoice6', 'EMPTY RESPONSE');                 
    3526                                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3527                                         $this->writeFileLog('addInternalDocumentInvoice6', $response['messages'][0]['messageCodeLocale']);                 
    3528                                     } else {
    3529                                         //Verify if exists template as default
    3530                                         $i = 0;
    3531                                         $count = count($response['result']);
    3532                                         $sendEmail = false;
    3533                                         while ($i < $count) {
    3534                                             foreach ($response['result'][$i] as $key => $value){
    3535                                                 if($key == 'enabled' && $value == 1){
    3536                                                     $sendEmail = true;
    3537                                                     $_SESSION['repstamp'] = $response['result'][$i]['repstamp'];
    3538                                                     break;
    3539                                                 }   
    3540                                             }
    3541                                             ++$i;
    3542                                         }
    3543                                         //If is configured to send email in backend settings of plugin
    3544                                         if($sendEmail == true){
    3545                                             $this->paramsQuery('Cl', 'no', $_SESSION['numberClient']);
    3546                                             curl_setopt($ch, CURLOPT_URL, $this->url);
    3547                                             curl_setopt($ch, CURLOPT_POST, false);
    3548                                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3549                                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3550                                             $response = curl_exec($ch);
    3551                                             // send response as JSON
    3552                                             $response = json_decode($response, true);
    3553 
    3554                                             if (curl_error($ch)) {
    3555                                                 $this->writeFileLog('addInternalDocumentInvoice7', $ch);
    3556                                             } else if(empty($response)){
    3557                                                 $this->writeFileLog('addInternalDocumentInvoice7', 'EMPTY RESPONSE');                     
    3558                                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3559                                                 $this->writeFileLog('addInternalDocumentInvoice7', $response['messages'][0]['messageCodeLocale']);
    3560                                                 $this->messagesError(utf8_decode(" in configuration of email to send them to client! Message from Backend: " . $response['messages'][0]['messageCodeLocale']));
    3561                                             } else {
    3562                                                 if($response['result'][0]['email'] != ''){
    3563                                                     //Email To
    3564                                                     $_SESSION['emailClient'] = $response['result'][0]['email'];
    3565                                                     //Email From
    3566                                                     $infoAdmin = $this->get_settingsAdmin();
    3567                                                     $emailAdmin = $infoAdmin[3]['default'];
    3568 
    3569                                                     //Send FT to email selected
    3570                                                     $this->paramsSendReportEmail($_SESSION['repstamp'], $_SESSION['ftstamp'], $_SESSION['emailClient'], $emailAdmin, $settings['backend']['typeOfInvoice'], '');
    3571                                                     curl_setopt($ch, CURLOPT_URL, $this->url);
    3572                                                     curl_setopt($ch, CURLOPT_POST, false);
    3573                                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3574                                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3575                                                     $response = curl_exec($ch);
    3576                                                     // send response as JSON
    3577                                                     $response = json_decode($response, true);
    3578 
    3579                                                     if (curl_error($ch)) {
    3580                                                         $this->writeFileLog('addInternalDocumentInvoic8', $ch);
    3581                                                     } else if(empty($response)){
    3582                                                         $this->writeFileLog('addInternalDocumentInvoic8', 'EMPTY RESPONSE');                         
    3583                                                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3584                                                         $this->writeFileLog('addInternalDocumentInvoice8', $response['messages'][0]['messageCodeLocale']);                         
    3585                                                     }
    3586                                                 }
    3587                                             }
    3588                                         }
    3589                                     }
     1530                            }   
     1531                        }
     1532                        ++$i;
     1533                    }
     1534                    //$this->logs->writeFileLog('Info:', 'Stock updated');
     1535                }
     1536                return $updatedStock;
     1537            }
     1538        }
     1539
     1540        // Send E-mail
     1541        public function sendEmail($ch, $credentials, $response){
     1542            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     1543
     1544            //Saves customer data and invoice stamp
     1545            $_SESSION['numberClient'] = $response['result'][0]['no'];
     1546            $_SESSION['ftstamp'] = $response['result'][0]['ftstamp'];
     1547
     1548            # Verify if are selected type of internal document and send invoice checkbox
     1549            if(isset($settings['backend']['typeOfInvoice']) && $settings['backend']['createInvoice'] == 'on' &&
     1550                    $settings['backend']['typeOfInvoice'] > 0 && isset($settings['backend']['sendInvoice'])){
     1551
     1552                //Obtain reports for print
     1553                $response = $this->utils_services->paramsGetReportForPrint($ch, $credentials);
     1554
     1555                //$this->logs->writeFileLog('paramsGetReportForPrint:', $response);
     1556
     1557                if (curl_error($ch)) {
     1558                    $this->logs->writeFileLog('addSimpleFT17', $ch);
     1559                } else if(empty($response)){
     1560                    $this->logs->writeFileLog('addSimpleFT17', 'EMPTY RESPONSE');                       
     1561                } else if(isset($response['messages'][0]['messageCodeLocale'])){
     1562                    $this->logs->writeFileLog('addSimpleFT17', $response['messages'][0]['messageCodeLocale']);                       
     1563                } else {
     1564                    //Verify if exists template as default
     1565                    $i = 0;
     1566                    $count = count($response['result']);
     1567                    $sendEmail = false;
     1568                    while ($i < $count) {
     1569                        foreach ($response['result'][$i] as $key => $value){
     1570                            if($key == 'enabled' && $value == 1){
     1571                                $sendEmail = true;
     1572                                $_SESSION['repstamp'] = $response['result'][$i]['repstamp'];
     1573                                break;
     1574                            }
     1575                        }
     1576                        ++$i;
     1577                    }                                                           
     1578                    #If exists template as default
     1579                    if($sendEmail == true){                                     
     1580                        //Obtain client
     1581                        $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Cl', 'no', $_SESSION['numberClient']);
     1582
     1583                        //$this->logs->writeFileLog('custom_by_no:', $response);
     1584                       
     1585                        if (curl_error($ch)) {
     1586                            $this->logs->writeFileLog('addSimpleFT18', $ch);
     1587                        } else if(empty($response)){
     1588                            $this->logs->writeFileLog('addSimpleFT18', 'EMPTY RESPONSE');                           
     1589                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
     1590                            $this->logs->writeFileLog('addSimpleFT18', $response['messages'][0]['messageCodeLocale']);
     1591                        } else {
     1592                            if($response['result'][0]['email'] != ''){
     1593                                //Email To
     1594                                $_SESSION['emailClient'] = $response['result'][0]['email'];
     1595                                //Email From
     1596                                $infoAdmin = $this->get_settingsAdmin();
     1597                                $emailAdmin = $infoAdmin[3]['default'];                                 
     1598                                ###
     1599                                $body = $settings['backend']['emailBody'];
     1600
     1601                                //Send FT to email selected
     1602                                $response = $this->utils_services->paramsSendReportEmail(
     1603                                                                    $ch, $credentials, $_SESSION['repstamp'],
     1604                                                                    $_SESSION['ftstamp'], $_SESSION['emailClient'],
     1605                                                                    $emailAdmin, $settings['backend']['typeOfInvoice'], '', $body);
     1606                                                                                       
     1607                                //$this->logs->writeFileLog('paramsSendReportEmail:', $response);
     1608                               
     1609                                if (curl_error($ch)) {
     1610                                    $this->logs->writeFileLog('addSimpleFT19', $ch);
     1611                                } else if(empty($response)){
     1612                                    $this->logs->writeFileLog('addSimpleFT19', 'EMPTY RESPONSE');                               
     1613                                } else if(isset($response['messages'][0]['messageCodeLocale'])){
     1614                                    $this->logs->writeFileLog('addSimpleFT19', $response['messages'][0]['messageCodeLocale']);                               
     1615                                } else {
     1616                                    $this->logs->writeFileLog('Info:', 'Email sended');
    35901617                                }
    35911618                            }
    3592                         } else {
    3593                             //Manage stock
    3594                             if($settings['backend']['manageStock'] == 'on'){
    3595                                 $post_ID = sanitize_text_field( $_REQUEST['post_ID'] );
    3596                                 $order_received = get_option('woocommerce_checkout_order_received_endpoint');
    3597        
    3598                                 if(!empty($post_ID)){
    3599                                     $order = new WC_Order( $post_ID );
    3600                                 } else {
    3601                                     $order = new WC_Order( $order_received );
    3602                                 }
    3603                    
    3604                                 $i = 0;
    3605                                 foreach($order->get_items() as $key => $value){
    3606                                     $productReference = wc_get_product( $value['item_meta']['_product_id'][0] );
    3607                                     //#1 - Try with WC_product
    3608                                     try{
    3609                                         $productReference = new WC_Product($value->get_id());
    3610                                     }catch(Exception $e){
    3611                                         $this->writeFileLog('addInternalDocumentInvoice4.1', 'WC_Product with error => using WC_Product_variation');
    3612                                         $productReference = new WC_Product_Variation($value->get_id());
    3613                                     }             
    3614                                     $productID[$sku[$i]] = $value['item_meta']['_product_id'][0];
    3615                                 }
    3616 
    3617                                 $i = 0;
    3618                                 $count = count($_SESSION['voProducts']['fis']);
    3619                                 while ($i < $count) {
    3620                                     foreach ($_SESSION['voProducts']['fis'][$i] as $key => $value){
    3621                                         //Obtain product from reference
    3622                                         $this->paramsQuery('St', 'ref', $_SESSION['voProducts']['fis'][$i]['ref']);
    3623                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    3624                                         curl_setopt($ch, CURLOPT_POST, false);
    3625                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3626                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3627                                         $response = curl_exec($ch);
    3628                                         // send response as JSON
    3629                                         $response = json_decode($response, true);
    3630 
    3631                                         if (curl_error($ch)) {
    3632                                             $this->writeFileLog('addInternalDocumentInvoice5', $ch);
    3633                                         } else if(empty($response)){
    3634                                             $this->writeFileLog('addInternalDocumentInvoice5', 'EMPTY RESPONSE');                     
    3635                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3636                                             $this->writeFileLog('addInternalDocumentInvoice5', $response['messages'][0]['messageCodeLocale']);                     
    3637                                         } else {
    3638                                             //If find reference, update stock
    3639                                             if (is_array($sku)){
    3640                                                 foreach ($sku as $key => $value) {
    3641                                                     if($_SESSION['voProducts']['fis'][$i]['ref'] == $value){
    3642                                                         update_post_meta($productID[$value],'_stock',$response['result'][0]['stock']);
    3643                                                     }
    3644                                                 }
    3645                                             }
    3646                                         }   
    3647                                     }
    3648                                     ++$i;
    3649                                 }
    3650                             }
    36511619                        }
    36521620                    }
    36531621                }
    36541622            }
    3655                 $this->writeFileLog('addInternalDocumentInvoice', "sai addInternalDocumentInvoice ft:" . $order_id);
    3656         }
    3657 
    3658         //Insert new invoice without internal document
    3659         public function addSimpleFT($ch,$orderid){
    3660             global $woocommerce;
    3661            
    3662             $this->writeFileLog('addSimpleft', "Entrei simple ft:" . $orderid);
    3663                
    3664             $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    3665             //See if type of invoice is configured
    3666             if(empty($settings['backend']['typeOfInvoice']) || $settings['backend']['typeOfInvoice'] == 0){
    3667                 $this->writeFileLog('addSimpleFT', 'Empty type of invoice');
    3668             } else {   
    3669                 //Put the same number of order in Drive FX
    3670                 global $wpdb;
    3671                 $table_name = $wpdb->prefix."postmeta";
    3672                 //Obtain next post_id of order in MySQL
    3673                 $query = "SELECT meta_key, meta_value FROM %s where post_id = %d";
    3674                 $docid = $wpdb->get_results(str_replace("'", "", $wpdb->prepare($query, $table_name, sanitize_text_field($orderid))));
    3675                 $nifName = '_billing_'.$settings['backend']['fieldNif'];
    3676                 foreach ($docid as $key => $value) {
    3677                     if($value->meta_key == '_billing_country'){
    3678                         $_billing_country = $value->meta_value;
    3679                     } else if($value->meta_key == '_billing_first_name') {
    3680                         $_billing_first_name = $value->meta_value;
    3681                     } else if($value->meta_key == '_billing_last_name') {
    3682                         $_billing_last_name = $value->meta_value;
    3683                     } else if($value->meta_key == '_billing_address_1') {
    3684                         $_billing_address_1 = $value->meta_value;
    3685                     } else if($value->meta_key == '_billing_city') {
    3686                         $_billing_city = $value->meta_value;
    3687                     } else if($value->meta_key == '_billing_postcode') {
    3688                         $_billing_postcode = $value->meta_value;
    3689                     } else if($value->meta_key == $nifName) {
    3690                         $_billing_nif = $value->meta_value;
    3691                     } else if($value->meta_key == '_billing_email') {
    3692                         $_billing_email = $value->meta_value;
    3693                     } else if($value->meta_key == '_billing_phone') {
    3694                         $_billing_phone = $value->meta_value;
    3695                     } else if($value->meta_key == '_shipping_country') {
    3696                         $_shipping_country = $value->meta_value;
    3697                     } else if($value->meta_key == '_shipping_address_1') {
    3698                         $_shipping_address_1 = $value->meta_value;
    3699                     } else if($value->meta_key == '_shipping_city') {
    3700                         $_shipping_city = $value->meta_value;
    3701                     } else if($value->meta_key == '_shipping_postcode') {
    3702                         $_shipping_postcode = $value->meta_value;
    3703                     }
    3704                 }
    3705                
    3706                 $order_meta = get_post_meta($orderid);
    3707                
    3708 
    3709                 $billing_country = $order_meta['_billing_country'][0];
    3710                 $order_received = get_option('woocommerce_checkout_order_received_endpoint');
    3711 
    3712                 if($_billing_country == ''){
    3713                     $_billing_country = sanitize_text_field( $_REQUEST['_billing_country'] );
    3714                 }
    3715                 if($_billing_country=='') $_billing_country="PT";
    3716                 //Obtain country
    3717                 $this->paramsQuery('Countries', 'nomeabrv', $_billing_country);
    3718                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3719                 curl_setopt($ch, CURLOPT_POST, false);
    3720                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3721                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3722                 $response = curl_exec($ch);
    3723                 // send response as JSON
    3724                 $response = json_decode($response, true);
    3725 
    3726                 if (curl_error($ch)) {
    3727                     $this->writeFileLog('addSimpleFT2', $ch);
    3728                 } else if(empty($response)){
    3729                     $this->writeFileLog('addSimpleFT2', 'EMPTY RESPONSE');
    3730                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3731                     $this->writeFileLog('addSimpleFT2', $response['messages'][0]['messageCodeLocale']);
    3732                 } else {
    3733                     $paisesstamp = $response['result'][0]['paisesstamp'];
    3734                     $nomePais = $response['result'][0]['nome'];
    3735                 }
    3736 
    3737                 if($_shipping_country == ''){
    3738                     $_shipping_country =  $order_meta['_shipping_country'][0];
    3739                     if($_shipping_country == ''){
    3740                         $_shipping_country = $billing_country;
    3741                     }
    3742                 }
    3743                 if($_shipping_country=='') $_shipping_country="PT";
    3744                 //Obtain shipping country
    3745                 $this->paramsQuery('Countries', 'nomeabrv', $_shipping_country);
    3746                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3747                 curl_setopt($ch, CURLOPT_POST, false);
    3748                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3749                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3750                 $response = curl_exec($ch);
    3751                 // send response as JSON
    3752                 $response = json_decode($response, true);
    3753 
    3754                 if (curl_error($ch)) {
    3755                     $this->writeFileLog('addSimpleFT3', $ch);
    3756                 } else if(empty($response)){
    3757                     $this->writeFileLog('addSimpleFT3', 'EMPTY RESPONSE');
    3758                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3759                     $this->writeFileLog('addSimpleFT3', $response['messages'][0]['messageCodeLocale']);
    3760                 } else {
    3761                     $paisesstampShipping = $response['result'][0]['paisesstamp'];
    3762                     $nomePaisShipping = $response['result'][0]['nome'];
    3763                 }
    3764                
    3765                 unset($_SESSION['listOfSku']);
    3766                 unset($_SESSION['listOfQuantity']);         
    3767                 unset($_SESSION['listOfValueItem']);
    3768                 if (is_array(WC()->cart->cart_contents)){
    3769                     $i = 0;
    3770                     //Obtain key of wordpress thtat identified the different products in  cart
    3771                     foreach (WC()->cart->cart_contents as $key => $value){
    3772                         $productsOrder[$i] = $key;       
    3773                         ++$i;
    3774                     }
    3775                     $i = 0;
    3776                     $count = count(WC()->cart->cart_contents);
    3777                     //Wordpress function to obtain information of cart items
    3778                     while ($i < $count) {
    3779                         //Obtain info about products in cart
    3780                         $productData = WC()->cart->cart_contents[$productsOrder[$i]];
    3781                         //obtain reference items in cart
    3782                         if($productData['variation_id']!='' && $value['variation_id'] != 0){
    3783                             $productReference = wc_get_product( $productData['variation_id'] );
    3784                         } else {
    3785                             $productReference = wc_get_product( $productData['product_id'] );
    3786                         }
    3787 
    3788                         $sku[$i] = $productReference->get_sku();
    3789                         //Obtain quantity of the product in cart
    3790                         $quantity[$i] = $productData['quantity'];
    3791                         $valueItem[$i] = $productData['line_total'] + $value['line_tax'];
    3792                         ++$i;
    3793                     }
    3794                     //Save items of cart
    3795                     $_SESSION['listOfSku'] = $sku;
    3796                     $_SESSION['listOfQuantity'] = $quantity;
    3797                     $_SESSION['listOfValueItem'] = $valueItem;
    3798                 }                   
    3799 
    3800                 if(empty($_SESSION['listOfSku'])){
    3801                     //Obtain id of order and products
    3802                     $order = new WC_Order($orderid);
    3803                 //  $order = new WC_Order($order->post->ID);
    3804                    
    3805                     $i = 0;
    3806                    
    3807                     foreach($order->get_items() as $key => $value){
    3808                         if($value['variation_id'] != '' && $value['variation_id'] != 0){
    3809                             $product = new WC_Product_Variation($value['variation_id']);
    3810                         } else {
    3811                             $product = new WC_Product($value['product_id']);
    3812                         }
    3813                         $sku[$i] = $product->get_sku();
    3814                         $quantity[$i] = $value['qty'];
    3815                         $valueItem[$i] = $value['line_total'] + $value['line_tax'];
    3816                         ++$i;
    3817                     }
    3818                     //Save items of cart
    3819                     $_SESSION['listOfSku'] = $sku;
    3820                     $_SESSION['listOfQuantity'] = $quantity;
    3821                     $_SESSION['listOfValueItem'] = $valueItem;
    3822                 }
    3823 
    3824            
    3825                 $billing_email = $order_meta['_billing_email'][0];
    3826                
    3827 
    3828                 if($billing_email_ != '' || $billing_email != ''){
    3829                     //Verify if client exists
    3830                     if($billing_email_ == '' && $billing_email != ''){
    3831                         $this->paramsQuery('Cl', 'email', $billing_email);
    3832                     } else if ($billing_email_ != '' && $billing_email == ''){
    3833                         $this->paramsQuery('Cl', 'email', $billing_email_);
    3834                     }
    3835 
    3836                     curl_setopt($ch, CURLOPT_URL, $this->url);
    3837                     curl_setopt($ch, CURLOPT_POST, false);
    3838                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3839                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3840                     $response = curl_exec($ch);
    3841                     // send response as JSON
    3842                     $response = json_decode($response, true);       
    3843 
    3844                     if (curl_error($ch)) {
    3845                         $this->writeFileLog('addSimpleFT4', $ch);
    3846                     } else if(empty($response)){
    3847                         $this->writeFileLog('addSimpleFT4', 'EMPTY RESPONSE');         
    3848                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3849                         $this->writeFileLog('addSimpleFT4', $response['messages'][0]['messageCodeLocale']);         
    3850                     } else { 
    3851                         //Have client
    3852                         if(is_array($response['result'][0])){
    3853                             //Save number id of client
    3854                             $_SESSION['nrClient'] = $response['result'][0]['no'];
    3855                             //Save vo with products
    3856                             $_SESSION['voProducts'] = $response['result'][0];
    3857 
    3858                             $billing_first_name = $order_meta['_billing_first_name'][0];
    3859                             $billing_last_name = $order_meta['_billing_last_name'][0];
    3860                             $billing_email = $order_meta['_billing_email'][0];
    3861                             $billing_address_1 = $order_meta['_billing_address_1'][0];
    3862                             $billing_city = $order_meta['_billing_city'][0];
    3863                             $billing_phone = $order_meta['_billing_phone'][0]; 
    3864                             $billing_postcode = $order_meta['_billing_postcode'][0];
    3865                             $billing_nif = $order_meta['_billing_'.$settings['backend']['fieldNif']][0];
    3866 
    3867                                                
    3868                        
    3869                            
    3870                                 $response['result'][0]['nome'] = $billing_first_name . " " . $billing_last_name;
    3871                                 $response['result'][0]['email'] = $billing_email;
    3872                                 $response['result'][0]['morada'] = $billing_address_1;
    3873                                 $response['result'][0]['local'] = $billing_city;
    3874                                 $response['result'][0]['provincia'] = $billing_city;
    3875                                 $response['result'][0]['telefone'] = $billing_phone;
    3876                                 $response['result'][0]['codpost'] = $billing_postcode;
    3877                                 $response['result'][0]['ncont'] = $billing_nif;
    3878                            
    3879                            
    3880                            
    3881                             $response['result'][0]['paisesstamp'] = $paisesstamp;
    3882                             $response['result'][0]['pais'] = $nomePais;
    3883                             $response['result'][0]['Operation'] = 2;
    3884                            
    3885                             //Save data of client in Drive FX
    3886                             $this->paramsSave('ClWS', $response);
    3887                             curl_setopt($ch, CURLOPT_URL, $this->url);
    3888                             curl_setopt($ch, CURLOPT_POST, false);
    3889                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3890                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3891                             $response = curl_exec($ch);
    3892                        
    3893                             // send response as JSON
    3894                             $response = json_decode($response, true);
    3895 
    3896                             if (curl_error($ch)) {
    3897                                 $this->writeFileLog('addSimpleFT5', $ch);
    3898                             } else if(empty($response)){
    3899                                 $this->writeFileLog('addSimpleFT5', 'EMPTY RESPONSE');             
    3900                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3901                                 $this->writeFileLog('addSimpleFT5', $response['messages'][0]['messageCodeLocale']);
    3902                                 if($_SESSION['nrClient'] != ''){
    3903                                     //Inserted client in bd
    3904                                     $createClientSuccess = 1;
    3905                                 }             
    3906                             } else {
    3907                                 //Inserted client in bd
    3908                                 $createClientSuccess = 1;
    3909                             }
    3910                             //Dont have client - INSERT
    3911                         } else {
    3912                             //Obtain new instance of client
    3913                             $this->paramsNewInstance('ClWS', 0);
    3914                             curl_setopt($ch, CURLOPT_URL, $this->url);
    3915                             curl_setopt($ch, CURLOPT_POST, false);
    3916                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3917                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3918                             $response = curl_exec($ch);
    3919                             // send response as JSON
    3920                             $response = json_decode($response, true);
    3921 
    3922                             if (curl_error($ch)) {
    3923                                 $this->writeFileLog('addSimpleFT6', $ch);
    3924                             } else if(empty($response)){
    3925                                 $this->writeFileLog('addSimpleFT6', 'EMPTY RESPONSE');             
    3926                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3927                                 $this->writeFileLog('addSimpleFT6', $response['messages'][0]['messageCodeLocale']);             
    3928                             } else {                 
    3929                                 //Save number id of client
    3930                                 $_SESSION['nrClient'] = $response['result'][0]['no'];
    3931                                 //Save vo with products
    3932                                 $_SESSION['voProducts'] = $response['result'][0];
    3933 
    3934                                 $billing_first_name = $order_meta['_billing_first_name'][0];
    3935                             $billing_last_name = $order_meta['_billing_last_name'][0];
    3936                             $billing_email = $order_meta['_billing_email'][0];
    3937                             $billing_address_1 = $order_meta['_billing_address_1'][0];
    3938                             $billing_city = $order_meta['_billing_city'][0];
    3939                             $billing_phone = $order_meta['_billing_phone'][0]; 
    3940                             $billing_postcode = $order_meta['_billing_postcode'][0];
    3941                             $billing_nif = $order_meta['_billing_'.$settings['backend']['fieldNif']][0];
    3942 
    3943                                                
    3944                        
    3945                            
    3946                                 $response['result'][0]['nome'] = $billing_first_name . " " . $billing_last_name;
    3947                                 $response['result'][0]['email'] = $billing_email;
    3948                                 $response['result'][0]['morada'] = $billing_address_1;
    3949                                 $response['result'][0]['local'] = $billing_city;
    3950                                 $response['result'][0]['provincia'] = $billing_city;
    3951                                 $response['result'][0]['telefone'] = $billing_phone;
    3952                                 $response['result'][0]['codpost'] = $billing_postcode;
    3953                                 $response['result'][0]['ncont'] = $billing_nif;
    3954                            
    3955                            
    3956 
    3957                                
    3958                            
    3959                            
    3960                                 $response['result'][0]['paisesstamp'] = $paisesstamp;
    3961                                 $response['result'][0]['pais'] = $nomePais;
    3962                                
    3963                                 $response['result'][0]['preco'] = intval(str_replace('epv', '', $settings['backend']['productPriceColumn']));
    3964 
    3965                                 //Save data of client in Drive FX
    3966                                 $this->paramsSave('ClWS', $response);
    3967                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    3968                                 curl_setopt($ch, CURLOPT_POST, false);
    3969                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3970                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    3971                                 $response = curl_exec($ch);
    3972                                
    3973                                 // send response as JSON
    3974                                 $response = json_decode($response, true);
    3975                        
    3976                                 if (curl_error($ch)) {
    3977                                     $this->writeFileLog('addSimpleFT7', $ch);
    3978                                 } else if(empty($response)){
    3979                                     $this->writeFileLog('addSimpleFT7', 'EMPTY RESPONSE');               
    3980                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    3981                                     $this->writeFileLog('addSimpleFT7', $response['messages'][0]['messageCodeLocale']);
    3982                                     if($_SESSION['nrClient'] != ''){
    3983                                         //Inserted client in bd
    3984                                         $createClientSuccess = 1;
    3985                                     }               
    3986                                 } else {
    3987                                     //Inserted client in bd
    3988                                     $createClientSuccess = 1;
    3989                                 }
    3990                             }
    3991                         }
    3992                     }
    3993                 } else {
    3994                     //Verify if existis generic client
    3995                     $this->paramsQuery('Cl', 'clivd', '1');
    3996                     curl_setopt($ch, CURLOPT_URL, $this->url);
    3997                     curl_setopt($ch, CURLOPT_POST, false);
    3998                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    3999                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4000                     $response = curl_exec($ch);
    4001                     // send response as JSON
    4002                     $response = json_decode($response, true);             
    4003 
    4004                     if (curl_error($ch)) {
    4005                         $this->writeFileLog('addSimpleFT8', $ch);
    4006                     } else if(empty($response)){
    4007                         $this->writeFileLog('addSimpleFT8', 'EMPTY RESPONSE');         
    4008                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4009                         $this->writeFileLog('addSimpleFT8', $response['messages'][0]['messageCodeLocale']);         
    4010                     } else { 
    4011                         //Have generic client
    4012                         if(is_array($response['result'][0])){
    4013                             //Save number id of client
    4014                             $_SESSION['nrClient'] = $response['result'][0]['no'];
    4015                             //Save vo with products
    4016                             $_SESSION['voProducts'] = $response['result'][0];
    4017                             //Obtain client from Drive FX
    4018                             $createClientSuccess = 1;
    4019                         //Dont have generic client
    4020                         } else {
    4021                             //Obtain new instance of client
    4022                             $this->paramsNewInstance('ClWS', 0);
    4023                             curl_setopt($ch, CURLOPT_URL, $this->url);
    4024                             curl_setopt($ch, CURLOPT_POST, false);
    4025                             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4026                             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4027                             $response = curl_exec($ch);
    4028                             // send response as JSON
    4029                             $response = json_decode($response, true);
    4030 
    4031                             if (curl_error($ch)) {
    4032                                 $this->writeFileLog('addSimpleFT9', $ch);
    4033                             } else if(empty($response)){
    4034                                 $this->writeFileLog('addSimpleFT9', 'EMPTY RESPONSE');             
    4035                             } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4036                                 $this->writeFileLog('addSimpleFT9', $response['messages'][0]['messageCodeLocale']);             
    4037                             } else {
    4038                                 $response['result'][0]['nome'] = 'Generic Client';
    4039                                 $response['result'][0]['clivd'] = true;
    4040                                
    4041                                 $response['result'][0]['preco'] = intval(str_replace('epv', '', $settings['backend']['productPriceColumn']));
    4042                  
    4043                                 //Save number id of client
    4044                                 $_SESSION['nrClient'] = $response['result'][0]['no'];
    4045                                 //Save vo with products
    4046                                 $_SESSION['voProducts'] = $response['result'][0];
    4047 
    4048                                 //Save data of client in Drive FX
    4049                                 $this->paramsSave('ClWS', $response);
    4050                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4051                                 curl_setopt($ch, CURLOPT_POST, false);
    4052                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4053                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4054                                 $response = curl_exec($ch);
    4055                                 // send response as JSON
    4056                                 $response = json_decode($response, true);
    4057 
    4058                                 if (curl_error($ch)) {
    4059                                     $this->writeFileLog('addSimpleFT10', $ch);
    4060                                 } else if(empty($response)){
    4061                                     $this->writeFileLog('addSimpleFT10', 'EMPTY RESPONSE');               
    4062                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4063                                     $this->writeFileLog('addSimpleFT10', $response['messages'][0]['messageCodeLocale']);
    4064                                     if($_SESSION['nrClient'] != ''){
    4065                                         //Inserted client in bd
    4066                                         $createClientSuccess = 1;
    4067                                     }               
    4068                                 } else {
    4069                                     //Inserted client in bd
    4070                                     $createClientSuccess = 1;
    4071                                 }
    4072                             }
    4073                         }
    4074                     }   
    4075                 }
    4076 
    4077                 //If client is created/obtained with success
    4078                 if($createClientSuccess == 1){
    4079                     //Obtain new instance of invoice
    4080                     $this->paramsNewInstance('FtWS', $settings['backend']['typeOfInvoice']);
    4081                     curl_setopt($ch, CURLOPT_URL, $this->url);
    4082                     curl_setopt($ch, CURLOPT_POST, false);
    4083                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4084                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4085                     $response = curl_exec($ch);     
    4086                     // send response as JSON
    4087                     $response = json_decode($response, true);
    4088 
    4089                     if (curl_error($ch)) {
    4090                         $this->writeFileLog('addSimpleFT11', $ch);
    4091                     } else if(empty($response)){
    4092                         $this->writeFileLog('addSimpleFT11', 'EMPTY RESPONSE');         
    4093                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4094                         $this->writeFileLog('addSimpleFT11', $response['messages'][0]['messageCodeLocale']);         
    4095                     } else {     
    4096                         //Obtain id of order and products
    4097                         $order = new WC_Order($orderid);
    4098                     //  $order = new WC_Order($order->post->ID);
    4099 
    4100                         $numberOrder = $order->post->ID;
    4101                         $i = 0;
    4102                          
    4103                         foreach($order->get_items() as $key => $value){
    4104                             if($value['variation_id'] != '' && $value['variation_id'] != 0){
    4105                                 $product = new WC_Product_Variation($value['variation_id']);
    4106                             } else {
    4107                                 $product = new WC_Product($value['product_id']);
    4108                             }
    4109                             $sku[$i] = $product->get_sku();
    4110                             $quantity[$i] = $value['qty'];
    4111                             $valueItem[$i] = $value['line_total'] + $value['line_tax'];
    4112                             ++$i;
    4113                         }
    4114                         //Save items of cart
    4115                         $_SESSION['listOfSku'] = $sku;
    4116                         $_SESSION['listOfQuantity'] = $quantity;
    4117                         $_SESSION['listOfValueItem'] = $valueItem;
    4118 
    4119                         //FT from Backend if is clicked "button tip"
    4120                         if(empty($_SESSION['listOfSku'][0])){
    4121                             //Obtain id of order and products
    4122                             $order = new WC_Order($orderid);
    4123                                        
    4124                             $i = 0;
    4125                             foreach($order->get_items() as $key => $value){
    4126                                 if($value['variation_id'] != '' && $value['variation_id'] != 0){
    4127                                     $product = new WC_Product_Variation($value['variation_id']);
    4128                                 } else {
    4129                                     $product = new WC_Product($value['product_id']);
    4130                                 }
    4131                                 $sku[$i] = $product->get_sku();
    4132                                 $quantity[$i] = $value['qty'];
    4133                                     $valueItem[$i] = $value['line_total'] + $value['line_tax'];
    4134                                 ++$i;
    4135                             }
    4136                             //Save items of cart
    4137                             $_SESSION['listOfSku'] = $sku;
    4138                             $_SESSION['listOfQuantity'] = $quantity;
    4139                             $_SESSION['listOfValueItem'] = $valueItem;
    4140                         }   
    4141                        
    4142                        
    4143                         //Save number of client in FT
    4144                         $response['result'][0]['no'] = $_SESSION['nrClient'];
    4145                        
    4146                        
    4147                         // build our web service full URL
    4148                         $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    4149                         $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    4150                         $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    4151                         $urlFt = $settings['backend']['url'] . $this->extraurl . "/REST/FtWS/actEntity";
    4152                         // Create map with request parameters
    4153                         $paramsFt =  array ('entity' => json_encode($response['result'][0]),
    4154                                             'code' => 0,
    4155                                             'newValue' => "{}");
    4156                         // Build Http query using params
    4157                         $queryFt = http_build_query($paramsFt);
    4158                         curl_setopt($ch, CURLOPT_URL, $urlFt);
    4159                         curl_setopt($ch, CURLOPT_POST, false);
    4160                         curl_setopt($ch, CURLOPT_POSTFIELDS, $queryFt);
    4161                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4162                         $response = curl_exec($ch);
    4163                        
    4164                         // send response as JSON
    4165                         $response = json_decode($response, true);   
    4166                    
    4167                         if (curl_error($ch)) {
    4168                             $this->writeFileLog('addSimpleFT13', $ch);
    4169                         } else if(empty($response)){
    4170                             $this->writeFileLog('addSimpleFT13', 'EMPTY RESPONSE');             
    4171                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4172                             $this->writeFileLog('addSimpleFT13', $response['messages'][0]['messageCodeLocale']);             
    4173                         } else {
    4174                             //Obtain new instance of FT
    4175                             // Only If have articles to FT
    4176                             if(!empty($_SESSION['listOfSku'])){
    4177                                
    4178                                 //Obtain name and price of delivery
    4179                                     global $wpdb;
    4180                                     $table_name = $wpdb->prefix."woocommerce_order_items";
    4181                                     $query = "SELECT * FROM %s WHERE order_id = %s and (order_item_type = 'shipping' or order_item_type='fee')";
    4182                                     $resultsShipping = $wpdb->get_results(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $numberOrder)));
    4183                                
    4184 
    4185                                     $table_name = $wpdb->prefix."woocommerce_order_itemmeta";
    4186                                     $query = "SELECT * FROM %s WHERE order_item_id = %s and (meta_key = 'cost' or meta_key='_line_total')";
    4187                                        
    4188                                    
    4189                                
    4190                                
    4191                                 //addNewBIsByRef is obsulet, push Bis to Bo and Then ActEntity
    4192 
    4193                                 foreach ($_SESSION['listOfSku'] as $key => $value) {
    4194                                     if($_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0){
    4195                                         $fi = new stdClass();
    4196                                
    4197                                         // Da sugestão 139643 - Alterou-se a variável a usar na query, uma vez que em casos que o carrinho possua mais que um item
    4198                                         //estamos a passar um array para a query. Como a varia $sku é igual a $_SESSION['listOfSku'], sobre o qual se está a iterar
    4199                                         //basta passar para a query a variável $value
    4200                                         //$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
    4201                                         $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $value ) );
    4202                                         $getproducttype = wc_get_product($product_id);
    4203                                         $typeproduct = $getproducttype->get_type();
    4204                                         if ($typeproduct == 'variation'){
    4205                                             if ( $product_id ) $product =  new WC_Product_Variation( $product_id );
    4206                                         }
    4207                                         else {
    4208                                             if ( $product_id ) $product =  new WC_Product( $product_id );
    4209                                         }
    4210                                
    4211                                         $fi->ref = $value;
    4212                                         $fi->design = $product->get_name();
    4213                                         $fi->qtt= $_SESSION['listOfQuantity'][$key];
    4214                                         $response['result'][0]['fis'][] = $fi;
    4215                                     }
    4216                                 }
    4217                                
    4218                            
    4219                                 $items = $order->get_items();
    4220                                    
    4221                                
    4222                                 $key=0;
    4223                                 foreach($items as $item => $values) {
    4224                                                                        
    4225                                         //$response['result'][0]['fis'][$key]->epv= ($values['line_total'] + $value['line_tax']) / $values['qty'];
    4226                                          if($settings['backend']['includeTaxonSendCost']=="true")
    4227                                                 $response['result'][0]['fis'][$key]->etiliquido = $values['line_total']  + $values['line_tax'];   
    4228                                         else
    4229                                             $response['result'][0]['fis'][$key]->etiliquido = $values['line_total']  ;   
    4230 
    4231                                            
    4232                                             $key++;                                                     
    4233                                 }
    4234                            
    4235                            
    4236                                
    4237                                 foreach ($resultsShipping as $resultShipping) {     
    4238                                     $resultDB = $wpdb->get_row(str_replace("'".$table_name."'", $table_name, $wpdb->prepare($query, $table_name, $resultShipping->order_item_id)));
    4239                                     //Introduce new line to add encharge of delivery
    4240                                    $fi= new stdClass();
    4241                                    $fi->design = $resultShipping->order_item_name;
    4242                                    $fi->qtt = 1;
    4243                                    $fi->etiliquido = $fi->epv = $resultDB->meta_value;
    4244                                      if($settings['backend']['includeTaxonSendCost']=="true")
    4245                                    $fi->ivaincl=true;   
    4246                                    
    4247                                     if($fi->etiliquido == 0){
    4248                                         $fi->qtt = 0;
    4249                                         $fi->ivaincl = false;
    4250                                     }
    4251                                    
    4252                                     $response['result'][0]['fis'][]= $fi;
    4253                                
    4254                                 }
    4255                                 $urlFt = $settings['backend']['url'] . $this->extraurl . "/REST/FtWS/actEntity";
    4256                                 // Create map with request parameters
    4257                                 $paramsFt =  array ('entity' => json_encode($response['result'][0]),
    4258                                             'code' => 0,
    4259                                             'newValue' => "{}");
    4260                                 // Build Http query using params
    4261                                 $paramsFt = http_build_query($paramsFt);
    4262                                 curl_setopt($ch, CURLOPT_URL, $urlFt);
    4263                                 curl_setopt($ch, CURLOPT_POST, false);
    4264                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $paramsFt);
    4265                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4266                                 $response = curl_exec($ch);
    4267                                
    4268                                 // send response as JSON
    4269                                 $response = json_decode($response, true);
    4270                            
    4271                                 /*$this->paramsNewInstanceByRef('FtWS', 'addNewFIsByRef', 'IdFtStamp', 'fiStampEditing', $response['result'][0]['ftstamp'], $_SESSION['listOfSku']);
    4272                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4273                                 curl_setopt($ch, CURLOPT_POST, false);
    4274                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4275                                 $response = curl_exec($ch);
    4276                                 // send response as JSON
    4277                                 $response = json_decode($response, true);   */
    4278                            
    4279                                 if (curl_error($ch)) {
    4280                                     $this->writeFileLog('addSimpleFT12', $ch);
    4281                                 } else if(empty($response)){
    4282                                     $this->writeFileLog('addSimpleFT12', 'EMPTY RESPONSE');         
    4283                                 } else if(isset($response['messages'][0]['messageCodeLocale']) && $response['messages'][0]['messageCode']!='messages.Business.Stocks.InvalidRefAutoCreate'){
    4284                                    
    4285                                     $this->writeFileLog('addSimpleFT12', $response['messages'][0]['messageCodeLocale']);         
    4286                                 } else { 
    4287                                    
    4288                                    
    4289                                    
    4290                                
    4291                                    
    4292                                     $billing_first_name = $order_meta['_billing_first_name'][0];
    4293                                     $billing_last_name = $order_meta['_billing_last_name'][0];
    4294                                     $billing_email = $order_meta['_billing_email'][0];
    4295                                     $billing_address_1 = $order_meta['_billing_address_1'][0];
    4296                                     $billing_city = $order_meta['_billing_city'][0];
    4297                                     $billing_phone = $order_meta['_billing_phone'][0]; 
    4298                                     $billing_postcode = $order_meta['_billing_postcode'][0];
    4299                                     $billing_nif = $order_meta['_billing_'.$settings['backend']['fieldNif']][0];
    4300            
    4301                                                                                
    4302                                    
    4303                                     $response['result'][0]['nome2'] = $billing_first_name . " " . $billing_last_name;
    4304                                     $response['result'][0]['morada'] = $billing_address_1;
    4305                                     $response['result'][0]['local'] = $billing_city;
    4306                                     $response['result'][0]['provincia'] = $billing_city;
    4307                                     $response['result'][0]['codpost'] = $billing_postcode;
    4308                                     $response['result'][0]['ncont'] = $billing_nif;
    4309                                     $response['result'][0]['telefone'] = $billing_phone;
    4310                                     $response['result'][0]['moradato'] = $shipping_address_1;
    4311                                     $response['result'][0]['localto'] = $shipping_city;
    4312                                     $response['result'][0]['codpostto'] = $shipping_postcode;
    4313                                     $response['result'][0]['pais'] = $nomePais;
    4314                                     $response['result'][0]['paisesstamp'] = $paisesstamp; 
    4315                                     $response['result'][0]['paisto'] = $nomePaisShipping;
    4316                                     $response['result'][0]['paisesstampto'] = $paisesstampShipping;   
    4317 
    4318                                    
    4319                                     //Update list of Quantity
    4320                                 /*  if (is_array($_SESSION['listOfQuantity'])){
    4321                                         foreach ($_SESSION['listOfQuantity'] as $key => $value){
    4322                                            
    4323                                             if( $_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0 && $response['result'][0]['fis'][$key]['qtt'] != $value){
    4324                                                 $response['result'][0]['fis'][$key]['qtt'] = $value;
    4325                                             }
    4326                                         }
    4327 
    4328                                     }*/
    4329                                     /*
    4330                                     //Update list of Value Item
    4331                                     if (is_array($_SESSION['listOfValueItem'])){
    4332                                       foreach ($_SESSION['listOfValueItem'] as $key => $value){
    4333                                         if( $_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0 && $response['result'][0]['fis'][$key]['epv'] != $value){
    4334                                           $response['result'][0]['fis'][$key]['epv'] = $value;
    4335                                         }
    4336                                       }
    4337                                     }*/
    4338 
    4339                                     //Eliminate comercial discount
    4340                                     if (is_array($_SESSION['listOfSku'])){
    4341                                         foreach ($_SESSION['listOfSku'] as $key => $value){
    4342                                          if( $_SESSION['listOfQuantity'][$key]*$_SESSION['listOfValueItem'][$key]!=0){
    4343                                             //Eliminate discount in field "desconto"
    4344                                             $response['result'][0]['fis'][$key]['desconto'] = 0;
    4345                                             //Eliminate discount in field "desconto"
    4346                                             $response['result'][0]['fis'][$key]['desc2'] = 0;
    4347                                             //Eliminate discount in field "desc3"
    4348                                             $response['result'][0]['fis'][$key]['desc3'] = 0;
    4349                                             //Eliminate discount in field "desc4"
    4350                                             $response['result'][0]['fis'][$key]['desc4'] = 0;
    4351                                             //Eliminate discount in field "desc5"
    4352                                             $response['result'][0]['fis'][$key]['desc5'] = 0;
    4353                                             //Eliminate discount in field "desc6"
    4354                                             $response['result'][0]['fis'][$key]['desc6'] = 0;
    4355                                            
    4356                                             //Eliminate financial discount of client
    4357                                             $response['result'][0]['efinv'] = 0; 
    4358                                             $response['result'][0]['fin'] = 0;
    4359                                          }
    4360                                         }
    4361                                     }
    4362                                    
    4363                                
    4364                                    
    4365                        
    4366                                     // build our web service full URL
    4367                                     $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html/');
    4368                                     $settings['backend']['url'] = rtrim($settings['backend']['url'], '/html');
    4369                                     $settings['backend']['url'] = rtrim($settings['backend']['url'], '/');
    4370                                     $urlFt = $settings['backend']['url'] . $this->extraurl . "/REST/FtWS/actEntity";
    4371                                     // Create map with request parameters
    4372                                     $paramsFt =  array ('entity' => json_encode($response['result'][0]),
    4373                                                         'code' => 0,
    4374                                                         'newValue' => "{}");
    4375                                     // Build Http query using params
    4376                                     $queryFt = http_build_query($paramsFt);
    4377                                     curl_setopt($ch, CURLOPT_URL, $urlFt);
    4378                                     curl_setopt($ch, CURLOPT_POST, false);
    4379                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $queryFt);
    4380                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4381                                     $response = curl_exec($ch);
    4382                                     // send response as JSON
    4383                                     $response = json_decode($response, true);   
    4384 
    4385                                     if (curl_error($ch)) {
    4386                                         $this->writeFileLog('addSimpleFT13', $ch);
    4387                                     } else if(empty($response)){
    4388                                         $this->writeFileLog('addSimpleFT13', 'EMPTY RESPONSE');             
    4389                                     } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4390                                         $this->writeFileLog('addSimpleFT13', $response['messages'][0]['messageCodeLocale']);             
    4391                                     } else {
    4392                                         //Save FT
    4393                                         $this->paramsSave('FtWS', $response);
    4394                                        
    4395                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    4396                                         curl_setopt($ch, CURLOPT_POST, false);
    4397                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4398                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4399                                         $response = curl_exec($ch);
    4400                                    
    4401                                         // send response as JSON
    4402                                        
    4403                                         $response = json_decode($response, true); 
    4404                                        
    4405                                         if (curl_error($ch)) {
    4406                                             $this->writeFileLog('addSimpleFT14', $ch);
    4407                                         } else if(empty($response)){
    4408                                             $this->writeFileLog('addSimpleFT14', 'EMPTY RESPONSE');               
    4409                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4410                                             $this->writeFileLog('addSimpleFT14', $response['messages'][0]['messageCodeLocale']);               
    4411                                         } else {
    4412                                             //Enable to sign Document
    4413                                             if($response['result'][0]['draftRecord'] == 1){
    4414                                                 //Save ftstamp of invoice
    4415                                                 $_SESSION['ftstamp'] = $response['result'][0]['ftstamp'];
    4416                                                 $_SESSION['fno'] =  $response['result'][0]['fno'];
    4417                                                 //Sign document
    4418                                                
    4419                                                 if($settings['backend']['toSignInvoice'] == 'on'){
    4420                                                
    4421                                                     $this->paramsSignDocument($response['result'][0]['ftstamp']);
    4422                                                     curl_setopt($ch, CURLOPT_URL, $this->url);
    4423                                                     curl_setopt($ch, CURLOPT_POST, false);
    4424                                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4425                                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4426                                                     $response = curl_exec($ch);
    4427                                                     // send response as JSON
    4428                                                     $response = json_decode($response, true);
    4429                        
    4430                                                 }
    4431                                                
    4432                                    
    4433                                                 if (curl_error($ch)) {
    4434                                                     $this->writeFileLog('addSimpleFT15', $ch);
    4435                                                 } else if(empty($response)){
    4436                                                     $this->writeFileLog('addSimpleFT15', 'EMPTY RESPONSE');                   
    4437                                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4438                                                     $this->writeFileLog('addSimpleFT15', $response['messages'][0]['messageCodeLocale']);                   
    4439                                                 } else {
    4440                                                     //Manage stock
    4441                                                     if($settings['backend']['manageStock'] == 'on'){
    4442                                                         $post_ID = sanitize_text_field( $_REQUEST['post_ID'] );
    4443                                                         $order_received = get_option('woocommerce_checkout_order_received_endpoint');
    4444                
    4445                                                         if(empty($order_received)){
    4446                                                             $order = new WC_Order( $post_ID );
    4447                                                         } else {
    4448                                                             $order = new WC_Order( $order_received );
    4449                                                         }
    4450 
    4451                                                         $i = 0;
    4452                                                         foreach($order->get_items() as $key => $value){
    4453                                                             $productReference = wc_get_product( $value['item_meta']['_product_id'][0] );
    4454                                                             $sku[$i] = $productReference->get_sku();
    4455            
    4456                                                             $productID[$sku[$i]] = $value['item_meta']['_product_id'][0];
    4457                                                         }
    4458 
    4459                                                         $i = 0;
    4460                                                         $count = count($_SESSION['voProducts']['fis']);
    4461                                                         while ($i < $count) {
    4462                                                             foreach ($_SESSION['voProducts']['fis'][$i] as $key => $value){
    4463                                                                 //Obtain product from reference
    4464                                                                 $this->paramsQuery('St', 'ref', $_SESSION['voProducts']['fis'][$i]['ref']);
    4465                                                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4466                                                                 curl_setopt($ch, CURLOPT_POST, false);
    4467                                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4468                                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4469                                                                 $response = curl_exec($ch);
    4470                                                                 // send response as JSON
    4471                                                                 $response = json_decode($response, true);
    4472 
    4473                                                                 if (curl_error($ch)) {
    4474                                                                     $this->writeFileLog('addSimpleFT16', $ch);
    4475                                                                 } else if(empty($response)){
    4476                                                                     $this->writeFileLog('addSimpleFT16', 'EMPTY RESPONSE');                           
    4477                                                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4478                                                                     $this->writeFileLog('addSimpleFT16', $response['messages'][0]['messageCodeLocale']);                           
    4479                                                                 } else {
    4480                                                                     //If find ref, update stock
    4481                                                                     foreach ($sku as $key => $value) {
    4482                                                                         if($_SESSION['voProducts']['fis'][$i]['ref'] == $value){
    4483                                                                             update_post_meta($productID[$value],'_stock',$response['result'][0]['stock']);
    4484                                                                         }
    4485                                                                     }
    4486                                                                 }   
    4487                                                             }
    4488                                                             ++$i;
    4489                                                         }
    4490                                                     }
    4491                                                     //Verify if are selected type of internal document and send invoice checkbox
    4492                                                     if(isset($settings['backend']['typeOfInvoice']) && $settings['backend']['createInvoice'] == 'on' && $settings['backend']['typeOfInvoice'] > 0 && isset($settings['backend']['sendInvoice'])){
    4493                                                         //Obtain reports for print
    4494                                                         $this->paramsGetReportForPrint();
    4495                                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    4496                                                         curl_setopt($ch, CURLOPT_POST, false);
    4497                                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4498                                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4499                                                         $response = curl_exec($ch);
    4500                                                         // send response as JSON
    4501                                                         $response = json_decode($response, true);
    4502 
    4503                                                         if (curl_error($ch)) {
    4504                                                             $this->writeFileLog('addSimpleFT17', $ch);
    4505                                                         } else if(empty($response)){
    4506                                                             $this->writeFileLog('addSimpleFT17', 'EMPTY RESPONSE');                       
    4507                                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4508                                                             $this->writeFileLog('addSimpleFT17', $response['messages'][0]['messageCodeLocale']);                       
    4509                                                         } else {
    4510                                                             //Verify if exists template as default
    4511                                                             $i = 0;
    4512                                                             $count = count($response['result']);
    4513                                                             $sendEmail = false;
    4514                                                             while ($i < $count) {
    4515                                                                 foreach ($response['result'][$i] as $key => $value){
    4516                                                                     if($key == 'enabled' && $value == 1){
    4517                                                                         $sendEmail = true;
    4518                                                                         $_SESSION['repstamp'] = $response['result'][$i]['repstamp'];
    4519                                                                         break;
    4520                                                                     }
    4521                                                                 }
    4522                                                                 ++$i;
    4523                                                             }
    4524                                                                                                    
    4525                                                             //If exists template as default
    4526                                                             if($sendEmail == true){                                     
    4527                                                                 //Obtain client
    4528                                                                 $this->paramsQuery('Cl', 'no', $_SESSION['nrClient']);
    4529                                                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4530                                                                 curl_setopt($ch, CURLOPT_POST, false);
    4531                                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4532                                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4533                                                                 $response = curl_exec($ch);
    4534                                                                 // send response as JSON
    4535                                                                 $response = json_decode($response, true);
    4536                                                                
    4537                                                                 if (curl_error($ch)) {
    4538                                                                     $this->writeFileLog('addSimpleFT18', $ch);
    4539                                                                 } else if(empty($response)){
    4540                                                                     $this->writeFileLog('addSimpleFT18', 'EMPTY RESPONSE');                           
    4541                                                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4542                                                                     $this->writeFileLog('addSimpleFT18', $response['messages'][0]['messageCodeLocale']);
    4543                                                                     $this->messagesError(utf8_decode(" in configuration of email to send them to client! Message from Backend: " . $response['messages'][0]['messageCodeLocale']));
    4544                                                                 } else {
    4545                                                                     if($response['result'][0]['email'] != ''){
    4546                                                                         //Email To
    4547                                                                         $_SESSION['emailClient'] = $response['result'][0]['email'];
    4548                                                                         //Email From
    4549                                                                         $infoAdmin = $this->get_settingsAdmin();
    4550                                                                         $emailAdmin = $infoAdmin[3]['default'];
    4551                                                                
    4552                                                                         //Send FT to email selected
    4553                                                                         $this->paramsSendReportEmail($_SESSION['repstamp'], $_SESSION['ftstamp'], $_SESSION['emailClient'], $emailAdmin, $settings['backend']['typeOfInvoice'],$_SESSION['fno'] );
    4554                                                                         curl_setopt($ch, CURLOPT_URL, $this->url);
    4555                                                                         curl_setopt($ch, CURLOPT_POST, false);
    4556                                                                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4557                                                                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4558                                                                
    4559                                                                    
    4560                                                                         $response = curl_exec($ch);
    4561                                                                    
    4562                                                                         // send response as JSON
    4563                                                                         $response = json_decode($response, true);
    4564                                                                        
    4565                                                                         if (curl_error($ch)) {
    4566                                                                             $this->writeFileLog('addSimpleFT19', $ch);
    4567                                                                         } else if(empty($response)){
    4568                                                                             $this->writeFileLog('addSimpleFT19', 'EMPTY RESPONSE');                               
    4569                                                                         } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4570                                                                             $this->writeFileLog('addSimpleFT19', $response['messages'][0]['messageCodeLocale']);                               
    4571                                                                         }
    4572                                                                     }
    4573                                                                 }
    4574                                                             }
    4575                                                         }
    4576                                                     }
    4577                                                 }
    4578                                             } else {
    4579                                                 if($_SESSION['gamaDRIVEFX'] >= 9) {
    4580                                                     //Manage stock
    4581                                                     if($settings['backend']['manageStock'] == 'on'){
    4582                                                         $post_ID = sanitize_text_field( $_REQUEST['post_ID'] );
    4583                                                         $order_received = get_option('woocommerce_checkout_order_received_endpoint');
    4584 
    4585                                                         if(empty($order_received)){
    4586                                                             $order = new WC_Order( $post_ID );
    4587                                                         } else {
    4588                                                             $order = new WC_Order( $order_received );
    4589                                                         }
    4590 
    4591                                                         $i = 0;
    4592                                                         foreach($order->get_items() as $key => $value){
    4593                                                             $productReference = wc_get_product( $value['item_meta']['_product_id'][0] );
    4594                                                             $sku[$i] = $productReference->get_sku();
    4595 
    4596                                                             $productID[$sku[$i]] = $value['item_meta']['_product_id'][0];
    4597                                                         }
    4598 
    4599                                                         $i = 0;
    4600                                                         $count = count($_SESSION['voProducts']['fis']);
    4601                                                         while ($i < $count) {
    4602                                                             foreach ($_SESSION['voProducts']['fis'][$i] as $key => $value){
    4603                                                                 //Obtain product from reference
    4604                                                                 $this->paramsQuery('St', 'ref', $_SESSION['voProducts']['fis'][$i]['ref']);
    4605                                                                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4606                                                                 curl_setopt($ch, CURLOPT_POST, false);
    4607                                                                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4608                                                                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4609                                                                 $response = curl_exec($ch);
    4610                                                                 // send response as JSON
    4611                                                                 $response = json_decode($response, true);
    4612 
    4613                                                                 if (curl_error($ch)) {
    4614                                                                     $this->writeFileLog('addSimpleFT20', $ch);
    4615                                                                 } else if(empty($response)){
    4616                                                                     $this->writeFileLog('addSimpleFT20', 'EMPTY RESPONSE');                         
    4617                                                                 } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4618                                                                     $this->writeFileLog('addSimpleFT20', $response['messages'][0]['messageCodeLocale']);                         
    4619                                                                 } else {
    4620                                                                     //If find ref, update stock
    4621                                                                     foreach ($sku as $key => $value) {
    4622                                                                         if($_SESSION['voProducts']['fis'][$i]['ref'] == $value){
    4623                                                                             update_post_meta($productID[$value],'_stock',$response['result'][0]['stock']);
    4624                                                                         }
    4625                                                                     }
    4626                                                                 }   
    4627                                                             }
    4628                                                             ++$i;
    4629                                                         }
    4630                                                     }
    4631                                                 }
    4632                                             }
    4633                                         }
    4634                                     }
    4635                                 }
    4636                             }
    4637                         }
    4638                     }
    4639                 }
    4640             }
    4641             $this->writeFileLog('addSimpleft', "Sai simple ft:" . $_REQUEST['order_id']);
    4642         }
    4643 
    4644         //Add products from Drive FX in online shop
     1623            return $sendedEmail;                       
     1624        }
     1625
     1626        //Add products from Phc in online shop
    46451627        function addProduct($nomeProduct, $contentProduct, $excerptProduct, $slugNameProduct, $stockUnitsProduct, $price, $sku, $manageStock, $visible, $thumb_url){
    46461628            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     
    46521634                          'post_type'    => "product"
    46531635                         );
    4654             /*$post = array(
    4655                           'post_title'   => $nomeProduct,
    4656                           'post_content' => $contentProduct,
    4657                           'post_status'  => "publish",
    4658                           'post_excerpt' => $excerptProduct,
    4659                           'post_name'    => $slugNameProduct,
    4660                           'post_type'    => "product"
    4661                          );
    4662          */
     1636       
    46631637            //Create product/post:
    46641638            $new_post_id = wp_insert_post($post, $wp_error);
     
    46921666        //Show list of products
    46931667        public function listProducts(){
     1668
    46941669            $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
     1670
     1671            // get Credentials
     1672            $credentials = $this->syncro_services->fetchCredentials();     
    46951673            //Obtain configuration to make login
    4696             $this->paramsLogin();
     1674            $ch = $this->auth_services->PHCLogin($ch, $credentials);   
    46971675            //initial request with login data
    4698             $ch = curl_init();
    4699             //URL to save cookie "ASP.NET_SessionId"
    4700             curl_setopt($ch, CURLOPT_URL, $this->url);
    4701             curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    4702             curl_setopt($ch, CURLOPT_POST, true);
    4703             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    4704             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4705             //Parameters passed to POST
    4706             curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4707             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    4708             curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    4709             curl_setopt($ch, CURLOPT_COOKIEJAR, '');
    4710             curl_setopt($ch, CURLOPT_COOKIEFILE, '');
    4711             $response = curl_exec($ch);
     1676            $response = curl_exec($ch);
    47121677            // send response as JSON
    4713             $response = json_decode($response, true);
     1678            $response = json_decode($response, true);
     1679            // get the temporary token and insert in credentials object
     1680            $credentials->token = $response['result'][0]['token'];
    47141681
    47151682            if (curl_error($ch)) {
    4716                 $this->writeFileLog('listProducts', $ch);
     1683                $this->logs->writeFileLog('listProducts', $ch);
    47171684                unset($_SESSION['username']);
    47181685            } else if(empty($response)){
    4719                 $this->writeFileLog('listProducts', 'EMPTY RESPONSE');
     1686                $this->logs->writeFileLog('listProducts', 'EMPTY RESPONSE');
    47201687                unset($_SESSION['username']);
    47211688            } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4722                 $this->writeFileLog('listProducts', $response['messages'][0]['messageCodeLocale']);
     1689                $this->logs->writeFileLog('listProducts', $response['messages'][0]['messageCodeLocale']);
    47231690                unset($_SESSION['username']);
    4724             } else {     
     1691            } else {
     1692                               
     1693                // Get condition of Tax Tab from Woocommerce -> Configuration -> Tax
     1694                $woocommerce_calc_taxes = get_option('woocommerce_calc_taxes');
     1695                $woocommerce_prices_include_tax = get_option('woocommerce_prices_include_tax');
     1696
     1697                //Know which column is used to see iva included based on backend configuration of plugin
     1698                switch ($settings['backend']['productPriceColumn']) {
     1699                    case 'epv1':
     1700                        $columnIva = 'iva1incl';
     1701                        break;
     1702                    case 'epv2':
     1703                        $columnIva = 'iva2incl';
     1704                        break;
     1705                    case 'epv3':
     1706                        $columnIva = 'iva3incl';
     1707                        break;
     1708                    case 'epv4':
     1709                        $columnIva = 'iva4incl';
     1710                        break;
     1711                }
    47251712               
    4726                 //Obtain gama of Drive FX
    4727                 $this->paramsGetBackEndInfo();
    4728 
    4729                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4730                 curl_setopt($ch, CURLOPT_POST, false);
    4731                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4732                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4733                 $response = curl_exec($ch);
    4734                 // send response as JSON
    4735                 $response = json_decode($response, true);
     1713                //Obtain gama of PHC
     1714                $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     1715
     1716                //$this->logs->writeFileLog('ListProducts BackEnd:', $response);
    47361717
    47371718                if (curl_error($ch)) {
    4738                     $this->writeFileLog('setCommunicationFx2WooCommerce', $ch);
     1719                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    47391720                } else if(empty($response)){
    4740                     $this->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
     1721                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
    47411722                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4742                     $this->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
     1723                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
    47431724                } else {
    47441725                    $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
     
    47461727               
    47471728                //Obtain parameter of manage stock
    4748                 $this->paramsGetFrontendInfo();
    4749 
    4750                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4751                 curl_setopt($ch, CURLOPT_POST, false);
    4752                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4753                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4754                 $response = curl_exec($ch);
    4755                 // send response as JSON
    4756                 $response = json_decode($response, true);
     1729                $response = $this->utils_services->paramsGetFrontendInfo($ch, $credentials);
     1730
     1731                //$this->logs->writeFileLog('ListProducts FrontEnd:', $response);
    47571732               
    47581733                if (curl_error($ch)) {
    4759                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', $ch);
     1734                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $ch);
    47601735                } else if(empty($response)){
    4761                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', 'EMPTY RESPONSE');
     1736                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', 'EMPTY RESPONSE');
    47621737                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4763                     $this->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
     1738                    $this->logs->writeFileLog('setCommunicationFx2WooCommerce.1', $response['messages'][0]['messageCodeLocale']);
    47641739                } else {
    47651740                    foreach ($response['result'] as $key => $value){
     
    47701745                }
    47711746               
    4772                 //Verify GAMA or parameter "Manage stock" or value choose in warehouse dropdown
    47731747                if($_SESSION['gamaDRIVEFX'] < 9 || $settings['backend']['warehouse'] == -1 || $settings['backend']['warehouse'] == ''){
    4774                     $this->paramsQuery2('St');
     1748
     1749                    // Products with VAT included in price
     1750                    if(($woocommerce_calc_taxes == "no") || ($woocommerce_calc_taxes == "yes" && $woocommerce_prices_include_tax == "yes")) {   
     1751
     1752                        if ($settings['backend']['positiveStock'] == 'on'){
     1753                            $response = $this->utils_services->paramsQuery5($ch, $credentials, 'St', '2', 'stock', '0', '0', $columnIva, '1');
     1754                        } else {
     1755                            $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0' , $columnIva, '1');
     1756                        }                   
     1757                       
     1758                        //$this->logs->writeFileLog('StList response1:', $response);
     1759
     1760                    }
     1761                    // Products without VAT included in price
     1762                    else if($woocommerce_calc_taxes == "yes" && $woocommerce_prices_include_tax == 'no'){
     1763
     1764                        if ($settings['backend']['positiveStock'] == 'on'){
     1765                            $response = $this->utils_services->paramsQuery5($ch, $credentials, 'St', '2', 'stock', '0', '0', $columnIva, '0');
     1766                        } else {
     1767                            $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '0' , $columnIva, '0');
     1768                        }
     1769                         
     1770                        //$this->logs->writeFileLog('StList response2:', $response);       
     1771                       
     1772                    }
    47751773                } else {
    4776                     //$this->paramsQuery('Sa', "armazem", $settings['backend']['warehouse']);
    4777                     $this->paramsQuery2('St');
     1774                    $response = $this->utils_services->entityName_Query($ch, $credentials, 'St');
    47781775                }       
    4779 
    4780                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4781                 curl_setopt($ch, CURLOPT_POST, false);
    4782                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4783                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4784                 $response = curl_exec($ch);
    4785                 // send response as JSON
    4786                 $response = json_decode($response, true); 
     1776               
    47871777
    47881778                if (curl_error($ch)) {
    4789                     $this->writeFileLog('listProducts2', $ch);
     1779                    $this->logs->writeFileLog('listProducts2', $ch);
    47901780                } else if(empty($response)){
    4791                     $this->writeFileLog('listProducts2', 'EMPTY RESPONSE');       
     1781                    $this->logs->writeFileLog('listProducts2', 'EMPTY RESPONSE');       
    47921782                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4793                     $this->writeFileLog('listProducts2', $response['messages'][0]['messageCodeLocale']);       
    4794                 } else {           
    4795                    
     1783                    $this->logs->writeFileLog('listProducts2', $response['messages'][0]['messageCodeLocale']);       
     1784                } else {   
     1785
    47961786                    foreach ($response['result'] as $key => $value){
    47971787                        if($key > 0){
    47981788                            $refArray .= ",";
    47991789                        }
    4800                         $arrayRef[$value['ref']] = $value['stock'];
    4801                        
     1790                        // filter stock - uninvoiced order
     1791                        if ($settings['backend']['filterStock'] == 'on'){
     1792                            // Get all the stock (entries)
     1793                            $responseFilter = $this->utils_services->doubleFilter($ch, $credentials, 'Sl', 'ref', $value['ref'], 'entrada', '1');   
     1794                                                               
     1795                            $totalStock = array_reduce(
     1796                                $responseFilter['result'],
     1797                                function( $currentTotal, $sl ) {
     1798                                    return $currentTotal += intval($sl["qtt"]);
     1799                                },
     1800                                0
     1801                            );     
     1802                           
     1803                            if ($settings['backend']['positiveStock'] == 'on'){
     1804                                //Extract the customer ordrers from total stock
     1805                                if ($totalStock - $value['qttcli'] > 0){
     1806                                    $arrayRef[$value['ref']] = $totalStock - $value['qttcli']; 
     1807                                }       
     1808                            } else {
     1809                                $arrayRef[$value['ref']] = $totalStock - $value['qttcli']; 
     1810                            }                                               
     1811                        } else{
     1812                            $arrayRef[$value['ref']] = $value['stock'];
     1813                        }                       
    48021814                        $refArray .= '{
    48031815                                        "comparison":0,
     
    48101822                                      }';   
    48111823                    }       
    4812 
    4813                     // build our web service full URL
    4814                     $this->paramsQuery3('St', $refArray);
    4815                     curl_setopt($ch, CURLOPT_URL, $this->url);
    4816                     curl_setopt($ch, CURLOPT_POST, false);
    4817                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4818                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4819                     $response = curl_exec($ch);
    4820                     // send response as JSON
    4821                     $response = json_decode($response, true);               
     1824       
     1825                    $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);                   
     1826                   
     1827                    //$this->logs->writeFileLog('StList response:', $response);
    48221828
    48231829                    if (curl_error($ch)) {
    4824                         $this->writeFileLog('listProducts3', $ch);
     1830                        $this->logs->writeFileLog('listProducts3', $ch);
    48251831                    } else if(empty($response)){
    4826                         $this->writeFileLog('listProducts3', 'EMPTY RESPONSE');               
     1832                        $this->logs->writeFileLog('listProducts3', 'EMPTY RESPONSE');             
    48271833                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4828                         $this->writeFileLog('listProducts3', $response['messages'][0]['messageCodeLocale']);             
     1834                        $this->logs->writeFileLog('listProducts3', $response['messages'][0]['messageCodeLocale']);               
    48291835                    } else {
    4830                         //Know which column is used to see iva included based on backend configuration of plugin
    4831                         switch ($settings['backend']['productPriceColumn']) {
    4832                             case 'epv1':
    4833                                 $columnIva = 'iva1incl';
    4834                                 break;
    4835                             case 'epv2':
    4836                                 $columnIva = 'iva2incl';
    4837                                 break;
    4838                             case 'epv3':
    4839                                 $columnIva = 'iva3incl';
    4840                                 break;
    4841                             case 'epv4':
    4842                                 $columnIva = 'iva4incl';
    4843                                 break;
    4844                         }
    4845 
     1836                       
    48461837                        //Create rows with information of products
    48471838                        $tableProducts = '';
     
    48571848                            if(!empty($settings['backend']['productPriceColumn']) && $settings['backend']['productPriceColumn'] != 'epv0'){
    48581849                                foreach ($response['result'] as $key => $value) {
    4859                                     $woocommerce_calc_taxes = get_option('woocommerce_calc_taxes');
    4860                                     $woocommerce_prices_include_tax = get_option('woocommerce_prices_include_tax');
    4861 
    4862                                     //Configured in tax tab of woocommerce
    4863                                     if(($woocommerce_calc_taxes == "no") || ($woocommerce_calc_taxes == "yes" && $woocommerce_prices_include_tax == "yes")) {                               
    4864                                         if($response['result'][$key][$columnIva] == 1){
    4865                                             $tableProducts .= "<tr>";
    4866                                             if(wc_get_product_id_by_sku( $response['result'][$key]['ref'] )== ""){
    4867                                                 if($arrayRef[$response['result'][$key]['ref']] < 0){
    4868                                                     $tableProducts .= "<td style='text-align: left;'><input type='checkbox' disabled name='checkboxes' value='".$response['result'][$key]['ref']."'></td>";
    4869                                                 } else {
    4870                                                     $tableProducts .= "<td style='text-align: left;'><input type='checkbox' name='checkboxes' value='".$response['result'][$key]['ref']."'></td>";
    4871                                                 }
    4872                                             } else {
    4873                                                 $tableProducts .= "<td style='text-align: left;'><div class='updateStockShop' id='".$response['result'][$key]['ref']."'><img src='".plugins_url('/images/right.png', __FILE__)."' alt='' width='16' height='16'></div></td>";
    4874                                             }
    4875 
    4876                                             $tableProducts .= "<td style='text-align: left;'>". $response['result'][$key]['ref'].   
    4877                                                               "</td><td style='text-align: left;'>". $response['result'][$key]['design'].
    4878                                                               "</td><td style='text-align: left;'>". $response['result'][$key]['familia']."</td>";
    4879                                            
    4880                                             //Only exists stocks after Star GAMA
    4881                                             if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){
    4882                                                 if($response['result'][$key]['stock'] < 0){
    4883                                                     $tableProducts .= "<td style='text-align: right; color: red;'>".$arrayRef[$response['result'][$key]['ref']]."</td></tr>";
    4884                                                 } else {
    4885                                                     $tableProducts .= "<td style='text-align: right;'>".$arrayRef[$response['result'][$key]['ref']]."</td></tr>";
    4886                                                 }
    4887                                             }
     1850
     1851                                    //Create Table                                     
     1852                                    $tableProducts .= "<tr>";
     1853                                    if(wc_get_product_id_by_sku( $response['result'][$key]['ref'] )== ""){
     1854                                        if($arrayRef[$response['result'][$key]['ref']] < 0){
     1855                                            $tableProducts .= "<td style='text-align: left;'><input type='checkbox' disabled name='checkboxes' value='".$response['result'][$key]['ref']."'></td>";
     1856                                        } else {
     1857                                            $tableProducts .= "<td style='text-align: left;'><input type='checkbox' name='checkboxes' value='".$response['result'][$key]['ref']."'></td>";
    48881858                                        }
    4889                                     } else if($woocommerce_calc_taxes == "yes" && $woocommerce_prices_include_tax == 'no'){
    4890                                     echo "entrou222";
    4891                                         if($response['result'][$key][$columnIva] == 0){
    4892                                             $tableProducts .= "<tr>";
    4893                                             if(wc_get_product_id_by_sku( $response['result'][$key]['ref'] )== ""){
    4894                                                 if($arrayRef[$response['result'][$key]['ref']] < 0){
    4895                                                     $tableProducts .= "<td style='text-align: left;'><input type='checkbox' disabled name='checkboxes' value='".$response['result'][$key]['ref']."'></td>";
    4896                                                 } else {
    4897                                                     $tableProducts .= "<td style='text-align: left;'><input type='checkbox' name='checkboxes' value='".$response['result'][$key]['ref']."'></td>";
    4898                                                 }
    4899                                             } else {
    4900                                                 $tableProducts .= "<td style='text-align: left;'><div class='updateStockShop' id='".$response['result'][$key]['ref']."'><img src='".plugins_url('/images/right.png', __FILE__)."' alt='' width='16' height='16'></div></td>";
    4901                                             }
    4902 
    4903                                             $tableProducts .= "<td style='text-align: left;'>".$response['result'][$key]['ref'].   "</td><td style='text-align: left;'>".$response['result'][$key]['design']."</td><td style='text-align: left;'>".
    4904                                                                  $response['result'][$key]['familia']."</td>";
    4905                                            
    4906                                             //Only exists stocks after Star GAMA
    4907                                             if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){
    4908                                                 if($response['result'][$key]['stock'] < 0){
    4909                                                   $tableProducts .= "<td style='text-align: right; color: red;'>".$arrayRef[$response['result'][$key]['ref']]."</td></tr>";
    4910                                                 } else {
    4911                                                   $tableProducts .= "<td style='text-align: right;'>".$arrayRef[$response['result'][$key]['ref']]."</td></tr>";
    4912                                                 }
    4913                                             }
     1859                                    } else {
     1860                                        $tableProducts .= "<td style='text-align: left;'><div class='updateStockShop' id='".$response['result'][$key]['ref']."'><img src='".plugins_url('/images/right.png', __FILE__)."' alt='' width='16' height='16'></div></td>";
     1861                                    }
     1862
     1863                                    $tableProducts .= "<td style='text-align: left;'>". $response['result'][$key]['ref'].   
     1864                                                        "</td><td style='text-align: left;'>". $response['result'][$key]['design'].
     1865                                                        "</td><td style='text-align: left;'>". $response['result'][$key]['familia']."</td>";
     1866                                   
     1867                                    //Only exists stocks after Star GAMA
     1868                                    if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){
     1869                                        if($response['result'][$key]['stock'] < 0){
     1870                                            $tableProducts .= "<td style='text-align: right; color: red;'>".$arrayRef[$response['result'][$key]['ref']]."</td></tr>";
     1871                                        } else {
     1872                                            $tableProducts .= "<td style='text-align: right;'>".$arrayRef[$response['result'][$key]['ref']]."</td></tr>";
    49141873                                        }
    4915                                     }
     1874                                    }                           
    49161875                                }
    49171876                                echo $tableProducts;
    49181877                            } else {
    4919                                 $this->writeFileLog('listProducts4', 'Products: Empty productPriceColumn');
     1878                                $this->logs->writeFileLog('listProducts4', 'Products: Empty productPriceColumn');
    49201879                            } 
    49211880                        }
     
    49241883            }   
    49251884            //Logout
    4926             $this->paramsLogout();
    4927             curl_setopt($ch, CURLOPT_URL, $this->url);
    4928             curl_setopt($ch, CURLOPT_POST, false);
    4929             curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4930             $response = curl_exec($ch);
    4931             curl_close ( $ch );
     1885            $this->auth_services->PHCLogout($ch, $credentials);
    49321886
    49331887            return $tableProducts;
     
    49381892            if(is_array($refs)){
    49391893                $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    4940                 //Obtain configuration to make login
    4941                 $this->paramsLogin();
     1894                // get Credentials
     1895                $credentials = $this->syncro_services->fetchCredentials();             
     1896                // Obtain configuration to make login
     1897                $ch = $this->auth_services->PHCLogin($ch, $credentials);
    49421898                //initial request with login data
    4943                 $ch = curl_init();
    4944                 //URL to save cookie "ASP.NET_SessionId"
    4945                 curl_setopt($ch, CURLOPT_URL, $this->url);
    4946                 curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    4947                 curl_setopt($ch, CURLOPT_POST, true);
    4948                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    4949                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4950                 //Parameters passed to POST
    4951                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    4952                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    4953                 curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    4954                 curl_setopt($ch, CURLOPT_COOKIEJAR, '');
    4955                 curl_setopt($ch, CURLOPT_COOKIEFILE, ''); 
    4956                 $response = curl_exec($ch);
     1899                $response = curl_exec($ch);     
    49571900                // send response as JSON
    49581901                $response = json_decode($response, true);
     1902                // get the temporary token and insert in credentials object
     1903                $credentials->token = $response['result'][0]['token'];
     1904               
     1905                //$this->logs->writeFileLog('SaveProducts Login:', $response);
    49591906
    49601907                if (curl_error($ch)) {
    4961                     $this->writeFileLog('saveProducts', $ch);
     1908                    $this->logs->writeFileLog('saveProducts', $ch);
    49621909                    unset($_SESSION['username']);
    49631910                } else if(empty($response)){
    4964                     $this->writeFileLog('saveProducts', 'EMPTY RESPONSE');
     1911                    $this->logs->writeFileLog('saveProducts', 'EMPTY RESPONSE');
    49651912                    unset($_SESSION['username']);
    49661913                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4967                     $this->writeFileLog('saveProducts', $response['messages'][0]['messageCodeLocale']);
     1914                    $this->logs->writeFileLog('saveProducts', $response['messages'][0]['messageCodeLocale']);
    49681915                    unset($_SESSION['username']);
    49691916                } else { 
    49701917                   
    4971                     //Obtain gama of Drive FX
    4972                     $this->paramsGetBackEndInfo();
    4973 
    4974                     curl_setopt($ch, CURLOPT_URL, $this->url);
    4975                     curl_setopt($ch, CURLOPT_POST, false);
    4976                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    4977                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    4978                     $response = curl_exec($ch);
    4979                     // send response as JSON
    4980                     $response = json_decode($response, true);
     1918                    //Obtain gama of PHC
     1919                    $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     1920
     1921                    //$this->logs->writeFileLog('SaveProducts BackEnd:', $response);
    49811922
    49821923                    if (curl_error($ch)) {
    4983                         $this->writeFileLog('setCommunicationFx2WooCommerce', $ch);
     1924                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    49841925                    } else if(empty($response)){
    4985                         $this->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
     1926                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
    49861927                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    4987                         $this->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
     1928                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
    49881929                    } else {
    49891930                        $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
     
    49921933                    //Verify GAMA or value choose in warehouse dropdown
    49931934                    if($_SESSION['gamaDRIVEFX'] < 9 || $settings['backend']['warehouse'] == -1 || $settings['backend']['warehouse'] == ''){
    4994                         $this->paramsQuery2('St');
     1935                        if ($settings['backend']['positiveStock'] == 'on'){
     1936                            $response = $this->utils_services->filterItem_compare($ch, $credentials, 'St', '2', 'stock', '0');
     1937                        } else {
     1938                            $response = $this->utils_services->entityName_Query($ch, $credentials, 'St');
     1939                        }
    49951940                    } else {
    4996                         $this->paramsQuery('Sa', "armazem", $settings['backend']['warehouse']);
    4997                     }
    4998                     curl_setopt($ch, CURLOPT_URL, $this->url);
    4999                     curl_setopt($ch, CURLOPT_POST, false);
    5000                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    5001                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5002                     $response = curl_exec($ch);
    5003                     // send response as JSON
    5004                     $response = json_decode($response, true); 
     1941                        $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Sa', 'armazem', $settings['backend']['warehouse']);
     1942                    }
     1943                   
     1944                    //$this->logs->writeFileLog('SaveProducts St ou Sa:', $response);
    50051945
    50061946                    if (curl_error($ch)) {
    5007                         $this->writeFileLog('saveProducts2', $ch);
     1947                        $this->logs->writeFileLog('saveProducts2', $ch);
    50081948                    } else if(empty($response)){
    5009                         $this->writeFileLog('saveProducts2', 'EMPTY RESPONSE');         
     1949                        $this->logs->writeFileLog('saveProducts2', 'EMPTY RESPONSE');         
    50101950                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5011                         $this->writeFileLog('saveProducts2', $response['messages'][0]['messageCodeLocale']);         
     1951                        $this->logs->writeFileLog('saveProducts2', $response['messages'][0]['messageCodeLocale']);         
    50121952                    } else {
    50131953                        $i = 0;
     
    50421982
    50431983                        //Obtain products from st
    5044                         $this->paramsQuery3('St', $refArray);
    5045                         curl_setopt($ch, CURLOPT_URL, $this->url);
    5046                         curl_setopt($ch, CURLOPT_POST, false);
    5047                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    5048                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5049                         $response = curl_exec($ch);
    5050                         // send response as JSON
    5051                         $response = json_decode($response, true);   
     1984                        $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);   
     1985               
     1986                        //$this->logs->writeFileLog('SaveList St:', $response); 
    50521987
    50531988                        if (curl_error($ch)) {
    5054                             $this->writeFileLog('saveProducts3', $ch);
     1989                            $this->logs->writeFileLog('saveProducts3', $ch);
    50551990                        } else if(empty($response)){
    5056                             $this->writeFileLog('saveProducts3', 'EMPTY RESPONSE');           
     1991                            $this->logs->writeFileLog('saveProducts3', 'EMPTY RESPONSE');           
    50571992                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5058                             $this->writeFileLog('saveProducts3', $response['messages'][0]['messageCodeLocale']);           
     1993                            $this->logs->writeFileLog('saveProducts3', $response['messages'][0]['messageCodeLocale']);           
    50591994                        } else {
    50601995                            //If exists selected products 
     
    50942029                }
    50952030                //Logout
    5096                 $this->paramsLogout();
     2031                $this->auth_services->PHCLogout($ch, $credentials);
    50972032                //session_destroy();
    5098                 curl_setopt($ch, CURLOPT_URL, $this->url);
    5099                 curl_setopt($ch, CURLOPT_POST, false);
    5100                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5101                 $response = curl_exec($ch);
    51022033            } else {
    51032034                echo "empty_refs";
     
    51092040            if(is_array($refs)){
    51102041                $settings = get_option(DRIVEFXWOOCOMMERCE_PLUGIN_NAME);
    5111                 //Obtain configuration to make login
    5112                 $this->paramsLogin();
     2042                // get Credentials
     2043                $credentials = $this->syncro_services->fetchCredentials();         
     2044                // Obtain configuration to make login
     2045                $ch = $this->auth_services->PHCLogin($ch, $credentials);     
    51132046                //initial request with login data
    5114                 $ch = curl_init();
    5115                 //URL to save cookie "ASP.NET_SessionId"
    5116                 curl_setopt($ch, CURLOPT_URL, $this->url);
    5117                 curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    5118                 curl_setopt($ch, CURLOPT_POST, true);
    5119                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    5120                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5121                 //Parameters passed to POST
    5122                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    5123                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    5124                 curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    5125                 curl_setopt($ch, CURLOPT_COOKIEJAR, '');
    5126                 curl_setopt($ch, CURLOPT_COOKIEFILE, ''); 
    5127                 $response = curl_exec($ch);
     2047                $response = curl_exec($ch);     
    51282048                // send response as JSON
    51292049                $response = json_decode($response, true);
     2050                // get the temporary token and insert in credentials object
     2051                $credentials->token = $response['result'][0]['token'];
     2052
     2053                //$this->logs->writeFileLog('Login response:', $response);
    51302054
    51312055                if (curl_error($ch)) {
    5132                     $this->writeFileLog('updateStocksProducts', $ch);
     2056                    $this->logs->writeFileLog('updateStocksProducts', $ch);
    51332057                    unset($_SESSION['username']);
    51342058                } else if(empty($response)){
    5135                     $this->writeFileLog('updateStocksProducts', 'EMPTY RESPONSE');
     2059                    $this->logs->writeFileLog('updateStocksProducts', 'EMPTY RESPONSE');
    51362060                    unset($_SESSION['username']);
    51372061                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5138                     $this->writeFileLog('updateStocksProducts', $response['messages'][0]['messageCodeLocale']);
     2062                    $this->logs->writeFileLog('updateStocksProducts', $response['messages'][0]['messageCodeLocale']);
    51392063                    unset($_SESSION['username']);
    51402064                } else { 
    51412065                   
    5142                     //Obtain gama of Drive FX
    5143                     $this->paramsGetBackEndInfo();
    5144 
    5145                     curl_setopt($ch, CURLOPT_URL, $this->url);
    5146                     curl_setopt($ch, CURLOPT_POST, false);
    5147                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    5148                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5149                     $response = curl_exec($ch);
    5150                     // send response as JSON
    5151                     $response = json_decode($response, true);
     2066                     //Obtain gama of PHC
     2067                     $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     2068
     2069                     //$this->logs->writeFileLog('Get Gama:', $response);
    51522070
    51532071                    if (curl_error($ch)) {
    5154                         $this->writeFileLog('setCommunicationFx2WooCommerce', $ch);
     2072                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    51552073                    } else if(empty($response)){
    5156                         $this->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
     2074                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
    51572075                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5158                         $this->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
     2076                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
    51592077                    } else {
    51602078                        $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
     
    51632081                    //Verify GAMA or value choose in warehouse dropdown
    51642082                    if($_SESSION['gamaDRIVEFX'] < 9 || $settings['backend']['warehouse'] == -1 || $settings['backend']['warehouse'] == ''){
    5165                         $this->paramsQuery2('St');
     2083                        $response = $this->utils_services->entityName_Query($ch, $credentials, 'St');
     2084
     2085                        //$this->logs->writeFileLog('st:', $response);
    51662086                    } else {
    5167                         $this->paramsQuery('Sa', "armazem", $settings['backend']['warehouse']);
    5168                     }
    5169                     curl_setopt($ch, CURLOPT_URL, $this->url);
    5170                     curl_setopt($ch, CURLOPT_POST, false);
    5171                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    5172                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5173                     $response = curl_exec($ch);
    5174                     // send response as JSON
    5175                     $response = json_decode($response, true); 
     2087                        $response = $this->utils_services->filterItem_Query($ch, $credentials, 'Sa', 'armazem', $settings['backend']['warehouse']);
     2088                    }
    51762089                   
    51772090                    if (curl_error($ch)) {
    5178                         $this->writeFileLog('updateStocksProducts2', $ch);
     2091                        $this->logs->writeFileLog('updateStocksProducts2', $ch);
    51792092                    } else if(empty($response)){
    5180                         $this->writeFileLog('updateStocksProducts2', 'EMPTY RESPONSE');       
     2093                        $this->logs->writeFileLog('updateStocksProducts2', 'EMPTY RESPONSE');       
    51812094                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5182                         $this->writeFileLog('updateStocksProducts2', $response['messages'][0]['messageCodeLocale']);       
     2095                        $this->logs->writeFileLog('updateStocksProducts2', $response['messages'][0]['messageCodeLocale']);       
    51832096                    } else {
    5184                    
    5185                         $count = count($response['result']);
    5186                    
     2097                       
     2098                        $count = count($response['result']);                   
    51872099                        $refArray = array();
    51882100                        $i=0;
    51892101                        while ($i < $count) {
    51902102                            foreach ($response['result'][$i] as $key => $value){       
    5191                                         $refArray[$i]=array();
    5192                                         $refArray[$i]['stock'] = $response['result'][$i]['stock'];
    5193                                         $refArray[$i]['sku'] = $response['result'][$i]['ref'];
     2103                                $refArray[$i]=array();
     2104                                // filter stock - uninvoiced order
     2105                                if ($settings['backend']['filterStock'] == 'on'){
     2106                                    // Get all the stock (entries)
     2107                                    $responseFilter = $this->utils_services->doubleFilter($ch, $credentials, 'Sl', 'ref', $response['result'][$i]['ref'], 'entrada', '1'); 
     2108                                                                       
     2109                                    $totalStock = array_reduce(
     2110                                        $responseFilter['result'],
     2111                                        function( $currentTotal, $sl ) {
     2112                                            return $currentTotal += intval($sl["qtt"]);
     2113                                        },
     2114                                        0
     2115                                    );                                                 
     2116                                    //Extract the customer ordrers from total stock             
     2117                                    $arrayRef[$value] = $totalStock - $response['result'][$i]['qttcli'];
     2118
     2119                                } else {
     2120                                    $refArray[$i]['stock'] = $response['result'][$i]['stock'];
     2121                                }                                                                                               
     2122                                $refArray[$i]['sku'] = $response['result'][$i]['ref'];         
    51942123                            }
    51952124                            ++$i;
    5196                         }
    5197            
    5198                         //If exists selected products 
    5199                    
     2125                        }                       
     2126                        //If exists selected products                   
    52002127                            foreach ($refArray as $prod) {           
    52012128                                //Obtain post_id of postmeta table
    52022129                                $productID = wc_get_product_id_by_sku($prod['sku']);
     2130                               
    52032131                                //Obtain products
    5204                                
    52052132                                if(!empty($productID)){
    5206                                         if($settings['backend']['manageStock'] == 'on'){
    5207                                        
    5208                                             update_post_meta($productID,'_stock',$prod['stock']);   
    5209                                  
     2133                                        if($settings['backend']['manageStock'] == 'on'){                                       
     2134                                            update_post_meta($productID,'_stock',$prod['stock']);   
     2135                     
    52102136                                            if($prod['stock'] > 0){
    52112137                                                update_post_meta( $productID, '_stock_status', 'instock');
     2138                                           
    52122139                                            } else {
    52132140                                                //update_post_meta( $productID, '_stock_status', 'outofstock');
     
    52232150                }
    52242151                //Logout
    5225                 $this->paramsLogout();
     2152                $this->auth_services->PHCLogout($ch, $credentials);
    52262153                //session_destroy();
    5227                 curl_setopt($ch, CURLOPT_URL, $this->url);
    5228                 curl_setopt($ch, CURLOPT_POST, false);
    5229                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5230                 $response = curl_exec($ch);
    52312154            } else {
    52322155                echo "empty_refs";
     
    52392162            //If exists selected products 
    52402163            if(is_array($refs)){           
    5241                 //Obtain configuration to make login
    5242                 $this->paramsLogin();
     2164                // get Credentials
     2165                $credentials = $this->syncro_services->fetchCredentials();             
     2166                // Obtain configuration to make login
     2167                $ch = $this->auth_services->PHCLogin($ch, $credentials);
    52432168                //initial request with login data
    5244                 $ch = curl_init();
    5245                 //URL to save cookie "ASP.NET_SessionId"
    5246                 curl_setopt($ch, CURLOPT_URL, $this->url);
    5247                 curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
    5248                 curl_setopt($ch, CURLOPT_POST, true);
    5249                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    5250                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5251                 //Parameters passed to POST
    5252                 curl_setopt($ch, CURLOPT_POSTFIELDS, $this->query);
    5253                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    5254                 curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    5255                 curl_setopt($ch, CURLOPT_COOKIEJAR, '');  //could be empty, but cause problems on some hosts
    5256                 curl_setopt($ch, CURLOPT_COOKIEFILE, '');  //could be empty, but cause problems on some hosts
    5257                 $response = curl_exec($ch);
     2169                $response = curl_exec($ch);     
    52582170                // send response as JSON
    52592171                $response = json_decode($response, true);
    5260 
     2172                // get the temporary token and insert in credentials object
     2173                $credentials->token = $response['result'][0]['token'];
     2174   
     2175                //$this->logs->writeFileLog('Login response:', $response);
     2176   
    52612177                if (curl_error($ch)) {
    5262                     $this->writeFileLog('updateAllFieldsProducts', $ch);
     2178                    $this->logs->writeFileLog('updateAllFieldsProducts', $ch);
    52632179                    unset($_SESSION['username']);
    52642180                } else if(empty($response)){
    5265                     $this->writeFileLog('updateAllFieldsProducts', 'EMPTY RESPONSE');
     2181                    $this->logs->writeFileLog('updateAllFieldsProducts', 'EMPTY RESPONSE');
    52662182                    unset($_SESSION['username']);
    52672183                } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5268                     $this->writeFileLog('updateAllFieldsProducts', $response['messages'][0]['messageCodeLocale']);
     2184                    $this->logs->writeFileLog('updateAllFieldsProducts', $response['messages'][0]['messageCodeLocale']);
    52692185                    unset($_SESSION['username']);
    52702186                } else {
    52712187               
    5272                     //Obtain gama of Drive FX
    5273                     $this->paramsGetBackEndInfo();
    5274 
    5275                     curl_setopt($ch, CURLOPT_URL, $this->url);
    5276                     curl_setopt($ch, CURLOPT_POST, false);
    5277                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    5278                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5279                     $response = curl_exec($ch);
    5280                     // send response as JSON
    5281                     $response = json_decode($response, true);
     2188                     //Obtain gama of PHC
     2189                     $response = $this->utils_services->paramsGetBackEndInfo($ch, $credentials);
     2190
     2191                     //$this->logs->writeFileLog('Get Gama:', $response);
    52822192
    52832193                    if (curl_error($ch)) {
    5284                         $this->writeFileLog('setCommunicationFx2WooCommerce', $ch);
     2194                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $ch);
    52852195                    } else if(empty($response)){
    5286                         $this->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
     2196                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', 'EMPTY RESPONSE');
    52872197                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5288                         $this->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
     2198                        $this->logs->writeFileLog('setCommunicationFx2WooCommerce', $response['messages'][0]['messageCodeLocale']);
    52892199                    } else {
    52902200                        $_SESSION['gamaDRIVEFX'] = $response['result'][0]["gama"];
     
    53092219                        }
    53102220                   
    5311                         $this->paramsQuery3('St',$refArray);
    5312                    
    5313                         curl_setopt($ch, CURLOPT_URL, $this->url);
    5314                         curl_setopt($ch, CURLOPT_POST, false);
    5315                         curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    5316                         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5317                         $response = curl_exec($ch);
    5318                         // send response as JSON
    5319                         $response = json_decode($response, true); 
     2221                        $response = $this->utils_services->paramsQuery3($ch, $credentials, 'St', $refArray);   
    53202222                       
    5321 
     2223                        //$this->logs->writeFileLog('StList response:', $response);
     2224                       
    53222225                        if (curl_error($ch)) {
    5323                             $this->writeFileLog('updateAllFieldsProducts2', $ch);
     2226                            $this->logs->writeFileLog('updateAllFieldsProducts2', $ch);
    53242227                        } else if(empty($response)){
    5325                             $this->writeFileLog('updateAllFieldsProducts2', 'EMPTY RESPONSE');           
     2228                            $this->logs->writeFileLog('updateAllFieldsProducts2', 'EMPTY RESPONSE');           
    53262229                        } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5327                             $this->writeFileLog('updateAllFieldsProducts2', $response['messages'][0]['messageCodeLocale']);           
     2230                            $this->logs->writeFileLog('updateAllFieldsProducts2', $response['messages'][0]['messageCodeLocale']);           
    53282231                        } else {
    53292232                            for($i=0;$i<sizeof($response['result']);$i++){
     
    53712274                               
    53722275                                                         
    5373                                     $this->paramsQuery3('Sa', $refArray);
    5374                                
    5375                                     curl_setopt($ch, CURLOPT_URL, $this->url);
    5376                                     curl_setopt($ch, CURLOPT_POST, false);
    5377                                     curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
    5378                                     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5379                                     $response = curl_exec($ch);
    5380                                     // send response as JSON
    5381                                     $response = json_decode($response, true); 
    5382                            
     2276                                    $response = $this->utils_services->paramsQuery3($ch, $credentials, 'Sa', $refArray);   
     2277           
     2278                                    //$this->logs->writeFileLog('Update All Sa:', $refArray); 
    53832279
    53842280                                    if (curl_error($ch)) {
    5385                                         $this->writeFileLog('updateAllFieldsProducts2', $ch);
     2281                                        $this->logs->writeFileLog('updateAllFieldsProducts2', $ch);
    53862282                                    } else if(empty($response)){
    5387                                         $this->writeFileLog('updateAllFieldsProducts2', 'EMPTY RESPONSE');           
     2283                                        $this->logs->writeFileLog('updateAllFieldsProducts2', 'EMPTY RESPONSE');           
    53882284                                    } else if(isset($response['messages'][0]['messageCodeLocale'])){
    5389                                         $this->writeFileLog('updateAllFieldsProducts2', $response['messages'][0]['messageCodeLocale']);           
     2285                                        $this->logs->writeFileLog('updateAllFieldsProducts2', $response['messages'][0]['messageCodeLocale']);           
    53902286                                    } else {             
    53912287                                            for($i=0;$i<sizeof($response['result']);$i++){
     
    54102306                                                         'post_title'   => $values['design']
    54112307                                                        );
    5412                                     /* 
    5413                                     comentado para as cervejas
    5414                                     $my_post = array('ID'           => $productID,
    5415                                                          'post_title'   => $response['result'][$key]['design'],
    5416                                                          'post_content' => $response['result'][$key]['design'],
    5417                                                          'post_excerpt' => $response['result'][$key]['desctec'],
    5418                                                          'post_name'    => $response['result'][$key]['design'],
    5419                                                         );*/
     2308
    54202309                                        wp_update_post( $my_post );
    54212310                                        update_post_meta( $productID, '_price', $values[$settings['backend']['productPriceColumn']] );
     
    54282317                }
    54292318                //Logout
    5430                 $this->paramsLogout();
    5431                 curl_setopt($ch, CURLOPT_URL, $this->url);
    5432                 curl_setopt($ch, CURLOPT_POST, false);
    5433                 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    5434                 $response = curl_exec($ch);     
     2319                $this->auth_services->PHCLogout($ch, $credentials);
    54352320            } else {
    54362321                echo "empty_refs";
  • drivefx-woocommerce/trunk/drivefx-woocommerce-settings.php

    r1487316 r2456862  
    1313    <div id="descriptionPlugin" style="width: 100%"></div>
    1414   
    15     <a href="https://www.drivefx.net/" target="_blank" title="Drive FX" class="alignleft" style="margin-right: 20px;">
    16       <img src="<?php echo plugins_url('images/logo_drivefx.png', __FILE__) ?>" width="125" height="125">
     15    <a href="https://www.phcgo.net/" target="_blank" title="PHC GO" class="alignleft" style="margin-right: 10px;">
     16      <img src="<?php echo plugins_url('images/logo_phcgo.svg', __FILE__) ?>" width="125" height="125">
    1717    </a>
    1818 
    1919    <h4>Eliminate your repetitive tasks!</h4>
    20     <p class="description"><strong><?php echo PLUGIN_NAME_WOOCOMMERCE ?></strong> is an easy-to-use integration that creates Invoices, Orders, Customers in your Drive FX accounting system.
     20    <p class="description"><strong><?php echo PLUGIN_NAME_WOOCOMMERCE ?></strong> is an easy-to-use integration that creates Invoices, Orders, Customers in your PHC GO accounting system.
    2121    You can also integrate the products and stocks in the WooCommerce solution and automatically send the invoices to your customers by mail.</p>
    2222    <p>Don't forget to <strong>save your settings</strong> when all done!</p>
  • drivefx-woocommerce/trunk/drivefx-woocommerce.php

    r2092492 r2456862  
    11<?php
    22/*
    3  * Plugin Name: Drive FX WooCommerce
    4  * Description: Easy integration between Woocommerce WordPress and your Drive FX installation.
    5  * Version: 4.5.9
     3 * Plugin Name: PHC GO WooCommerce
     4 * Description: Easy integration between Woocommerce WordPress and your PHC GO installation.
     5 * Version: 4.6.0
    66 * Author: PHC Software, S.A.
    7  * Author URI: https://www.drivefx.net/
     7 * Author URI: https://www.phcgo.net/
    88 */
    99 
     
    3030//Check if WooCommerce is active.
    3131if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    32     // start the plugin of Drive FX
     32    // start the plugin of PHC GO
    3333    DriveFxWoocommerce::self();
    3434}
  • drivefx-woocommerce/trunk/index.php

    r1487316 r2456862  
    11<?php
    22# Silence is golden.
     3
  • drivefx-woocommerce/trunk/js/drivefx-woocommerce.js

    r1630365 r2456862  
    1414           
    1515            //Open popup
    16             window.open("https://trial.phcfx.com/OauthCallback/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=Drive FX Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=550,resizable=no,toolbar=no,menubar=no,location=no,status=no");   
    17             //window.open("http://phc201412002/FX/OAuthCallback/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=Drive FX Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=550,resizable=no,toolbar=no,menubar=no,location=no,status=no");   
     16            window.open("https://sis05.drivefx.net/OAuthCallbackPHCGo/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=580,resizable=no,toolbar=no,menubar=no,location=no,status=no");   
     17            //window.open("https://trial.phcfx.com/OauthCallback/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=550,resizable=no,toolbar=no,menubar=no,location=no,status=no");   
     18            //window.open("http://sis.phc.pt/OauthCallback/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=580,resizable=no,toolbar=no,menubar=no,location=no,status=no");     
     19            //window.open("http://phc201412002/FX/OAuthCallback/oauth2callback_phcfx.aspx?backendUrl="+urlBackend+"&appName=PHC GO Woocommerce&redirectUri="+window.location.href, "yyyyy", "width=580,height=550,resizable=no,toolbar=no,menubar=no,location=no,status=no");     
    1820            return false;
    1921        } else {
     
    9294                jQuery('#loader').html('');
    9395            } catch(err) {
    94                 jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in Drive FX".</p></b></div>');
     96                jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in PHC GO".</p></b></div>');
    9597                jQuery('#importToShop').show();
    9698                jQuery('#loader').html('');
     
    164166                    jQuery('#loader').html('');
    165167                } catch(err) {
    166                     jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in Drive FX".</p></b></div>');
     168                    jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in PHC GO".</p></b></div>');
    167169                    jQuery('#importToShop').show();
    168170                    jQuery('#loader').html('');
     
    176178    });
    177179
    178     //Update stocks of products presented in Drive FX
     180    //Update stocks of products presented in PHC GO
    179181    jQuery('#updateStocks').click(function (event) {
    180182        //Update products
     
    233235                    jQuery('#loader').html('');
    234236                } catch(err) {
    235                     jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in Drive FX".</p></b></div>');
     237                    jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in PHC GO".</p></b></div>');
    236238                    jQuery('#importToShop').show();
    237239                    jQuery('#loader').html('');
     
    245247    });
    246248
    247     //Update all fields od products presented in Drive FX
     249    //Update all fields od products presented in PHC GO
    248250    jQuery('#updateAllFields').click(function (event) {
    249251        //Update products
     
    300302                    jQuery('#loader').html('');
    301303                } catch(err) {
    302                     jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in Drive FX".</p></b></div>');
     304                    jQuery('#descriptionPlugin').html('<div class="error" style="width: 96%;"><b><p>Incomplete configurations.<br/>Please verify if you fill "Create Invoice" and "Field to obtain product price in PHC GO".</p></b></div>');
    303305                    jQuery('#importToShop').show();
    304306                    jQuery('#loader').html('');
  • drivefx-woocommerce/trunk/readme.txt

    r2456857 r2456862  
    33Tags: phc software, drivefx, fx, phc go, go, invoices, client, internal document, products, plugin, business
    44Requires at least: 4.5
    5 Tested up to: 4.8
     5Tested up to: 5.6
    66Stable tag: 4.5.8
    77License: GPLv2 or later
  • drivefx-woocommerce/trunk/settings/backend.php

    r1688460 r2456862  
    1010?>
    1111
    12 <h3>Drive FX Backend Configurations</h3>
     12<h3>PHC Backend Configurations</h3>
    1313
    1414<?php
     
    1919    if ($opts['required']) $required[] = "<code>{$opts['label']}</code>";
    2020
    21   ?><p>Provide the info bellow so that the plugin can talk to your Drive FX backend installation.<br>
    22   <?php echo implode(', ', $required) ?> are required to be setup!</p>
    23 
    24   <div id="box">
    25     <div id="cab">
     21    ?><p>Provide the info bellow so that the plugin can talk to your PHC Software backend installation.<br>
     22    <?php echo implode(', ', $required) ?> are required to be setup!</p>
     23   
     24    <div id="box">
     25      <div id="cab">
    2626      Initialize Plugin Settings
    2727    </div>
     
    5454              <?php } ?>
    5555           
    56             <p class="description">The URL of your Drive FX application.<br>Something like, e.g. https://sisXX.drivefx.net/XPTO/</p>
     56            <p class="description">The URL of your PHC application.<br>Something like, e.g. https://sisXX.phcgo.net/XPTO/</p>
    5757          </td>
    5858        </tr>
    5959      </tbody>
    6060    </table>
    61   </div><?php
     61   </div><?php
    6262
    6363  foreach ($this->options['backend'] as $id => $opts):
     64 
    6465    $name  = sprintf(DRIVEFXWOOCOMMERCE_PLUGIN_NAME.'[backend][%s]', $id);
    6566    $value = isset($settings['backend'][$id]) ? $settings['backend'][$id] : null;
     
    114115          </tr>   
    115116          <?php break;
     117
    116118        case 'createInvoice':
    117119          ?></tbody>
     
    119121          </div> <?php
    120122          if($_SESSION['username'] != ''){ ?>
     123           
    121124            <div id="box">
    122125                <div id="cab">
     
    147150        case 'sendInvoice':
    148151          if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     152         
    149153          <tr>
    150154            <th scope="row">
     
    163167          </tr>
    164168          <?php } break;
     169        // Text for email body
     170        case 'emailBody':
     171          if($settings['backend']['createInvoice'] != '' && $settings['backend']['sendInvoice'] != ''){ ?>
     172          <tr>
     173            <th scope="row">
     174              <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     175            </th>
     176            <td>
     177              <textarea class="regular-text" id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>"><?php echo $value ?></textarea>
     178              <p class="description"><?php echo $opts['descr'] ?></p>
     179            </td>
     180          </tr>   
     181          <?php } break;
     182        // Type of Invoice
    165183        case 'typeOfInvoice':
    166184          if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     
    177195            </td>
    178196          </tr>
    179           <?php } break;
    180          
    181         case 'toSignInvoice':
     197          <?php } break;         
     198        case 'toSignInvoice':
     199              if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     200              <tr>
     201                <th scope="row">
     202                  <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     203                </th>
     204                <td>
     205                  <?php if($value == 'on'){
     206                    $checkedBox = 'checked';
     207                  } else {
     208                    $checkbox = '';
     209                  } ?>
     210                  <input style="width: 0;" class="regular-text" <?php echo $checkedBox ?> id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>">
     211                  <span><?php echo $opts['checkboxDescription'] ?></span>
     212                  <p class="description"><?php echo $opts['descr'] ?></p>
     213                </td>
     214              </tr>
     215
     216              <?php } break;
     217
     218        case 'fieldNif':
     219              if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     220              <tr>
     221                <th scope="row">
     222                  <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     223                </th>
     224                <td>
     225            <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     226            <?php echo $_SESSION[$id];?>
     227           
     228                </td>
     229              </tr>
     230              <?php } break;
     231
     232        case 'includeTaxonSendCost':
    182233          if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    183234          <tr>
     
    186237            </th>
    187238            <td>
    188               <?php if($value == 'on'){
    189                 $checkedBox = 'checked';
    190               } else {
    191                 $checkbox = '';
    192               } ?>
    193               <input style="width: 0;" class="regular-text" <?php echo $checkedBox ?> id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>">
    194               <span><?php echo $opts['checkboxDescription'] ?></span>
    195               <p class="description"><?php echo $opts['descr'] ?></p>
     239          <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     240          <?php echo $_SESSION[$id];?>
     241          </select>
    196242            </td>
    197243          </tr>
    198           <?php } break;
    199         case 'includeTaxonSendCost':
    200           if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    201           <tr>
    202             <th scope="row">
    203               <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
    204             </th>
    205             <td>
    206                 <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    207                 <?php echo $_SESSION[$id];?>
    208                 </select>
    209             </td>
    210           </tr>
    211           <?php } break;
    212         case 'fieldNif':
    213           if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    214           <tr>
    215             <th scope="row">
    216               <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
    217             </th>
    218             <td>
    219                 <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    220                 <?php echo $_SESSION[$id];?>
    221                
    222             </td>
    223           </tr>
    224           <?php } break;
    225         case 'warehouseOrder':
    226             // Show gama >= star
    227             if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
    228               </tbody>
    229               </table>
    230               </div>
    231               <div id="box">
    232                   <div id="cab">
    233                     Order Settings
    234                   </div>
    235                   <table class="form-table">
    236                     <tbody>
    237                       <tr>
    238                         <th scope="row">
    239                           <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
    240                         </th>
    241                         <td>
    242                           <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    243                           <?php if(!empty($_SESSION[$id])){ ?>
    244                             <option value="1">Default Warehouse</option>
    245                           <?php }
    246                           echo $_SESSION[$id]; ?>
    247                         </td>
    248                       </tr>
    249                       <?php } break;
    250         case 'typeOfOrder':
    251             if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     244           <?php } break;
     245      //Customer free-tax
     246        case 'createExemptCl':
     247          ?></tbody>
     248          </table>
     249          </div><?php
     250          if($_SESSION['username'] != ''){ ?>
     251            <div id="box">
     252                <div id="cab">
     253                Tax-exempt customers Settings
     254                </div>
     255                <table class="form-table">
     256                  <tbody>
     257                  <tr>
     258                      <th scope="row">
     259                        <?php if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '') { ?>
     260                            <label for="<?php echo $id ?>">Create tax-exempt customers?</label>
     261                        <?php } ?>
     262                      </th>
     263                      <td>
     264                        <?php if($value == 'on'){
     265                          $checkedBox = 'checked';
     266                        } else {
     267                          $checkbox = '';
     268                        } ?>
     269                        <input style="width: 0;" class="regular-text" <?php echo $checkedBox ?> id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>">
     270                        <span><?php echo $opts['checkboxDescription'] ?></span>
     271                        <p class="description"><?php echo $opts['descr'] ?></p>
     272                      </td>
     273                    </tr>
     274              <?php } break;
     275              //The reason for the tax exemption.
     276               case 'typeOfReason':
     277                if($_SESSION['username'] != ''  && $settings['backend']['createInvoice'] != '' && $settings['backend']['createExemptCl'] != ''){ ?>
     278                    <tr>
     279                    <th scope="row">
     280                      <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     281                    </th>
     282                    <td>
     283                      <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     284                      <?php if(!empty($_SESSION[$id])){ ?>
     285                        <option value="0">Select one...</option>
     286                      <?php }
     287                      echo $_SESSION[$id]; ?>
     288                    </td>
     289                  </tr>
     290                  <?php } break;
     291
     292          case 'warehouseOrder':       
     293          // Show gama >= star
     294          if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
     295                </tbody>
     296                </table>
     297                </div>
     298                <div id="box">
     299                    <div id="cab">
     300                      Order Settings
     301                    </div>
     302                    <table class="form-table">
     303                      <tbody>
     304                        <tr>
     305                          <th scope="row">
     306                            <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     307                          </th>
     308                          <td>
     309                            <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     310                            <?php if(!empty($_SESSION[$id])){ ?>
     311                              <option value="1">Default Warehouse</option>
     312                            <?php }
     313                            echo $_SESSION[$id]; ?>
     314                          </td>
     315                        </tr>
     316                        <?php } break;
     317          case 'typeOfOrder':
     318          if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     319              <tr>
     320                <th scope="row">
     321                  <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     322                </th>
     323                <td>
     324                  <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     325                  <?php if(!empty($_SESSION[$id])){ ?>
     326                    <option value="0">Select one...</option>
     327                  <?php }
     328                  echo $_SESSION[$id]; ?>
     329                </td>
     330              </tr>
     331           
     332              <?php } break;         
     333        case 'toSignOrder':
     334              if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     335              <tr>
     336                <th scope="row">
     337                  <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     338                </th>
     339                <td>
     340                  <?php if($value == 'on'){
     341                    $checkedBox = 'checked';
     342                  } else {
     343                    $checkbox = '';
     344                  } ?>
     345                  <input style="width: 0;" class="regular-text" <?php echo $checkedBox ?> id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>">
     346                  <span><?php echo $opts['checkboxDescription'] ?></span>
     347                  <p class="description"><?php echo $opts['descr'] ?></p>
     348                </td>
     349              </tr>
     350
     351              <?php } break;
     352          case 'numberOfOrder':
     353            if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['toSignOrder'] != ''){ ?>
    252354            <tr>
    253355              <th scope="row">
     
    256358              <td>
    257359                <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    258                 <?php if(!empty($_SESSION[$id])){ ?>
    259                   <option value="0">Select one...</option>
    260                 <?php }
    261                 echo $_SESSION[$id]; ?>
     360                <?php $fieldsStatus = array('notSelected' => 'Select one...',
     361                                            'nmdesc' => 'Main Description',
     362                                            'texto1' => 'Name of Final Text',
     363                                            'texto2' => 'Name of Final Text 2',
     364                                            'texto3' => 'Name of Final Text 3',
     365                                            'tmodelo' => 'Alphanumeric Field 1',
     366                                            'tmarca' => 'Alphanumeric Field 2',
     367                                            'tserie' => 'Alphanumeric Field 3'
     368                                            );
     369                      foreach ($fieldsStatus as $key => $value){
     370                        $selected_dropdown = '';
     371                        if($settings['backend']['numberOfOrder'] == $key){
     372                          $selected_dropdown = 'selected';
     373                        } ?>
     374                          <option id="<?php echo $key ?>" <?php echo $selected_dropdown ?> value="<?php echo $key ?>"><?php echo $value ?></option>
     375                        <?php                     
     376                      } ?>
     377              </td>
     378            </tr>
     379
     380              <?php } break;
     381          case 'statusOfOrder':
     382            if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     383            <tr>
     384              <th scope="row">
     385                <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     386              </th>
     387              <td>
     388                <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     389                <?php $fieldsStatus = array('notSelected' => 'Select one...',
     390                                            'nmdesc' => 'Main Description',
     391                                            'texto1' => 'Name of Final Text',
     392                                            'texto2' => 'Name of Final Text 2',
     393                                            'texto3' => 'Name of Final Text 3',
     394                                            'tmodelo' => 'Alphanumeric Field 1',
     395                                            'tmarca' => 'Alphanumeric Field 2',
     396                                            'tserie' => 'Alphanumeric Field 3'
     397                                            );
     398                      foreach ($fieldsStatus as $key => $value){
     399                        $selected_dropdown = '';
     400                        if($settings['backend']['statusOfOrder'] == $key){
     401                          $selected_dropdown = 'selected';
     402                        } ?>
     403                          <option id="<?php echo $key ?>" <?php echo $selected_dropdown ?> value="<?php echo $key ?>"><?php echo $value ?></option>
     404                        <?php                     
     405                      } ?>
    262406              </td>
    263407            </tr>
    264408            <?php } break;
    265         case 'statusOfOrder':
    266           if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
    267           <tr>
    268             <th scope="row">
    269               <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
    270             </th>
    271             <td>
    272               <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    273               <?php $fieldsStatus = array('notSelected' => 'Select one...',
    274                                           'nmdesc' => 'Main Description',
    275                                           'texto1' => 'Name of Final Text',
    276                                           'texto2' => 'Name of Final Text 2',
    277                                           'texto3' => 'Name of Final Text 3',
    278                                           'tmodelo' => 'Alphanumeric Field 1',
    279                                           'tmarca' => 'Alphanumeric Field 2',
    280                                           'tserie' => 'Alphanumeric Field 3'
    281                                           );
    282                     foreach ($fieldsStatus as $key => $value){
    283                       $selected_dropdown = '';
    284                       if($settings['backend']['statusOfOrder'] == $key){
    285                         $selected_dropdown = 'selected';
    286                       } ?>
    287                         <option id="<?php echo $key ?>" <?php echo $selected_dropdown ?> value="<?php echo $key ?>"><?php echo $value ?></option>
    288                       <?php                     
    289                     } ?>
    290             </td>
    291           </tr>
    292           <?php } break;
    293         case 'manageStock':
    294           if($_SESSION['username'] != ''){ ?>
    295             </tbody>
    296             </table>
    297             </div>
    298             <div id="box">
    299               <div id="cab">
    300                 Product Settings
     409            // Select reference for shipping
     410            case 'shippingName':
     411              if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
     412                    <tr>
     413                      <th scope="row">
     414                        <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     415                      </th>
     416                      <td>
     417                        <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     418                        <?php if(!empty($_SESSION[$id])){ ?>
     419                          <option value="0">Select one...</option>
     420                        <?php }
     421                        echo $_SESSION[$id]; ?>
     422                      </td>
     423                    </tr>
     424                    <?php } break;
     425             // Select reference for fees
     426             case 'feesName':
     427              if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
     428                    <tr>
     429                      <th scope="row">
     430                        <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     431                      </th>
     432                      <td>
     433                        <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     434                        <?php if(!empty($_SESSION[$id])){ ?>
     435                          <option value="0">Select one...</option>
     436                        <?php }
     437                        echo $_SESSION[$id]; ?>
     438                      </td>
     439                    </tr>
     440                    <?php } break;
     441            //Manage stock
     442          case 'manageStock':
     443            if($_SESSION['username'] != ''){ ?>
     444              </tbody>
     445              </table>
    301446              </div>
    302               <table class="form-table">
    303                 <tbody>
    304                 <?php if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){ ?>
     447              <div id="box">
     448                <div id="cab">
     449                  Product Settings
     450                </div>
     451                <table class="form-table">
     452                  <tbody>
     453                 <?php if($_SESSION['manageStockParameter'] === 'S' && $_SESSION['gamaDRIVEFX'] >= 9){ ?>
     454                    <tr>
     455                      <th scope="row">
     456                        <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     457                      </th>
     458                      <td>
     459                        <?php if($value == 'on'){
     460                          $checkedBox = 'checked';
     461                        } else {
     462                          $checkbox = '';
     463                        } ?>
     464                        <input style="width: 0;" class="regular-text" <?php echo $checkedBox ?> id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>">
     465                        <span><?php echo $opts['checkboxDescription'] ?></span>
     466                        <p class="description"><?php echo $opts['descr'] ?></p>
     467                      </td>
     468                    </tr>
     469                    <?php } } break;
     470                    // Select produtcs that have a positive stock
     471                    case 'positiveStock':
     472                      if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != ''){ ?>
     473                     
     474                      <tr>
     475                        <th scope="row">
     476                          <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     477                        </th>
     478                        <td>
     479                          <?php if($value == 'on'){
     480                            $checkedBox = 'checked';
     481                          } else {
     482                            $checkbox = '';
     483                          } ?>
     484                          <input style="width: 0;" class="regular-text" <?php echo $checkedBox ?> id="<?php echo $id ?>" type="<?php echo $opts['type'] ?>" name="<?php echo $name ?>">
     485                          <span><?php echo $opts['checkboxDescription'] ?></span>
     486                          <p class="description"><?php echo $opts['descr'] ?></p>
     487                        </td>
     488                      </tr>
     489                      <?php } break;
     490                 // Filter stock (stock - orders)   
     491                 case 'filterStock':
     492                  if($_SESSION['username'] != '' && $settings['backend']['createInvoice'] != '' && $settings['backend']['warehouse'] == "-1"){ ?>
     493                 
    305494                  <tr>
    306495                    <th scope="row">
     
    318507                    </td>
    319508                  </tr>
    320                   <?php } } break;
    321         case 'productPriceColumn':
    322           if($_SESSION['username'] != ''){ ?>
     509                  <?php } break;
     510          // Product price column
     511          case 'productPriceColumn':
     512            if($_SESSION['username'] != ''){ ?>
     513              <tr>
     514                <th scope="row">
     515                  <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
     516                </th>
     517                <td>
     518                  <select id="<?php echo $id ?>" name="<?php echo $name ?>">
     519                  <?php $fieldsStatus = array('epv0' => 'Select one...',
     520                                              'epv1' => 'Retail price 1 (epv1)',
     521                                              'epv2' => 'Retail price 2 (epv2)',
     522                                              'epv3' => 'Retail price 3 (epv3)',
     523                                              'epv4' => 'Retail price 4 (epv4)'
     524                                              );
     525                        foreach ($fieldsStatus as $key => $value){
     526                          $selected_dropdown = '';
     527                          if($settings['backend']['productPriceColumn'] == $key){
     528                            $selected_dropdown = 'selected';
     529                          } ?>
     530                            <option id="<?php echo $key ?>" <?php echo $selected_dropdown ?> value="<?php echo $key ?>"><?php echo $value ?></option>
     531                          <?php                     
     532                        } ?>
     533                </td>
     534              </tr>
     535              <?php } break;
     536          case 'warehouse':
     537            if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
    323538            <tr>
    324539              <th scope="row">
     
    327542              <td>
    328543                <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    329                 <?php $fieldsStatus = array('epv0' => 'Select one...',
    330                                              'epv1' => 'Retail price 1 (epv1)',
    331                                              'epv2' => 'Retail price 2 (epv2)',
    332                                              'epv3' => 'Retail price 3 (epv3)',
    333                                              'epv4' => 'Retail price 4 (epv4)'
    334                                             );
    335                       foreach ($fieldsStatus as $key => $value){
    336                         $selected_dropdown = '';
    337                         if($settings['backend']['productPriceColumn'] == $key){
    338                           $selected_dropdown = 'selected';
    339                         } ?>
    340                           <option id="<?php echo $key ?>" <?php echo $selected_dropdown ?> value="<?php echo $key ?>"><?php echo $value ?></option>
    341                         <?php                     
    342                       } ?>
     544                <?php if(!empty($_SESSION[$id])){ ?>
     545                  <option value="-1">All Warehouses</option>
     546                <?php }
     547                echo $_SESSION[$id]; ?>
    343548              </td>
    344549            </tr>
    345             <?php } break;
    346         case 'warehouse':
    347           if($_SESSION['gamaDRIVEFX'] >= 9 && $_SESSION['username'] != ''){ ?>
    348           <tr>
    349             <th scope="row">
    350               <label for="<?php echo $id ?>"><?php echo $opts['label'] ?></label>
    351             </th>
    352             <td>
    353               <select id="<?php echo $id ?>" name="<?php echo $name ?>">
    354               <?php if(!empty($_SESSION[$id])){ ?>
    355                 <option value="-1">All Warehouses</option>
    356               <?php }
    357               echo $_SESSION[$id]; ?>
    358             </td>
    359           </tr>
    360           </tbody>
    361           </table>
    362           </div>
    363           <?php } else {
    364             ?> </tbody>
    365           </table>
    366           </div>
    367           <?php } break;   
    368         default:
    369           break;
     550           </tbody>
     551            </table>
     552            </div>
     553            <?php }
     554            else {
     555              ?> </tbody>
     556            </table>
     557            </div>
     558            <?php } break; 
     559           default:
     560            break;
    370561      }
    371562    }
     563   
    372564       
    373565  endforeach;
  • drivefx-woocommerce/trunk/settings/import-products.php

    r1487316 r2456862  
    44?>
    55
    6 <h3>Drive FX Import Products</h3>
     6<h3>PHC Import Products</h3>
    77
    88<h4><em>Online Shop</em></h4>
    9 <p>Check to new insert products presented in your Drive FX on your Online Shop.</p>
     9<p>Check to new insert products presented in your Phc Software on your Online Shop.</p>
    1010
    1111<div id="loader"></div>
    12 <div id="importToShop" class="button button-primary" title="List all products from Drive FX">
    13     <img id="list" src="<?php echo plugins_url('/../images/list.png', __FILE__) ?>" title="List all products from Drive FX"> List Products
     12<div id="importToShop" class="button button-primary" title="List all products from PHC">
     13    <img id="list" src="<?php echo plugins_url('/../images/list.png', __FILE__) ?>" title="List all products from PHC"> List Products
    1414</div>
    1515
     
    1919<!-- Buttons to "show list, save products, update stocks and update all fields" -->
    2020<div id="loader2"></div>
    21 <div id="saveProductInShop" class="button button-primary" title="Import new products from Drive FX">
     21<div id="saveProductInShop" class="button button-primary" title="Import new products from PHC">
    2222    <img id="plus" src="<?php echo plugins_url('/../images/plus.png', __FILE__) ?>" title="Save selected product in yout online store"> Import New Products
    2323</div>
     
    2828    </div>
    2929<?php } ?>
    30 <div id="updateAllFields" class="button button-primary" title="Update all fields of products from Drive FX">
     30<div id="updateAllFields" class="button button-primary" title="Update all fields of products from PHC">
    3131    <img id="plus" src="<?php echo plugins_url('/../images/update.png', __FILE__) ?>" title="Update all fields of products in your online store"> Update all fields
    3232</div>
Note: See TracChangeset for help on using the changeset viewer.