<?php
class ControllerEntegrasyonSync extends Controller
{
    private $error = array();
    private $check;
    private $token_data;
    private $validate = true;
    private $reg = null;

    public function __construct($registry)
    {

        parent::__construct($registry);
        $this->reg = $registry;
        $this->load->model('entegrasyon/general');
        $this->token_data = $this->model_entegrasyon_general->getToken();

    }

    public function sync_products()
    {

        $limit=1000;
        $code = $this->request->get['code'];
        $total = $this->request->get['total'];
        $totalpage=round($total/$limit);

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }
        $matched =  $this->request->get['matched'];
        $unmatched =  $this->request->get['unmatched'];
        $this->load->model('entegrasyon/sync');

        $start=($page-1) * $limit;

        $query1 = $this->db->query("select * from market_product where code='".$code."' limit $start , $limit");

        // echo $query1->num_rows;
        //print_r($query1->rows);

        foreach ($query1->rows as $product) {
            //  echo $row['model'];

            $query =  $this->db->query("select  count(*) as total from market_product where `model`='".$this->db->escape($product['model'])."'");

            // echo $query->num_rows;
            if($query->row['total'] == 1){

                $query=$this->db->query("select * from product_url where barcode='".$this->db->escape($product['barcode'])."'");
                if($query->num_rows){
                    $marketplace_data = array('sale_status' => $product['sale_status'] && $product['quantity'] ? 1:0 , 'approval_status' => $product['approval_status'], 'commission' => 0, 'product_id' => isset($product['marketplace_product_id']) ? $product['marketplace_product_id'] : '', 'sale_price' => number_format($product['sale_price'],2), 'list_price' => number_format($product['list_price'],2), 'url' => $this->model_entegrasyon_sync->getMarketPlaceUrl($code, $product['marketplace_product_id']));
                    //$this->model_entegrasyon_sync->addMarketplaceProduct($query->row['product_id'], $marketplace_data, $code);
                    // $this->db->query("update market_product SET product_id='".$query->row['product_id']."' where `model`='" . $product['model'] . "' ");
                    $matched++;

                }else {
                    $unmatched++;
                }


            }
        }

        $page++;


        $url = 'index.php?route=entegrasyon/sync/sync_products&page=' . $page . '&total=' . $total . '&code=' . $code . '&matched=' . $matched . '&unmatched='.$unmatched.'&' . $this->token_data['token_link'];
        $json['matched'] = ((int)$matched);
        $json['unmatched'] = ((int)$unmatched);
        $json['page'] = $page;
        $json['total_page'] = $totalpage;
        $json['current_page'] = $page-1;

        if ($page <= $totalpage) {

            $json['status'] = true;
            $json['next'] = $url;

        } else {
            $json['message'] = 'Tamamlandı';
        }

        echo json_encode($json);


    }

    public function get_products_form()
    {
        ini_set('display_errors', 1);
        ini_set('display_startup_errors', 1);
        error_reporting(E_ALL);

        $code = $this->request->get['code'];


        $this->load->model('entegrasyon/product/marketplace/' . $code);





        $this->load->model('entegrasyon/general');
        $products = $this->{"model_entegrasyon_product_marketplace_" . $code}->getProducts(array('itemcount' => 1, 'sale_status'=>true, 'page' => 1));




        $query = $this->db->query("select count(*) as total from market_product where code='" . $code . "'");

        $data['downloaded'] = $query->row['total'];


        $data['unmatched'] = 0;
        $data['matched'] = 0;
        $data['total'] = $products['total'];
        $data['token_link'] = $this->token_data['token_link'];
        $data['code'] = $code;
        $marketPlace = $this->model_entegrasyon_general->getMarketPlace($code);

        $data['message'] = $products['message'];
        $data['marketplace'] = $marketPlace['name'];
        $data['info'] = $marketPlace['name'] . ' Mağazanızda yer alan tüm ürün bilgileri aşağıda listelenmiştir. Seknronizasyon işlemi ' . $marketPlace['name'] . ' ile web sitenizde yer alan ürünleri ürün kodlarına göre karşılaştırıp eşleştirir. Senkronizasyon işlemi herhangi bir stok yada fiyat güncellemesi yapmaz.';

        $this->response->setOutput($this->load->view('entegrasyon/sync/get_products_form', $data));

    }


    public function get_products_progress()
    {

        $code = $this->request->get['code'];
        $json = array();
        if (isset($this->request->get['total'])) {
            $total = $this->request->get['total'];
        } else {
            $total = 0;
        }

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            // $this->db->query("delete from market_product where code ='".$code."'");
            $page = 1;
            $this->delete_market_products($code);

        }




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

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

        }

        $downloaded = (int)$this->request->get['downloaded'];
        $totaldownloaded = (int)$this->request->get['totalDownloaded'];
        if ($code == 'cs') {
            $limit = 100;
        }else if($code=='pz'){

            $limit = 20;

        } else {

            $limit = 100;
        }

        $this->load->model('entegrasyon/product/marketplace/' . $code);
        // $debug=true;
        $products = $this->{"model_entegrasyon_product_marketplace_" . $code}->getProducts(array('itemcount' => $limit,'sale_status'=>true, 'page' => $page, $debug), $debug, $pasif);





        if ($total) {
            $datam['total'] = $total;
        } else if ($products['status']) {

            $datam['total'] = $products['total'];

        } else {
            $datam['total'] = 0;

        }

        $totalpage = ceil($datam['total'] / $limit);


        /*  if ($code == 'eptt') {
               $totalpage = 1;

           }*/

        $this->load->model("entegrasyon/sync");
        $render_product = array();
        if ($code == 'eptt') {

            $start = $page * $limit;
            $a = 0;
            for ($i = $start; $i < count($products['products']); $i++) {

                $render_product[] = $products['products'][$i];
                $a++;
                if ($a == $limit) break;
            }

        } else {
            $render_product = $products['products'];
        }

        // $json['unmatchedProductInfo']=array();


        //print_r($render_product);return;
        foreach ($render_product as $product) {



            $result = $this->model_entegrasyon_sync->addMarketProduct($product, $code);

            if ($result['downloaded']) {
                $downloaded++;
                $totaldownloaded++;
            }


        }



        $page++;


        $url = 'index.php?route=entegrasyon/sync/get_products_progress&page=' . $page . '&total=' . $datam['total'] . '&code=' . $code . '&totalDownloaded=' . $totaldownloaded . '&downloaded='.$downloaded.'&' . $this->token_data['token_link'];
        $json['downloaded'] = ((int)$downloaded);
        $json['page'] = $page;
        $json['total_page'] = $totalpage;
        $json['current_page'] = $page;


        if (($page < $totalpage) && $render_product) {

            $json['status'] = true;
            $json['next'] = $url;

        } else {

            $json['message'] = 'Tamamlandı';

        }

        echo json_encode($json);

    }

    public function delete_market_products()
    {
        // $this->db->query("delete from market_product where code='" . $code . "'");

        $code = $this->request->get['code'];

        // $this->db->query("update product_to_marketplace SET $code='' ");
        // $this->db->query("update variant_to_marketplace SET $code='' ");
        //$this->db->query("update market_product SET product_id=0 where code='" . $code . "' ");

        $this->db->query("delete from market_product where code='".$code."'");
        $this->db->query("update product_url SET $code=0 where user_id='".$this->user->getId()."' ");

        /// echo json_encode(array('status' => true));
    }



    public function product_match_form()
    {
        $data['token_link'] = $this->token_data['token_link'];
        $code = $this->request->get['code'];
        $filter_name = $this->request->get['matching_words'];
        $alternatives= explode(',',$filter_name);
        $product_type=$this->request->get['product_type'];
        $primary_id=$this->request->get['primary_id'];



        // $sql="SELECT * FROM market_product WHERE MATCH(name) AGAINST('".$this->db->escape($alternatives[0])."') and code='".$code."' ";
        $sql="SELECT * FROM market_product WHERE code='".$code."' ";
        foreach ($alternatives as $index=>$alternative) {

            if($index == 0){
                $sql.=" AND name like '".$this->db->escape($alternative)."%' ";
            }else {
                $sql.=" AND name like '%".$this->db->escape($alternative)."%' ";

            }
        }

        $sql.=" limit 3";

        //  echo $sql;return;


        $query = $this->db->query($sql);
        $product_datas = array();
        foreach ($query->rows as $product) {
            $product_datas[] = array(
                'name' => $product['name'],
                'model' => $product['model'],
                //'image' => $img,
                'market_product_id' => $product['market_product_id']
            );
        }
        $data['product_datas'] = $product_datas;
        $data['code']=$code;


        $data['primary_id']=$primary_id;
        $data['product_type']=$product_type;
        $this->response->setOutput($this->load->view('entegrasyon/sync/product_match_form', $data));

    }

    public function product_match_search()
    {
        $data['token_link'] = $this->token_data['token_link'];
        $filter_name = $this->request->get['filter_name'];
        $code = $this->request->get['code'];




        $alternatives= explode(' ',$filter_name);
        /* $sql="SELECT * FROM market_product WHERE MATCH(name) AGAINST('".$this->db->escape($alternatives[0])."') and code='".$code."' ";
         foreach ($alternatives as $index=>$alternative) {
             if($index>0){
                 $sql.=" AND name like '%".$this->db->escape($alternative)."%' ";
             }
         }*/

        $sql="SELECT * FROM market_product WHERE code='".$code."' ";
        foreach ($alternatives as $index=>$alternative) {
            // if($index > 0){
            $sql.=" AND name like '%".$this->db->escape($alternative)."%' ";
            //}
        }




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


        $product_datas = array();

        foreach ($query->rows as $product) {
            $product_datas[] = array(
                'name' => $product['name'],
                'model' => $product['model'],
                //'image' => $img,
                'market_product_id' => $product['market_product_id']
            );
        }



        $data['product_datas'] = $product_datas;
        $data['code']=$code;
        $data['primary_id']=$this->request->get['primary_id'];
        $data['product_type']=$this->request->get['product_type'];

        $this->response->setOutput($this->load->view('entegrasyon/sync/search_result', $data));


    }

    public function match()
    {
        $this->load->model('entegrasyon/sync');

        $market_product_id = $this->request->post['market_product_id'];
        $primary_id = $this->request->post['primary_id'];
        $product_type = $this->request->post['product_type'];
        $code = $this->request->post['code'];
        $query=$this->db->query("select * from market_product where market_product_id='".$market_product_id."'");
        $market_product_info = $query->row;

        $sale_status= $market_product_info['sale_status'] && $market_product_info['quantity'] ? 1:0;
        $marketplace_data = array('sale_status' => $sale_status , 'approval_status' => $market_product_info['approval_status'], 'commission' => 0, 'product_id' => isset($market_product_info['marketplace_product_id']) ? $market_product_info['marketplace_product_id'] : '', 'sale_price' => number_format($market_product_info['sale_price'],2), 'list_price' => number_format($market_product_info['list_price'],2), 'url' => $this->model_entegrasyon_sync->getMarketPlaceUrl($code, $market_product_info['marketplace_product_id']));

        $json=array();

        if($product_type==1){
            //Product
            $result= $this->model_entegrasyon_sync->addMarketplaceProduct($primary_id, $marketplace_data, $code);

            $json[]=array('product_type'=>1,'sale_price'=>$marketplace_data['sale_price'],'primary_id'=>$primary_id);


        }else {
            //Variant
            $variant_product= $this->db->query("select *  from product_variant where product_variant_id='".$primary_id."'")->row;
            $is_main_product_exists=$this->db->query("select count(*) as total from product_to_marketplace where product_id='".$variant_product['product_id']."' and  $code !=''" );


            if($is_main_product_exists->row['total']==0){


                $this->model_entegrasyon_sync->addMarketplaceProduct($variant_product['product_id'], $marketplace_data, $code);
                $json[]=array('product_type'=>1,'sale_price'=>$marketplace_data['sale_price'],'primary_id'=>$variant_product['product_id']);


            }

            $result=  $this->model_entegrasyon_sync->addMarketplaceVariant($primary_id, $marketplace_data, $code);
            $this->db->query("update market_product SET product_id='".$variant_product['product_id']."' where `market_product_id`='" . $market_product_id . "' ");

            $json[]=array('product_type'=>2,'sale_price'=>$marketplace_data['sale_price'],'primary_id'=>$primary_id);

        }




        echo json_encode($json);

    }

}
