<?php

class ModelEntegrasyonGeneral extends Model {


    public function getMarketPlaces()
    {
        $this->load->model('tool/image');
        $marketplaces = array();
        $markets= unserialize($this->config->get('mir_marketplaces'));
        if ($markets){
            foreach ($markets as $market) {

                $marketplaces[] = array(
                    'name'      => $market['marketname'],
                    'logo'     =>$this->model_tool_image->resize('entegrasyon-logo/'.$market['code'].'-logo.png', 40, 40),
                    'status'    => $market['status'],
                    'member_type'=>$market['usergroupname'],
                    'code'      => $market['code'],
                    'domain_id'=>$market['domain_id'],
                    'domain_marketplace_id'=>$market['domain_marketplace_id'],
                    'edit'     => ''
                );
            }
        }
        return $marketplaces;

    }
    public function loadPageRequired()
    {


        //$this->document->addStyle('https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.0/css/bootstrap.min.css');
        //  $this->document->addScript('https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.0/js/bootstrap.min.js');


        $this->document->addScript('https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js');
        $this->document->addStyle('https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css');

        $this->document->addScript('https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js');
        $this->document->addScript('https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js');
        $this->document->addStyle('https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css');
        $this->document->addScript('https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.4/js/bootstrap-dialog.min.js');
        $this->document->addStyle('https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.4/css/bootstrap-dialog.min.css');
        $this->document->addScript('//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/js/bootstrap-editable.min.js');
        $this->document->addStyle('//cdnjs.cloudflare.com/ajax/libs/x-editable/1.5.0/bootstrap3-editable/css/bootstrap-editable.css');
        $this->document->addScript('view/javascript/entegrasyon/typeahead.js');
        $this->document->addScript('view/javascript/entegrasyon/typeaheadjs.js');
        $this->document->addScript('https://cdnjs.cloudflare.com/ajax/libs/jquery-toast-plugin/1.3.2/jquery.toast.min.js');
        $this->document->addStyle('https://cdnjs.cloudflare.com/ajax/libs/jquery-toast-plugin/1.3.2/jquery.toast.min.css');
        $this->document->addScript('https://cdn.jsdelivr.net/npm/sweetalert2@10');
        $this->document->addStyle('https://cdn.jsdelivr.net/npm/sweetalert2@9/dist/sweetalert2.min.css');
        $this->document->addScript('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.js');
        $this->document->addStyle('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css');

        $this->document->addStyle('view/stylesheet/entegrasyon/entegrasyon.css');

    }


    public function get_answer($question)
    {

        $patterns=array();
        $patterns[] = array('action'=>false,'keyword'=>array('pahalı','piyasada','fiyat', 'fark', "ne farkı",'neden'),'message'=>'Merhabalar, ürün fiyatlari otomatik olarak güncellenmektedir. Bazen yazılımsal nedenlerden dolayı fiyat olması gerekenden yüksek yada düşük olabilmektedir, En kısa zamanda ilgileneceğiz. Anlayışınizdan dolayi teşekkür eder keyifli alışverişler dileriz.');
        $patterns[] = array('action'=>false,'keyword'=>array('parça','yedek','kırıldı','kırık','tamir','bozuldu'),'message'=>'Merhabalar, Ne yazıkki parça satışımız yoktur, Anlayışınızdan dolayı teşekkür eder keyifli alışverişler dileriz.');
        $patterns[] = array('action'=>true, 'keyword'=>array('bana ait','izinsiz','şikayet','kaldır','izin','ürünüm','markamız','görselleri','kanun','telif'),'message'=>'Merhabalar, ürünler entegrasyon yazılımı ile pazaryerine eklenmektedir, bu sebeple aksilikler yaşanabilmektedir, ürün ile en kısa zamanda ilgileneceğiniz, bilgi için teşekkür ederiz');
        $patterns[] = array('action'=>true, 'keyword'=>array('kargoya','ne zaman', 'verilecek'),'message'=>'Merhabalar, ürünüz tedarik sürecindedir, en kısa sürede siparişinizi kargolayacağız, gecikme için özür dileriz.');
        $patterns[] = array('action'=>true, 'keyword'=>array('resimdeki gibimi','ne zaman', 'verilecek'),'message'=>'Merhabalar, ürünüz tedarik sürecindedir, en kısa sürede siparişinizi kargolayacağız, gecikme için özür dileriz.');
        $patterns[] = array('action'=>true, 'keyword'=>array('orjinal','orginal'),'message'=>'Merhabalar, evet efendim orjinal ürüdür. keyifli alışverişler dileriz.');

        foreach ($patterns as $pattern){

            foreach ($pattern['keyword'] as $keyword) {

                if( strpos( $question, $keyword ) !== false) {
                    return  $pattern;
                }
            }

        }

        $pattern = array('action'=>false, 'keyword'=>array('','message' => 'Merhabalar, ürüne dair detaylı bilgiler en kısa zamanda eklenecektir, ilginizden dolayı teşekkür eder keyifli alışverişler dileriz.'));

        return $pattern;



    }


    public function update_product_price($code,$competition_price,$product_id)
    {
        $query = $this->db->query("select * from " . DB_PREFIX . "es_product where product_id='" . $product_id . "'");
        $row = $query->row;

        $variable = $row[''. $code . ''];
        $settings = unserialize($variable);
        $settings[$code.'_product_sale_price'] = $competition_price;
        $this->db->query("update " . DB_PREFIX . "es_product SET $code='" . $this->db->escape(serialize($settings)) . "', date_modified=NOW() where product_id = '".$row['product_id']."' ");



    }

    public function checkPermission()
    {

        $ara = strpos(HTTP_SERVER,'easyentegre');

        if($ara){

            return false;
        }else {

            return true;
        }

    }

    public function getMarketPlace($code)
    {
        $this->load->model('tool/image');
        $markets= unserialize($this->config->get('mir_marketplaces'));
        foreach ($markets as $market) {
            if($market['code']==$code){
                return array(
                    'name'      => $market['marketname'],
                    'logo'     =>$this->model_tool_image->resize('entegrasyon-logo/'.$market['code'].'-logo.png', 40, 40),
                    'status'    => $market['status'],
                    'member_type'=>$market['usergroupname'],
                    'code'      => $market['code'],
                    'domain_id'=>$market['domain_id'],
                    'domain_marketplace_id'=>$market['domain_marketplace_id'],
                    'edit'     => ''
                );
            }
        }


    }




    public function checkSoap()
    {

        $status=true;
        if (!extension_loaded('soap')) {

            $status = false;

        }

        return $status;

    }

    public function getUpdatableProducts($data=array())
    {
        $last_update_date =  $this->config->get('module_entegrasyon_last_update');
        if(!$last_update_date){

            $last_update_date=date("Y-m-d H:i:s", strtotime("-1 day"));
        }
        $sql="select p.product_id,p.quantity,p.price,p2m.n11,p2m.cs,p2m.gg,p2m.hb,p2m.ty,p2m.eptt,p2m.amz,p.date_modified from ".DB_PREFIX."es_product_to_marketplace p2m LEFT JOIN ".DB_PREFIX."product p ON(p.product_id=p2m.product_id) where p.date_modified >= '".$last_update_date."' ";


        if(isset($data['market'])){

            $sql .= " AND p2m.".$data['market']."!=''";
        }



        $query=$this->db->query($sql);
        if($query->num_rows){
            return $query->rows;
        }else {

            return false;
        }
    }
    public function getUpdatableProductsTotal($data=array())
    {
        $last_update_date =  $this->config->get('module_entegrasyon_last_update');
        if(!$last_update_date){

            $last_update_date=date("Y-m-d H:i:s", strtotime("-1 day"));
        }
        $sql="select count(*) as total from ".DB_PREFIX."es_product_to_marketplace p2m LEFT JOIN ".DB_PREFIX."product p ON(p.product_id=p2m.product_id) where p.date_modified >= '".$last_update_date."' ";



        if(isset($data['market'])){

            $sql .= " AND p2m.".$data['market']."!=''";
        }


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

        return $query->row['total'];
    }
    public function getUpdatableProductsTotalTest($data=array())
    {
        $last_update_date =  $this->config->get('module_entegrasyon_last_update');
        if(!$last_update_date){

            $last_update_date=date("Y-m-d H:i:s", strtotime("-1 day"));
        }
        $sql="select count(*) as total from ".DB_PREFIX."es_product_to_marketplace p2m LEFT JOIN ".DB_PREFIX."product p ON(p.product_id=p2m.product_id)  ";



        if(isset($data['market'])){

            $sql .= " WHERE p2m.".$data['market']."!=''";
        }




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

        return $query->row['total'];
    }


    public function getUpdatableProductsTest($data=array())
    {
        $last_update_date =  $this->config->get('module_entegrasyon_last_update');
        if(!$last_update_date){

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


        $sql="select p.product_id,p.quantity,p.price,p2m.n11,p2m.cs,p2m.gg,p2m.hb,p2m.ty,p2m.eptt,p2m.amz,p.date_modified from ".DB_PREFIX."es_product_to_marketplace p2m LEFT JOIN ".DB_PREFIX."product p ON(p.product_id=p2m.product_id)";


        if(isset($data['market'])){

            $sql .= " WHERE p2m.".$data['market']."!=''";
        }

        // $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];





        $query=$this->db->query($sql);
        if($query->num_rows){
            return $query->rows;
        }else {

            return false;
        }
    }


    public function createUpdateSession($update_type)
    {
        $this->db->query("INSERT INTO ".DB_PREFIX."es_update_session SET update_type='".$update_type."', date_created=NOW() ");
        return $this->db->getLastId();

    }

    public function getLastUpdateSession($update_type)
    {
        $query=  $this->db->query("SELECT date_created FROM `".DB_PREFIX."es_update_session`  WHERE `update_type`=".$update_type." ORDER BY update_session_id DESC LIMIT 0,1");
        if($query->num_rows){
            return $query->row['date_created'];

        }else {

            return '2000-05-25 10:00:00';

        }

    }



    public function getProductByModel($model)
    {

        $query= $this->db->query("select * from ".DB_PREFIX."product where model='".$model."'");

        return $query->row;

    }


    public function read_session($filename)
    {

        $dosyaAdi = DIR_DOWNLOAD . $filename.'.txt';
        $file = fopen($dosyaAdi, 'r');
        $jsonData = fread($file, filesize($dosyaAdi));
        fclose($file);

// JSON verisini diziye çevir
        $myArray = json_decode($jsonData, true);

        return $myArray;

        /* $log = new Log('testlog.log');
         $log->write("session Read");
         $log->write($myArray);
         echo 'yes';*/

    }

    public function delete_session($filename)
    {

        $this->session_set(array(),$filename);

    }

    public function session_set($array,$filename)
    {

        try {
            $jsonData = json_encode($array);

// Dosyayı aç ve veriyi dosyaya yaz
            $dosyaAdi = DIR_DOWNLOAD . $filename.'.txt';

            //  echo $dosyaAdi;
            $file = fopen($dosyaAdi, 'w');
            fwrite($file, $jsonData);
            fclose($file);
        } catch (Exception $exception) {

            echo $exception->getMessage();

        }


    }



}