<?php

class ControllerEntegrasyonUpdate extends Controller
{

    private $reg = '';

    private $barcodes = array();

    private $user_info = null;

    public function __construct($registry)
    {

        parent::__construct($registry);

        $this->reg = $registry;
    }

    public function match_product()
    {

        $active_market='hb';
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);


        if (isset($_REQUEST['mode'])) {
            $mode = true;
        } else {
            $mode = false;
        }

        $debug = false;
        if (isset($this->request->get['debug'])) {

            $debug = true;
        }

        if (isset($_REQUEST['username'])) {
            $username = $_REQUEST['username'];
        } else {

            echo 'kullanıcı bulunamadı';
            return;
        }

        $this->reg->set('udb', new DB\Userdb(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, $username));


        $this->loadConfig();

        $user_info_query = $this->db->query("SELECT * FROM `oc_user_database` ud left join oc_user u on(ud.database_id=u.user_database_id) where ud.name='" . $username . "'");


        $user_info = $user_info_query->row;

        $this->user_info = $user_info;

        $this->load->model("tool/entegrasyon_api");



        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($active_market, $user_info['database_id']);

        print_r($api_info);

        $products = $this->hb->getProductsByStatus( $api_info);


        $matched_products=array();

        foreach ($products['result']['data'] as $item) {

            $matched_products[]=$item['merchantSku'];

        }

      //  print_r($matched_products);

        $this->hb->rejectMatchProduct($api_info,$matched_products);


    }
    public function test_order()
    {

        $active_market='pz';
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);


        if (isset($_REQUEST['mode'])) {
            $mode = true;
        } else {
            $mode = false;
        }

        $debug = false;
        if (isset($this->request->get['debug'])) {

            $debug = true;
        }

        if (isset($_REQUEST['username'])) {
            $username = $_REQUEST['username'];
        } else {

            echo 'kullanıcı bulunamadı';
            return;
        }

        $this->reg->set('udb', new DB\Userdb(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, $username));


        $this->loadConfig();

        $user_info_query = $this->db->query("SELECT * FROM `oc_user_database` ud left join oc_user u on(ud.database_id=u.user_database_id) where ud.name='" . $username . "'");


        $user_info = $user_info_query->row;

        $this->user_info = $user_info;

        $this->load->model("tool/entegrasyon_api");

        $this->load->model('entegrasyon/general');
        $this->load->model('entegrasyon/order');

        $this->load->model('entegrasyon/order/'.$active_market);


        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($active_market, $user_info['database_id']);

        $orders = $this->{'model_entegrasyon_order_' . $active_market}->getOrders($debug, 'add', $api_info);




    }

    public function update_orders($code, $api_info)
    {

        $query = $this->db->query("SELECT code,order_id, market_order_id,email FROM `order` where order_status not in (4,5,6) and user_id='" . $this->user_info['user_id'] . "' and code='" . $code . "' and DATE(date_added) >= DATE_SUB(CURDATE(), INTERVAL 20 DAY)  order by order_id DESC ");
        //$query = $this->db->query("SELECT code,order_id, market_order_id,email FROM `" . DB_PREFIX . "es_order` where   code='" . $code . "' order by order_id  DESC limit $start,$limit");


        // print_r($query->rows);


        $order_list = array();


        if ($code == 'cs') {
           // $this->load->model('entegrasyon/order/' . $code);

           // $order_list = $this->{'model_entegrasyon_order_' . $code}->check_order_status($query->rows, $api_info);



        } else {

            foreach ($query->rows as $order) {
                $this->load->model('entegrasyon/order/' . $order['code']);

                // $this->{'model_entegrasyon_order_' . $order['code']}->check_order_status($order,$api_info);
                $order_list[$order['code']][$order['order_id']] = $this->{'model_entegrasyon_order_' . $order['code']}->check_order_status($order, $api_info);
                // print_r($order_list);return;
            }


        }


        // print_r($order_list);return;


        if ($order_list[$code]) {

            foreach ($order_list[$code] as $order_id => $order) {

                $order_status = $this->model_entegrasyon_order->getOrderStatus($order['status'], $code);


                if ($order_status == 4) {

                    $query = $this->db->query("select * from `order` where order_id='" . $order_id . "'  ");
                    $order_info = $query->row;

                    if($order_info['buy']){
                        
                        $message = $this->user_info['username'] . ' e ait ' . $order_info['market_order_id'] . " numarali " . $order_info['code'] . " siparişiniz iptal edilmiştir. " . rand(0000, 9999);
                        $results = $this->sendsms($message, $this->user_info['phone'], "iptal");

                    }



                }
                $sql = "update `order` SET order_status = '" . $order_status . "', id='" . $order['shipment_package_id'] . "', invoice_link='" . $order['invoice_link'] . "', cargo_name='" . $order['cargo_name'] . "', tracking_url='" . $order['tracking_url'] . "', cargo_number='" . $this->db->escape($order['cargo_number']) . "', date_modified=NOW() where order_id='" . $order_id . "'";

                // echo  $order_id .':'.$sql.'<br>';

                $this->db->query($sql);
                // $this->udb->query($sql);


            }


        }

        if ($code == 'ty' & $code == 'hb') {
            $this->load->model('entegrasyon/order/' . $code);

            $claim_list = $this->{'model_entegrasyon_order_' . $code}->getClaims($api_info);


        }

        // $this->model_entegrasyon_general->session_set($order_list, $filename);


    }


    public function sendsms($mesaj, $telno, $type = "siparis")
    {
        $username = "5412616688";


        $pass = "C28$236";

        if ($type == "siparis") {
            $header = '8503023649';
        } else if ($type == "iptal") {
            $header = 'MIREGITIM';
        }

        $header = html_entity_decode($header, ENT_COMPAT, "UTF-8");
        $header = rawurlencode($header);


        $startdate = date('d.m.Y H:i');
        $startdate = str_replace('.', '', $startdate);
        $startdate = str_replace(':', '', $startdate);
        $startdate = str_replace(' ', '', $startdate);

        $stopdate = date('d.m.Y H:i', strtotime('+1 day'));
        $stopdate = str_replace('.', '', $stopdate);
        $stopdate = str_replace(':', '', $stopdate);
        $stopdate = str_replace(' ', '', $stopdate);
        $mesaj = str_replace(" ", "%20", $mesaj);

        $url = "https://api.netgsm.com.tr/bulkhttppost.asp?usercode=$username&password=$pass&gsmno=$telno&message=" . $this->db->escape($mesaj) . "&msgheader=$header&startdate=$startdate&stopdate=$stopdate";


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $output = curl_exec($ch);
        curl_close($ch);


        return $output;

    }


    public function update_after_xml()
    {

        //$this->entegrasyon->deleteSetting('easyxml');
        $products = $this->config->get('easyxml_updated_products');


        print_r($products);
        return;


        $pre_pro = array();

        $limit = 0;
        foreach ($products as $product) {


        }

        if ($pre_pro) {

            $update_results = $this->entegrasyon->updateMarketplaceProdutcsAfterOrder($pre_pro, HTTPS_SERVER, false, ' after xml update');

            //$update_results=array(2329=>array(),2333=>array());

            foreach ($update_results as $key => $item) {


                $index = array_search($key, $products);


                if ($index !== false) {

                    unset($products[$index]);

                    // print_r($products);
                }

                try {

                    $sql = "update " . DB_PREFIX . "product SET date_modified='2018-04-17 10:00:00' where product_id='" . $key . "'";

                    $this->db->query($sql);


                } catch (Exception $exception) {
                    echo $exception->getMessage();

                }

            }


            $this->entegrasyon->editSetting('easyxml', array('easyxml_updated_products' => array_values($products)));
        }


        echo '=== After update ===<br>';
        //print_r($products);

    }


    public function test()
    {

        $this->sendsms("dfsgsdgsdfgfdsg", "5412616688");

    }

    public function updatedb()
    {

        $update_sql = array();
        $update_sql[] = "TRUNCATE TABLE `" . DB_PREFIX . "es_order_status`";


        $update_sql[] = "INSERT INTO `" . DB_PREFIX . "es_order_status` (`order_status_id`, `name`, `oc`, `n11`, `gg`, `ty`, `eptt`, `hb`, `cs`, `amz`) VALUES
(1, 'Onay Bekliyor', '1', '1', '0', '0', '0', 'Open', 'Yeni Sipariş', ''),
(2, 'Kargolanma Aşamasında', '2', '5', 'STATUS_WAITING_CARGO_INFO', 'ReadyToShip, Picking, Invoiced', 'kargo_yapilmasi_bekleniyor', 'Packaged', 'Kargoya Verilecek, Hazırlanıyor', ''),
(3, 'Kargolandı', '3', '6', 'STATUS_WAITING_APPROVAL', 'Shipped', 'gonderilmis', 'InTransit', 'Kargoya Verildi', ''),
(4, 'İptal Edildi', '4', '4', '', 'Cancelled,UnSupplied', '', 'CancelledByCustomer, CancalledByMerchant,CancalledBySap', 'İptal Edildi', ''),
(5, 'Teslim Edildi', '5', '10', '', 'Delivered', '', 'Delivered', 'Teslim Edildi', ''),
(6, 'Teslim Edilemedi', '6', '', '', 'UnDelivered, Returned', '', '', '', '');";

        $update_sql[] = "ALTER TABLE `" . DB_PREFIX . "es_order` ADD `cargo_name` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL AFTER `payment_info`, ADD `tracking_url` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL AFTER `cargo_name`, ADD `cargo_number` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL AFTER `tracking_url`;";
        $update_sql[] = "ALTER TABLE `" . DB_PREFIX . "es_ordered_product` ADD `list_price` FLOAT(10,2) NOT NULL AFTER `price`;";
        $update_sql[] = "ALTER TABLE `" . DB_PREFIX . "es_order` CHANGE `id` `id` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
        $update_sql[] = "ALTER TABLE " . DB_PREFIX . "order ADD `payment_tax_id` INT(1) NOT NULL AFTER `payment_address_2`;";
        $update_sql[] = "ALTER TABLE " . DB_PREFIX . "es_order ADD `invoice_link` VARCHAR(64) CHARACTER SET utf8 COLLATE utf8_general_ci  NOT NULL AFTER `tracking_url`;";
        $update_sql[] = "ALTER TABLE `" . DB_PREFIX . "es_order` CHANGE `email` `email` VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
        $update_sql[] = "ALTER TABLE `" . DB_PREFIX . "es_ordered_product`  ADD `kdv` INT NOT NULL";
        $update_sql[] = "ALTER TABLE `" . DB_PREFIX . "es_ordered_product`  ADD `discount` INT NOT NULL";

        $update_sql[] = "CREATE TABLE `" . DB_PREFIX . "es_invoice` (
  `invoice_id` int(11) NOT NULL,
  `document_id` varchar(64) NOT NULL,
  `uuid` varchar(128) NOT NULL,
  `is_signed` int(1) DEFAULT '0',
  `email_send` int(11) NOT NULL DEFAULT '0',
  `pdf_path` text NOT NULL,
  `invoice_data` mediumtext CHARACTER SET utf8 NOT NULL,
  `date_added` datetime NOT NULL,
  `order_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;";

        $update_sql[] = "ALTER TABLE `" . DB_PREFIX . "es_invoice`
  ADD PRIMARY KEY (`invoice_id`),
  ADD KEY `order_id` (`order_id`),
  ADD KEY `document_id` (`document_id`);";

        $update_sql[] = "ALTER TABLE `" . DB_PREFIX . "es_invoice` MODIFY `invoice_id` int(11) NOT NULL AUTO_INCREMENT;";

        foreach ($update_sql as $sql) {
            $this->runExecute($sql);
        }

    }


    public function update_competition_price()
    {

        $code = $this->request->post['code'];
        $price = $this->request->post['price'];
        $product_id = $this->request->post['product_id'];;

        $this->load->model('entegrasyon/general');

        // print_r($this->request->post);
        //return;

        $this->model_entegrasyon_general->update_product_price($code, $price, $product_id);

        $debug = false;
        $product_info = $this->entegrasyon->getProduct($product_id);
        $product_info = $this->entegrasyon->getProductForUpdate($code, $product_info, 0, true, HTTPS_SERVER);
        $post_data['request_data'] = $product_info;
        $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace($code);

        $result = $this->entegrasyon->clientConnect($post_data, 'update_basic', $code, $debug, false);

        echo json_encode($result);


    }


    protected function loadConfig()
    {
        $this->registry->set('uconfig', new Uconfig());
        $query = $this->udb->query("SELECT * FROM setting");
        foreach ($query->rows as $setting) {
            if (!$setting['serialized']) {
                $this->uconfig->set($setting['key'], $setting['value']);
            } else {
                $this->uconfig->set($setting['key'], json_decode($setting['value'], true));
            }
        }

    }

    public function orders()
    {


        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);


        if (isset($_REQUEST['mode'])) {
            $mode = true;
        } else {
            $mode = false;
        }

        $debug = false;
        if (isset($this->request->get['debug'])) {

            $debug = true;
        }

        if (isset($_REQUEST['username'])) {
            $username = $_REQUEST['username'];
        } else {

            echo 'kullanıcı bulunamadı';
            return;
        }

        $this->reg->set('udb', new DB\Userdb(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, $username));


        $this->loadConfig();

        $user_info_query = $this->db->query("SELECT * FROM `oc_user_database` ud left join oc_user u on(ud.database_id=u.user_database_id) where ud.name='" . $username . "'");


        $user_info = $user_info_query->row;

        $this->user_info = $user_info;


    


        $stokUpdateData = array();
        $total_new = 0;

        $order_temp = 0;
        $ordered_product_temp = 0;
        $defined_ordered_product_temp = 0;
        $this->load->model('entegrasyon/order');


        $marketplaces = $this->db->query("select * from entegrasyon where entegrasyon_group_id=1 and status = 1 ")->rows;
        $active_markets = array();

        foreach ($marketplaces as $marketplace) {
            $user_marketplace_info = $this->db->query("select count(*) as total from database_entegrasyon where database_id='" . $user_info['user_database_id'] . "' and entegrasyon_id='" . $marketplace['entegrasyon_id'] . "'  ");
            $data[$marketplace['code']] = $user_marketplace_info->row['total'];
            if ($user_marketplace_info->row['total']) {
                $active_markets[] = $marketplace['code'];
            }


        }


        $orders = array();
        //print_r($marketplaces);

        /* foreach ($marketplaces as $key => $marketplace) {
                if ($marketplace['status'] && $key!=3) {
                    $this->load->model('entegrasyon/order/' . $marketplace['code']);
                    $orders[$marketplace['code']] = $this->{'model_entegrasyon_order_' . $marketplace['code']}->getOrders($debug);
                }

            }*/

        $this->load->model("tool/entegrasyon_api");
        $this->load->model("entegrasyon/order");

        foreach ($active_markets as $active_market) {
            if ($active_market == 'ty'  || $active_market == 'hb' || $active_market == 'cs'  ) {
           // if ($active_market == 'pz' ) {


                  $this->load->model('entegrasyon/order/' . $active_market);

                  $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($active_market, $user_info['database_id']);

                  $orders[$active_market] = $this->{'model_entegrasyon_order_' . $active_market}->getOrders($debug, 'add', $api_info);

                if ($active_market != 'pz'){
                    $result = $this->update_orders($active_market, $api_info);

                }


             }

                //print_r($result);

                //print_r($result);


          //  }
        }


     



        $total_order_count = array();


        $updated_products = array();


        //print_r($orders);return;

        foreach ($orders as $code => $orderpatch) {


            $order_count = 0;
            foreach ($orderpatch as $order) {


                $getOrder = $this->model_entegrasyon_order->getOrder($order['order_id']);
                $order_temp++;
                if ($code == "hb" && $getOrder) {
                    $getOrder = $this->model_entegrasyon_order->getOrder($order['order_id'], $order['email'], $order['id']);

                }

                if (!$getOrder) {
                    //Siparişleri Veritabanına Yazdırıyoruz
                    $barcodes = $this->model_entegrasyon_order->addOrder($order, $code, $user_info);


                    foreach ($barcodes as $barcode) {

                        $this->barcodes[] = $barcode;
                    }

                    // die;
                    $order_count++;
                    $total_new++;

                }


            }



            $total_order_count[$code] = $order_count;


        }

        //print_r($this->barcodes);

        $this->question($user_info);





        //print_r($updated_products);
        echo json_encode(array('total' => $total_new, 'markets' => $total_order_count));

    }




    public function question2()
    {



        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);


        if (isset($_REQUEST['mode'])) {
            $mode = true;
        } else {
            $mode = false;
        }

        $debug = false;
        if (isset($this->request->get['debug'])) {

            $debug = true;
        }

        if (isset($_REQUEST['username'])) {
            $username = $_REQUEST['username'];
        } else {

            echo 'kullanıcı bulunamadı';
            return;
        }

        $this->reg->set('udb', new DB\Userdb(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, $username));


        $this->loadConfig();

        $user_info_query = $this->db->query("SELECT * FROM `oc_user_database` ud left join oc_user u on(ud.database_id=u.user_database_id) where ud.name='" . $username . "'");


        $user_info = $user_info_query->row;



        $this->user_info = $user_info;

        $this->load->model("tool/entegrasyon_api");
        $this->load->model("entegrasyon/general");


        $marketplaces = $this->db->query("select * from entegrasyon where entegrasyon_group_id=1 and status = 1 ")->rows;
        $active_markets = array();

        foreach ($marketplaces as $marketplace) {
            $user_marketplace_info = $this->db->query("select count(*) as total from database_entegrasyon where database_id='" . $user_info['user_database_id'] . "' and entegrasyon_id='" . $marketplace['entegrasyon_id'] . "'  ");
            $data[$marketplace['code']] = $user_marketplace_info->row['total'];
            if ($user_marketplace_info->row['total']) {
                $active_markets[] = $marketplace['code'];
            }


        }



        foreach ($active_markets as $active_market) {
            if ($active_market == 'ty' || $active_market == 'hb') {
                // $this->load->model('entegrasyon/order/' . $active_market);

                $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($active_market, $user_info['database_id']);

                $question_list[$active_market] = $this->{$active_market}->get_questions($api_info);

                //print_r($result);


            }
        }








        foreach ($question_list as $code => $items) {

            foreach ($items as $item) {

                $answer = $this->model_entegrasyon_general->get_answer($item['text']);

                $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($code, $user_info['database_id']);


                //$post_data['code']=$code;
                $post_data['text'] = $answer['keyword']['message'];
                $post_data['question_id'] = $item['id'];

               if($answer['keyword']['message']){
                   $result = $this->{$code}->reply_question($post_data, $api_info);

               }

                if($answer['action']){

                    $update_list=array();

                   $product_info = $this->getMarketProduct($item['url']);
                   if($product_info){

                       $update_list[] = array(
                           "barcode" => $product_info['barcode'],
                           "stockCode" => $product_info['stock_code'],
                           "shipping_time" => 2,
                           "marketplace_product_id" => $product_info['marketplace_product_id'],
                           "salePrice" => 0,
                           "listPrice" => 0,
                           "quantity" => 0,

                       );

                       $result = $this->{$code}->update_fast($update_list, $api_info);
                       $this->udb->query("delete from market_product where market_product_id='".$product_info['market_product_id']."' ");

                   }

                 //print_r($product_info);
                }

            }

        }

        return;

        // print_r($question_list);


    }
    public function question($user_info)
    {


        $this->load->model("tool/entegrasyon_api");
        $this->load->model("entegrasyon/general");


        $marketplaces = $this->db->query("select * from entegrasyon where entegrasyon_group_id=1 and status = 1 ")->rows;
        $active_markets = array();

        foreach ($marketplaces as $marketplace) {
            $user_marketplace_info = $this->db->query("select count(*) as total from database_entegrasyon where database_id='" . $user_info['user_database_id'] . "' and entegrasyon_id='" . $marketplace['entegrasyon_id'] . "'  ");
            $data[$marketplace['code']] = $user_marketplace_info->row['total'];
            if ($user_marketplace_info->row['total']) {
                $active_markets[] = $marketplace['code'];
            }


        }



        foreach ($active_markets as $active_market) {
            if ($active_market == 'ty' || $active_market == 'hb' || $active_market == 'cs') {
                // $this->load->model('entegrasyon/order/' . $active_market);

                $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($active_market, $user_info['database_id']);

                $question_list[$active_market] = $this->{$active_market}->get_questions($api_info);

                //print_r($result);


            }
        }







        foreach ($question_list as $code => $items) {

            foreach ($items as $item) {


                $answer = $this->model_entegrasyon_general->get_answer($item['text']);



                $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($code, $user_info['database_id']);


                //$post_data['code']=$code;

                if(isset($answer['message'])) {
                    $post_data['text'] = $answer['message'];
                } else if(isset($answer['keyword']['message'])){
                        $post_data['text'] = $answer['keyword']['message'];

                    }

                $post_data['question_id'] = $item['id'];

                print_r($post_data);

                $result = $this->{$code}->reply_question($post_data, $api_info);


                print_r($result);

                if($answer['action']){

                    $update_list=array();

                   $product_info = $this->getMarketProduct($item['url']);
                   if($product_info){

                       $update_list[] = array(
                           "barcode" => $product_info['barcode'],
                           "stockCode" => $product_info['stock_code'],
                           "shipping_time" => 2,
                           "marketplace_product_id" => $product_info['marketplace_product_id'],
                           "salePrice" => 0,
                           "listPrice" => 0,
                           "quantity" => 0,

                       );

                       $result = $this->{$code}->update_fast($update_list, $api_info);
                       $this->udb->query("delete from market_product where market_product_id='".$product_info['market_product_id']."' ");

                   }

                 //print_r($product_info);
                }

            }

        }

        return;

        // print_r($question_list);


    }

    private function getMarketProduct($sku)
    {

      $query =  $this->udb->query("select * from market_product where marketplace_product_id like '".$sku."'  or barcode='".$sku."' or model='".$sku."'");

   return $query->row;

    }

    public function questions($mode = false)
    {

        $total_new = 0;

        $this->load->model('entegrasyon/general');


        $this->load->model('entegrasyon/question');
        $marketplaces = $this->model_entegrasyon_general->getMarketPlaces();

        $questions = array();

        foreach ($marketplaces as $marketplace) {
            if ($marketplace['status'] && ($marketplace['code'] == 'ty' || $marketplace['code'] == 'hb' || $marketplace['code'] == 'gg' || $marketplace['code'] == 'n11')) {
                $this->load->model('entegrasyon/question/' . $marketplace['code']);
                $questions[$marketplace['code']] = $this->{'model_entegrasyon_question_' . $marketplace['code']}->getQuestions();
            }

        }

        $total_question_count = array();


        foreach ($questions as $code => $questionpatch) {
            $question_count = 0;


            foreach ($questionpatch['result'] as $question) {


                $question_info = $this->model_entegrasyon_question->getQuestion($question['id']);

                if (!$question_info) {


                    //soruları Veritabanına Yazdırıyoruz
                    $this->model_entegrasyon_question->addQuestion($question, $code);


                    $total_new++;
                    $question_count++;


                } else if ($question['new_message'] && $question_info['answered']) {


                    $this->model_entegrasyon_question->updateQuestion($question);
                    $total_new++;
                    $question_count++;

                } else if ($question['rejected']) {
                    $this->model_entegrasyon_question->updateRejectedQuestion($question);


                }


            }

            $total_question_count[$code] = $question_count;

        }

        if ($mode) {

            return array('total' => $total_new, 'markets' => $total_question_count);
        } else {
            echo json_encode(array('total' => $total_new, 'markets' => $total_question_count));


        }

    }


    /*
        public function product()
        {



            $this->load->model('entegrasyon/general');

            if (!$this->model_entegrasyon_general->checkPermission()) {

                echo json_encode(array('status' => false, 'message' => 'Gerçek Mağaza bilgileri kullanıldığı için Demo versiyonda Ürün Güncellemesine izin verilmemektedir.'));
                return;

            }


            echo '<html dir="ltr" lang="en">
    <head>
    <meta charset="UTF-8" /></head><body>';
            date_default_timezone_set('Europe/Istanbul');
            $product_count = 0;
            set_time_limit(0);
            ini_set("memory_limit", '-1');
            ini_set('max_execution_time', 118000);
            //$last_update_date='2020-05-26 15:30:50';//$this->model_entegrasyon_general->getLastUpdateSession(1);
            $last_update_date = $this->config->get('module_entegrasyon_last_update');//$this->model_entegrasyon_general->getLastUpdateSession(1);


            if (!$last_update_date) {

                $last_update_date = date("Y-m-d H:i:s", strtotime("-2 day"));
            }

            $marketPlaces = $this->model_entegrasyon_general->getMarketPlaces();


            //  echo "Son Güncelleme Tarihi=".$last_update_date.'<br>';

            $marketplace_products = $this->model_entegrasyon_general->getUpdatableProducts();


            $i = 1;

            if ($marketplace_products) {
                echo '<h2 style="color:darkred">Kalan güncellenecek Ürün Sayısı:' . count($marketplace_products) . '</h2><h3 style="color:darkgreen">Güncelleme Devam Ediyor, Lütfen Bekleyiniz...</h3><br>';

                echo 'Başlangıç:' . strtotime('h:i:s', time()) . '<br>';
                foreach ($marketplace_products as $key => $marketplace_product) {
                    //  $product_modified_date=strtotime($marketplace_product['date_modified']);

                    //Son Güncelleme Tarihi ile sıradaki ürününn son güncelleme tarihini karşılaştır.
                    //Update edilebilir en az 1 ürün vasa yeni bir update session Oluştur.
                    // $update_session_id=$this->model_entegrasyon_general->createUpdateSession(1);


                    foreach ($marketPlaces as $marketPlace) {
                        $product = $this->entegrasyon->getProduct($marketplace_product['product_id'],$marketPlace['code']);

                        if ($marketPlace['status']) {

                            if ($marketplace_product[$marketPlace['code']]) {

                                // echo $product['name'].'-'.$marketPlace['name'].' de Güncellenebilir';
                                $product_info = $this->entegrasyon->getProductForUpdate($marketPlace['code'], $product,0,true,HTTPS_SERVER);


                                $product_info['model'] = $this->config->get($marketPlace['code'] . '_setting_model_prefix') . $product_info['model'];

                                $post_data['request_data'] = $product_info;
                                $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace($marketPlace['code']);

                                $result = $this->entegrasyon->clientConnect($post_data, 'update_basic', $marketPlace['code'], false);

                                if ($result['status']) {

                                    $marketplace_data = unserialize($product_info[$marketPlace['code']]);
                                    $marketplace_data['commission'] = $product_info['defaults']['commission'];
                                    $marketplace_data['price'] = $product_info['sale_price'];

                                    $this->entegrasyon->addMarketplaceProduct($product_info['product_id'], $marketplace_data, $marketPlace['code']);


                                    echo $i . ' : ' . $marketPlace['name'] . ' : ' . $product_info['name'] . '<strong style="color: #0baf5c"> Güncellendi</strong><br>';

                                } else {

                                    $error = $this->entegrasyon->getError($product_info['product_id'], $marketPlace['code']);
                                    if ($error) {
                                        $this->entegrasyon->updateError($product_info['product_id'], $marketPlace['code'], 3, $result['message']);
                                    } else {
                                        $this->entegrasyon->addError($product_info['product_id'], $marketPlace['code'], 3, $result['message']);
                                    }

                                    echo $i . ' : ' . $marketPlace['name'] . ' : ' . $product_info['name'] . '<strong style="color: darkred> Güncellenmedi!</strong> ' . $result["message"] . '<br>';


                                }


                                $logmesage=$product_info['model'] . ' Action:Update - Cron - Product';;

                                $logmesage.=' - Update content:'.'Stok & Fiyat';

                                $logmesage.='-Stock - :'.$product_info['quantity'].' - Sale Price:'.$product_info['sale_price'].' - List Price:'.$product_info['list_price'];

                                $logmesage.='- Result:'.$result['message'];

                                $this->entegrasyon->log($marketPlace['code'],$logmesage,false);


                            }


                        }


                    }


                    try {

                        $sql = "update " . DB_PREFIX . "product SET date_modified='2018-04-17 10:00:00' where product_id='" . $marketplace_product['product_id'] . "'";

                        $this->db->query($sql);


                    } catch (Exception $exception) {
                        echo $exception->getMessage();

                    }

                    $i++;
                    if ($i == 10) {

                        echo 'Bitiş' . strtotime('h:i:s', time()) . '<br>';
                        echo '<meta http-equiv="refresh" content="1;url=index.php?route=entegrasyon/update/product" />';

                        return;
                    }

                }

            } else {

                echo 'Güncellenecek Ürün Bulunamadı! Güncelleme yapılabilemesi için en az bir pazaryerinde bulunan bir ürününüz olmalı ve bu ürünün özellileri Admin/katalog/product sayfasında değiştirilmiş olmalıdır.';

            }

            // echo 'hohoho';

            $query = $this->db->query("select now() as last_date");
            $last_date = $query->row['last_date'];


            $this->entegrasyon->editSetting('module_entegrasyon', array('module_entegrasyon_last_update' => $last_date, 'module_entegrasyon_status' => $this->config->get('module_entegrasyon_status'), 'module_entegrasyon_version' => $this->config->get('module_entegrasyon_version')));


        }
    */


    public function test_question()
    {





        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);


        if (isset($_REQUEST['mode'])) {
            $mode = true;
        } else {
            $mode = false;
        }

        $debug = false;
        if (isset($this->request->get['debug'])) {

            $debug = true;
        }

        if (isset($_REQUEST['username'])) {
            $username = $_REQUEST['username'];
        } else {

            echo 'kullanıcı bulunamadı';
            return;
        }

        $this->reg->set('udb', new DB\Userdb(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, $username));


        $this->loadConfig();

        $user_info_query = $this->db->query("SELECT * FROM `oc_user_database` ud left join oc_user u on(ud.database_id=u.user_database_id) where ud.name='" . $username . "'");


        $user_info = $user_info_query->row;

        $this->user_info = $user_info;

        $this->load->model('tool/entegrasyon_api');



        $active_market = $code='hb';

        $api_info = $this->model_tool_entegrasyon_api->getEntegrasyonApiInfo($active_market, $user_info['database_id']);

        $question_list[$active_market] = $this->{$active_market}->get_questions($api_info);

        print_r($question_list);
        return;




        $result = $this->{$code}->reply_question($post_data, $api_info);



    }

}