<?php

namespace marketplace;
final class Etsy
{

    private $registry, $db, $session, $url, $config, $log, $customer, $currency, $tax, $parameters;
    private $base_url='https://openapi.etsy.com/v2';
    private $consumer_key='fra57e269fo96n57m6c4cz1p';
    private $consumer_secret='cslrhhtkik';
    //private $consumer_key='f38tva4akkmjd6n9hqx5mry5';
    //private $consumer_secret='qxryrfe12s';
    private $oauth=null;

    public function __construct($registry)
    {
        $this->db = $registry->get('db');
        $this->config = $registry->get('config');
        $this->session = $registry->get('session');
        $this->url = $registry->get('url');
        $this->log = $registry->get('log');
        $this->customer = $registry->get('customer');
        $this->currency = $registry->get('currency');
        $this->tax = $registry->get('tax');
        $this->registry = $registry;
        $this->parameters;
        if(!$this->oauth){
            $this->oauth = new \OAuth($this->consumer_key, $this->consumer_secret,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
        }
    }


    public function get_auth_url($params=array())
    {
        $req_token = $this->oauth->getRequestToken($this->base_url."/oauth/request_token?scope=email_r%20listings_r%20listings_w%20listings_d%20transactions_r%20transactions_w", 'oob', "GET");


        return array('status'=>1,'message'=>'başarılı','result'=>array('url'=>$req_token['login_url'],'api_data'=>$req_token));
    }



    public function test()
    {

        $result = $this->clientConnect($this->city_service, 'GetCities');
        print_r($result);
        echo 'OK!';

    }

    public function checkApi($params)
    {

        $message='';
        $data=array();
        $token_data=$this->verifier_api($params);

        if(!$token_data){
            $message.='Doğrulama için süreniz doldu, lütfen tekrar doğrulama linkine tıklayını.';

        }

        $shop_verify = file_get_contents($this->base_url.'/shops/'.$params['etsy_shop_name'].'?api_key='.$this->consumer_key);



        $data['token_info']=$token_data;
        $data['shop_data']=$shop_verify;
        return array('status'=>true,'message'=>$message,'result'=>$data);

    }


    public function shipping_templates($api_info)
    {

        $result=$this->clientConnect($this->base_url."/users/".$api_info['user_id']."/shipping/templates",$api_info,null);

        return $result;

    }

    public function create_shipping_template($request_data,$api_info)
    {
        $result=$this->clientConnect($this->base_url."/shipping/templates",$api_info,$request_data,'POST');

        print_r($result);
    }

    private function verifier_api($params){


        try {
            // set the verifier and request Etsy's token credentials url

            $this->oauth->setToken($params['temp_token'], $params['temp_token_secret']);
            $this->oauth->debug=true;
            return $this->oauth->getAccessToken($this->base_url."/oauth/access_token", null, $params['verified'], "GET");


        } catch (\OAuthException $e) {
            return false;
        }

    }

    public function check_permission($product_data, $api_info)
    {
        /*
                $this->oauth->setToken($api_info['etsy'], $access_token_secret);

                try {
                    $data = $oauth->fetch("https://openapi.etsy.com/v2/oauth/scopes", null, OAUTH_HTTP_METHOD_GET);
                    $json = $oauth->getLastResponse();
                    print_r(json_decode($json, true));

                } catch (OAuthException $e) {
                    error_log($e->getMessage());
                    error_log(print_r($oauth->getLastResponse(), true));
                    error_log(print_r($oauth->getLastResponseInfo(), true));
                    exit;
                }
        */
    }


    private function download_image($url)
    {

        $ext=pathinfo($url, PATHINFO_EXTENSION);
        $image_name=DIR_IMAGE.uniqid().'.'.$ext;

        $get_image=$this->getImgFromClient($url);


        if($get_image['status']){

            file_put_contents($image_name,$get_image['content']);
            return array('status'=>true,'message'=>'başarılı','result'=>$image_name);

        }else {

            return array('status'=>false,'message'=>$get_image['message'],'result'=>'');

        }



    }


    private function getImgFromClient($url)
    {

        //$url='https://www.ellconline.com/getimage.php?url='.$url;
        //$url='https://www.easyentegre.com/image/cache/catalog/referanslar/2-250x180.jpg';
        $url=str_replace(' ','%20',$url);
        $error=false;
        $handle=curl_init($url);
        curl_setopt($handle, CURLOPT_VERBOSE, true);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");

        $content = curl_exec($handle);
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

        $content = curl_exec($handle);
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

        if($httpCode!=200){

            $error=true;
        }


        if(!$error){

            return array('status'=>true, 'code'=>$httpCode, 'content'=>$content);

        }else {

            return array('status'=>false, 'code'=>$httpCode, 'content'=>$content);

        }


// Encode the image string data into base64

        // $url='https://www.ellconline.com/getimage.php?url='.$url;
        /*
                if($error){
                    $arrContextOptions = array(
                        "ssl" => array(
                            "verify_peer" => false,
                            "verify_peer_name" => false,
                        ),
                    );
                    // clearLastError();
                    $content = file_get_contents($url, false, stream_context_create($arrContextOptions));


                }else {
                    return  false;
                }

        */


    }


    public function upload_images($data,$api_info)
    {



        $ext=pathinfo($data['image']['url'], PATHINFO_EXTENSION);
        $image_name=DIR_IMAGE.uniqid().'.'.$ext;


        if($data['image']['base64']) {

            file_put_contents($image_name, base64_decode($data['image']['base64']));

            $mimetype = "image/png";
            $params = array('@image' => '@' . $image_name . ';type=' . $mimetype,'rank'=>$data['image']['photoId']+1);
            $url = $this->base_url."/listings/" . $data['listing_id'] . "/images";
            $result = $this->clientConnect($url, $api_info, $params, 'POST');

            unlink($image_name);
            return $result;

        }

    }


    public function add_product($product_data, $api_info)
    {

        ini_set('max_execution_time', 300); //300 seconds = 5 minutes


        $state=isset($product_data['product_setting']['etsy_state'])?$product_data['product_setting']['etsy_state']:'draft';
        $occasion=isset($product_data['product_setting']['etsy_occasion'])?$product_data['product_setting']['etsy_occasion']:$product_data['defaults']['occasion'];
        $recipient=isset($product_data['product_setting']['etsy_recipient'])?$product_data['product_setting']['etsy_recipient']:$product_data['defaults']['recipient'];
        $who_made=isset($product_data['product_setting']['etsy_who_made'])?$product_data['product_setting']['etsy_who_made']:$product_data['defaults']['who_made'];
        $when_made=isset($product_data['product_setting']['etsy_when_made'])?$product_data['product_setting']['etsy_when_made']:$product_data['defaults']['when_made'];


        $tags=array();


        foreach (explode(',',$product_data['tag']) as $tag) {

            if(strlen($tag) <= 20 && count($tags) < 13  && !in_array($tag,$tags)){

                $tags[]= $tag;
            }


        }






        $args =  array(
            "quantity" =>(int)$product_data['quantity'],
            "title" => $product_data['title'],
            "description" => strip_tags(html_entity_decode($product_data['description'])?html_entity_decode($product_data['description']):html_entity_decode($product_data['title'])),
            "price" => $product_data['sale_price'],
            //"materials" => array('wood, plastic'),
            "shipping_template_id" => $product_data['defaults']['shipping_template'],
            //"shop_section_id" => 123456,
            //"image_ids" => array(1), // Multimple?
            // "non_taxable" => false,
            //"processing_min" => 123456,
            //"processing_max" => 123456,
            //"category_id" => 123456,
            "currency_code"=>'USD',
            "taxonomy_id" => $product_data['category_id'],
            "tags" => implode(',',$tags),
            "is_supply" => true,


            // "style" => array('style1, style2')

        );

        if(isset($product_data['shipping'])){
            if($product_data['shipping']){
                $args['is_digital']=1;
            }
        }
        if($state)$args['state']=$state;
        if($occasion)$args['occasion']=$occasion;
        if($recipient)$args['recipient']=$recipient;
        if($who_made)$args['who_made']=$who_made;
        if($when_made)$args['when_made']=$when_made;


        //print_r($args);
        //return;


        /*
               $data = $this->oauth->fetch("https://openapi.etsy.com/v2/oauth/scopes", null, OAUTH_HTTP_METHOD_GET);

               $this->oauth->debug=false;
                $json = $this->oauth->getLastResponse();
                print_r(json_decode($json, true));
        */


        $status=false;
        $message=array();
        $send_data=$this->clientConnect($this->base_url.'/listings',$api_info,$args,'POST');
        $return_listing_data=array();

        if($send_data['status']){
            $status=true;

            $listing_data=$send_data['result']['results'][0];
            // $message.='product_send_success';
            foreach ($product_data['images'] as $image) {
                $data['listing_id']=$listing_data['listing_id'];
                $data['image']=$image;
                $image_data = $this->upload_images($data,$api_info);

                if(!$image_data['status']){

                    $message[]=$image_data['message'];

                }

            }

            $return_listing_data=array(
                'sale_status' => $listing_data['state'] == 'active' ? 1:0,
                'state'=>$listing_data['state'],
                'approval_status' => 1,
                'product_id' => $listing_data['listing_id'],
                'price' => $listing_data['price']

            );

        }



        if(!$send_data['status']){
            $message[]=$send_data['message'];

        }



        return array('status'=>$status,'message'=>implode('&',$message),'result'=>$return_listing_data);

    }


    public function open_for_sale($product_data, $api_info)
    {


        $url = "https://openapi.etsy.com/v2/listings/" . $product_data['product_id'];
        $result = $this->clientConnect($url, $api_info, array('listing_id'=>$product_data['product_id'],'state'=>'active'), 'PUT');
        return $result;

    }

    public function close_for_sale($product_data, $api_info)
    {


        $url = "https://openapi.etsy.com/v2/listings/" . $product_data['product_id'];
        $result = $this->clientConnect($url, $api_info, array('listing_id'=>$product_data['product_id'],'state'=>'inactive'), 'PUT');
        return $result;

    }

    public function delete_product($product_data, $api_info)
    {


        $url = "https://openapi.etsy.com/v2/listings/" . $product_data['product_id'];
        $result = $this->clientConnect($url, $api_info, null, 'DELETE');
        return $result;

    }



    private $attributes = array();

    public function category_attributes($request_data, $api_info)
    {

        ini_set('max_execution_time', 0); //0=NOLIMIT
        ini_set('set_time_limit', 0); //0=NOLIMIT

        $url='https://openapi.etsy.com/v2/taxonomy/seller/'.$request_data['category_id'].'/properties?api_key='.$this->consumer_key;

        $category_attributes=json_decode(file_get_contents($url),1);

        return array('status' => true, 'message' => 'başarılı', 'result' => $category_attributes['results']);

    }


    public function get_product($product_data, $api_info)
    {




        $product = json_decode(file_get_contents($this->base_url.'/listings/'.$product_data['product_id'].'?api_key='.$this->consumer_key),1);

        $Imagess = json_decode(file_get_contents($this->base_url.'/listings/'.$product_data['product_id'].'/images?api_key='.$this->consumer_key),1);



        $images=array();

        foreach ( $Imagess['results'] as $image) {

            $images[]=$image['url_fullxfull'];

        }



        $product['results'][0]['images']=$images;


        return array('status'=>true,'message'=>'','result'=>$product['results']);


    }


    public function update_all($product_data, $api_info)
    {




        // $state=isset($product_data['product_setting']['etsy_state'])?$product_data['product_setting']['etsy_state']:'draft';
        $occasion=isset($product_data['product_setting']['etsy_occasion'])?$product_data['product_setting']['etsy_occasion']:false;
        $recipient=isset($product_data['product_setting']['etsy_recipient'])?$product_data['product_setting']['etsy_recipient']:false;
        $who_made=isset($product_data['product_setting']['etsy_who_made'])?$product_data['product_setting']['etsy_who_made']:false;
        $when_made=isset($product_data['product_setting']['etsy_when_made'])?$product_data['product_setting']['etsy_when_made']:false;





        $args =  array(
            "quantity" =>$product_data['quantity'],
            "title" => $product_data['title'],
            "description" => strip_tags(html_entity_decode($product_data['description'])?html_entity_decode($product_data['description']):html_entity_decode($product_data['title'])),
            "price" => $product_data['sale_price'],
            //"materials" => array('wood, plastic'),
            //'sku'=>array($product_data['model']),
            "shipping_template_id" => $product_data['defaults']['shipping_template'],
            "is_digital" =>$product_data['shipping']?1:0,
            "currency_code"=>'USD',

            //"shop_section_id" => 123456,
            //"image_ids" => array(1), // Multimple?
            // "non_taxable" => false,
            //"processing_min" => 123456,
            //"processing_max" => 123456,
            //"category_id" => 123456,
            "taxonomy_id" => $product_data['category_id'],
            // "tags" => $product_data['tag'],
            "is_supply" => true,


            // "style" => array('style1, style2')

        );
        // if($state)$args['state']=$state;
        if($occasion)$args['occasion']=$occasion;
        if($recipient)$args['recipient']=$recipient;
        if($who_made)$args['who_made']=$who_made;
        if($when_made)$args['when_made']=$when_made;


        $etsy_data=unserialize($product_data['etsy']);


        //print_r($args);return;

        $url = $this->base_url."/listings/" . $etsy_data['product_id'];
        $result = $this->clientConnect($url, $api_info, $args, 'PUT');

        if(!$result['status']) return $result;

        $urlImages = "https://openapi.etsy.com/v2/listings/" . $etsy_data['product_id'].'/images';

        $getAllImages= $result = $this->clientConnect($urlImages, $api_info, null, 'GET');
        if($getAllImages['status']){

            foreach ($getAllImages['result']['results'] as $images) {

                $deleteurlImages = $this->base_url."/listings/" . $etsy_data['product_id'].'/images/'.$images['listing_image_id'];

                $result = $this->clientConnect($deleteurlImages, $api_info, null, 'DELETE');

            }




            // $message.='product_send_success';
            foreach ($product_data['images'] as $image) {


                $data['listing_id']=$etsy_data['product_id'];
                $data['image']=$image;
                $image_data = $this->upload_images($data,$api_info);

                if(!$image_data['status']){

                    $message[]=$image_data['message'];

                }


            }


        }






        return $result;


    }

    public function update_basic($product_data, $api_info)
    {




        $etsy_data=unserialize($product_data['etsy']);


        $url = "https://openapi.etsy.com/v2/listings/" . $etsy_data['product_id'];
        $result = $this->clientConnect($url, $api_info, array('listing_id'=>$etsy_data['product_id'],'quantity'=>$product_data['quantity'],"currency_code"=>'USD','price'=>$product_data['sale_price']), 'PUT');
        return $result;


    }


    public function clientConnect($url,$api_info,$params,$method='GET')
    {




        try {
            $this->oauth->setToken($api_info['access_token'], $api_info['access_token_secret']);
            $this->oauth->fetch($url,$params,$method);

            $response_info = $this->oauth->getLastResponse();

            return array('status'=>true,'message'=>'başarılı','result'=>json_decode($response_info,1));


        }catch (\OAuthException $exception){

            // echo $exception->getMessage() ;
            return array('status'=>false,'message'=>$exception->lastResponse.'-'.$exception->getMessage(),'result'=>array());

        }


    }


    public function get_products($product_info, $api_info)
    {




        $result = json_decode(file_get_contents($this->base_url.'/shops/'.$api_info['shop_id'].'/listings/active?api_key='.$this->consumer_key.'&limit='.$product_info['itemcount'].'&page='.$product_info['page']),1);



        return array('status'=>true,'message'=>'','result'=>$result);

    }

    public function get_orders($data, $api_info)
    {


        // $etsy_data=unserialize($product_data['etsy']);


        $url = "https://openapi.etsy.com/v2/shops/" . $api_info['shop_id'].'/receipts';

        $orders=array();


        $result = $this->clientConnect($url, $api_info, null, 'GET');



        foreach ($result['result']['results'] as $item) {



            $url = 'https://openapi.etsy.com/v2/receipts/'.$item['receipt_id'].'/transactions';




            $ordered_products = $this->clientConnect($url, $api_info, null, 'GET');

            $item['ordered_products']=array();
            foreach ($ordered_products['result']['results'] as $product) {



                $get_image=$this->clientConnect($this->base_url.'/listings/'.$product['listing_id'].'/images/'.$product['image_listing_id'], $api_info, null, 'GET')['result']['results'][0]['url_fullxfull'];
                $product['image']=$get_image;
                $item['ordered_products'][]=$product;

            }

            $item['ordered_country']=$this->clientConnect('https://openapi.etsy.com/v2/countries/'.$item['country_id'], $api_info, null, 'GET')['result']['results'][0];
            $orders[]=$item;


        }
        return array('status'=>true,'message'=>'','result'=>$orders);

    }


    public function getOrderInfo($order_id)
    {
        $this->parameters['orderRequest'] = array('id' => $order_id);
        return $this->clientConnect($this->order_service, 'OrderDetail');

    }

    public function get_questions($product_data, $api_info)
    {

        $this->parameters['auth'] = $api_info;
        $status='OPEN';
        $searchData=array(
            'productId'=>null,
            'buyerEmail'=>'',
            'subject'=>'',
            'status'=>$status,
            'questionDate'=>''
        );
        $pagingData = array(
            'currentPage'=>0,
            'pageSize'=>rand(10,99),
            'totalCount'=>100,
            'pageCount'=>null
        );


        $this->parameters['productQuestionSearch'] =$searchData;
        $this->parameters['pagingData'] = $pagingData;


        // return;

        $result = $this->clientConnect($this->product_service, 'GetProductQuestionList');

        return array('status' => true, 'message' => '', 'result' => $result);

    }

    public function get_question($product_data, $api_info)
    {

        $this->parameters['auth'] = $api_info;



        $this->parameters['productQuestionId'] = $product_data;

        $result = $this->clientConnect($this->product_service, 'GetProductQuestionDetail');


        $result_data=array(
            'status'=>$result['productQuestion']['status'],
            'productTitle'=>$result['productQuestion']['productTitle'],
            'userName'=>'',
            'text'=>$result['productQuestion']['question'],
            'creationDate'=>$result['productQuestion']['questionDate'],
        );

        if(isset($result['productQuestion']['answer'])){

            $answered_data=array(
                'text'=>$result['productQuestion']['answer']
            );

            $result_data['answer']=$answered_data;

        }


        return array('status' => true, 'message' => '', 'result' => $result_data);

    }
    public function reply_question($product_data, $api_info)
    {

        $this->parameters['auth'] = $api_info;
        $this->parameters['productQuestionId'] = $product_data['question_id'];
        $this->parameters['answer'] = $product_data['text'];

        $result = $this->clientConnect($this->product_service, 'SaveProductAnswer');

        return array('status' => true, 'message' => '', 'result' => $result);

    }






}