<?php

namespace marketplace;

final class Eptt
{

    private $registry, $username, $password, $shopId;

    public function __construct($registry)
    {
        $this->registry = $registry;

    }

    public function login($data)
    {

        $this->username = $data['username'];
        $this->password = $data['password'];
        $this->shopId = $data['shopId'];


    }


    public function checkApi($params)
    {

        $yesterday = date("Y-m-d H:i:s", strtotime("+1 day"));
        $product_data['request_data'] = $yesterday;
        $result = $this->get_orders($product_data, $params);
        if(!$result['status']){

            $result['message']='Api bilgileriniz doğrulanmamıştır, lütfen kontrol ederek tekrar deneyiniz';
        }
        return $result;

    }

    public function add_product($product_data, $api_info)
    {


        $this->login($api_info);
        $status = false;
        $message = '';

        $category_info = explode('|', $product_data['category_setting']['eptt_category_id']);
        $parent_id = $category_info[0];
        $category_id = $category_info[1];
        $category_name = $category_info[2];

        if (isset($product_setting['selected_attributes'])) {
            $selected_attributes = $product_data['attributes'];
        } else {
            $selected_attributes = array();
        }


        if(isset($product_data['product_setting']['eptt_barcode'])){

            if($product_data['product_setting']['eptt_barcode']){
                $barcode = $product_data['product_setting']['eptt_barcode'];

            }else {

                $barcode =  $product_data['model']  ;

            }

        }else {

            $barcode =  $product_data['model']  ;
        }



        $productMainId = isset($product_data['product_setting']['eptt_product_code']) ? $product_data['product_setting']['eptt_product_code'] ?$product_data['product_setting']['eptt_product_code'] : $product_data['model']:$product_data['model'];

        $defaults = $product_data['defaults'];
//print_r($defaults);
//return;


        $product_data['sale_price'] = $this->priceControl($product_data['sale_price']);
        $product_data['list_price'] = $this->priceControl($product_data['list_price']);

        $list_price = $product_data['list_price'];
        $sale_price = $product_data['sale_price'];

        $price = $sale_price ? $sale_price : $list_price;
        $title = $product_data['title'];
        $description = $product_data['description'];


        $prod_atrrbute = array();

        $ozellikler = $product_data['attributes'];


        if (isset($ozellikler)) {
            foreach ($ozellikler as $oz) {
                foreach ($oz['attribute'] as $value) {
                    $prod_atrrbute['attribute'][] = array('name' => $value['name'], 'value' => $value['text']);
                }
            }
        }

        if (isset($attribute) and $attribute != '') {
            foreach ($attribute as $key => $value) {
                if (is_array($value)) {
                    if ($value[0] != '') {
                        $prod_atrrbute['attribute'][] = array('name' => $key, 'value' => $value[0]);
                    }
                } else {
                    if ($value != '') {
                        $prod_atrrbute['attribute'][] = array('name' => $key, 'value' => $value);
                    }
                }
            }
        }


        // ürün stokta var mı yok mu
        if ($product_data["quantity"] > 0) {
            $mevcut = true;
        } else {
            $mevcut = false;
        }

        // ürün durumu daha önce gönderildi ise mevcut, yeni ürün ise yeni


        $kd = new \stdClass();
        $kd->KayitDurum = 'Yeni';

        $kdv = number_format($product_data['kdv'], 0);


        if ($product_data['tag'] != '') {
            $tag = $product_data['tag'];
        } else {
            $tag = explode(' ', $title);
            if (count($tag) > 1) {
                $tag = implode(', ', $tag);
            } else {
                $tag = $tag[0];
            }
        }

        $product_data['sale_price'] = $this->priceControl($product_data['sale_price']);
        $product_data['list_price'] = $this->priceControl($product_data['list_price']);
        $iskonto = 0;
        $price = $product_data['sale_price'];

        if ($product_data['list_price'] > $product_data['sale_price']) {

            $fiyat_farki = $product_data['list_price'] - $product_data['sale_price'];

            $kdvsiz_fiyat_farki = (float)$fiyat_farki / ((100 + $kdv) / 100);
            $fiyat = (float)$product_data['list_price'] / ((100 + $kdv) / 100);

            // echo $fiyat;

            $iskonto = (float)($kdvsiz_fiyat_farki * 100) / $fiyat;

        } else {

            $iskonto = 0;
        }


        $price = $product_data['list_price'];

        $images = $product_data['images'];


        $desi = (int)$product_data['weight'] ? number_format($product_data['weight'], 2, '.', '') : 1;
        $stokadet = (int)$product_data["quantity"];
        // eptt ürün gönderimi


        $variant = array();



        if (isset($product_data['variants']['variants']['options'])) {


            $variant['Variant'] = array();


            foreach ($product_data['variants']['variants']['options'] as $key => $option) {


                $variant['Variant'][$key] = array();
                $urun_secenek = array();

                $urun_secenek['VariantAttr'] = array();

                foreach ($option['attributes'] as $k => $attribute) {

                    // $variant->Variant->{$key}->{"Variant".($k+1)."Deger"} = $attribute['value'];

                    $urun_secenek['VariantAttr'][$k] = array();
                    $urun_secenek['VariantAttr'][$k]['Durum'] = 'Mevcut';
                    $urun_secenek['VariantAttr'][$k]['Deger'] = $attribute['value'];
                    $urun_secenek['VariantAttr'][$k]['FiyatFarkiMi'] = $option['price'] ? true:false;

                    if($option['price']){
                        $urun_secenek['VariantAttr'][$k]['Fiyat'] = $option['price'];

                    }
                    $urun_secenek['VariantAttr'][$k]['Tanim'] = $attribute['name'];
                }


                $variant['Variant'][$key]['AnaUrunKodu'] = $product_data['model'];
                $variant['Variant'][$key]['VariantBarkod'] = $product_data['model'] . $option['prefix'];
                $variant['Variant'][$key]['Miktar'] = $option['quantity'];

                $variant['Variant'][$key]['Attributes'] = $urun_secenek;;


            }


        } else {

            $variant = null;
        }
        $description = html_entity_decode($description, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 , 'UTF-8');

        $description = str_replace("&nbsp;", "<br>", $description);
        $description = str_replace("&#39;", "'", $description);
        $product_array = array(
            'Aciklama' =>$description,
            'Agirlik' => 0,
            'Aktif' => true, // kapatmak için false
            'YeniKategoriId' => (int)$category_id,
            'Barkod' => $barcode,
            'Desi' => $desi,
            'Durum' => $kd->KayitDurum,
            'GarantiSuresi' => 0,
            'GarantiVerenFirma' => null,
            'Iskonto' => $iskonto,
            'KDVOran' => $kdv,
            'KDVli' => $price,
            'KDVsiz' => (float)$price / ((100 + $kdv) / 100),
            'KategoriBilgisiGuncelle' => 0,
            'Mevcut' => $mevcut, // stokta yok için false
            'Miktar' => $product_data['quantity'],
            'TedarikciAltKategoriAdi' => null,
            'TedarikciAltKategoriId' => 0,
            'TedarikciSanalKategoriId' => 0,
            'ShopId' => $this->shopId, // mağaza shop id
            'Tag' => $tag, // ürün etiketleri virgül ile ayrılmış
            'UrunAdi' => $title,
            'KayitDurum' => $kd->KayitDurum,
            'UrunId' => 0,
            'UrunUrl' => null,
            'UrunResimleri' => $images,
            'VariantListesi' => $variant
        );


        $eptturun = new \stdClass();


        $eptturun->item = (object)$product_array;


        // print_r($eptturun);return;

        $result = $this->clientConnect('StokGuncelleV2', [$eptturun]);


        //  print_r($result);
        //  return ;

        if ($result['status']) {


            if (isset($result['result']->StokGuncelleV2Result)) {


                if (isset($result['result']->StokGuncelleV2Result->ErrorMessage)) {

                    $error = $result['result']->StokGuncelleV2Result->ErrorMessage;
                    if (strpos($error, 'stoklarınızda mevcut')) {

                        $status = true;
                        $message = 'Ürün Mevcut, Eşitlendi';

                    } else {
                        $message = $error;

                        $status = false;

                    }


                } else {
                    $message = "Ürün Eptt mağazanıza başarıyla gönderildi";

                    $status = true;

                }

            } else {

                $status = false;
                $message = $result['message'];
            }

        }


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


    }

    public function get_products($product_data, $api_info)
    {


        set_time_limit(0);
        ini_set("memory_limit", '-1');
        ini_set('max_execution_time', 118000);
        $this->login($api_info);
        $params = new \stdClass();
        $params->ShopId = $this->shopId;
        //$params->SearchKategoriId=0;
        // $params->SearchAltKategoriId=0;
        // $params->SearchUrunAdi="";
        $params->SearchBarkod = "";
        $params->SearchAktifPasif = 0;
        $params->SearchMevcut = 0;
        // $params->Page=1;
        //$params->limit=10;


        //  $eptturun = new \stdClass();
        //   $eptt_filter = (object)$filter_data;

        $products = array();

        $total = 0;
        $status = false;
        $result = $this->clientConnect('StokKontrolListesi', [$params]);

        $result = json_decode(json_encode($result), true);


        if ($result['status']) {
            $total = count($result['result']['StokKontrolListesiResult']['StokKontrolDetay']);

            $pages = ceil($total / 100);


            if ($total > 0) {
                foreach ($result['result']['StokKontrolListesiResult']['StokKontrolDetay'] as $item) {

                    $product = array(
                        'market_id' => $item['UrunId'],
                        'model' => $item['Barkod'],
                        'barcode' => $item['Barkod'],
                        'stock_code' => $item['Barkod'],
                        'product_code'=>$item['UrunId'],
                        'quantity'=>$item['Miktar'],
                        'list_price' => $item['KDVsiz'],
                        'name' => $item['UrunAdi'],
                        'sale_price' => $item['KDVsiz'],
                        'sale_status' => !$item['Aktif'] || !$item['Miktar'] || !$item['Mevcut'] ? 0 : $item['Aktif'],
                        'approval_status' => 1,
                        'custom_data'=>$item
                    );
                    $products[] = $product;
                }
            }

            $status = true;
        }

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


    }


    public function update_basic($product_data, $api_info, $mode = 'open')
    {

        //print_r($product_data);
        //return;

        $this->login($api_info);

        $iskonto = 0;
        $kdv = number_format($product_data['kdv'], 0);


        $price = $product_data['sale_price'];

        $product_data['sale_price'] = $this->priceControl($product_data['sale_price']);
        $product_data['list_price'] = $this->priceControl($product_data['list_price']);


        if ($product_data['list_price'] > $product_data['sale_price']) {

            $fiyat_farki = $product_data['list_price'] - $product_data['sale_price'];


            // echo 'list price:'.$product_data['list_price'].'<br>';
            // echo 'sale price:'.$product_data['sale_price'].'<br>';
            // echo 'kdvli ürün fiyat farkı='.$fiyat_farki.'<br>';

            $kdvsiz_fiyat_farki = (float)$fiyat_farki / ((100 + $kdv) / 100);

            // echo 'kdv siz fiyat farkı:'.$kdvsiz_fiyat_farki.'<br>';



            $fiyat = str_replace(',','',$product_data['list_price']) / ((100 + $kdv) / 100);

            //  echo 'fiyat:'.$fiyat.'<br>';

            $iskonto = (float)($kdvsiz_fiyat_farki * 100) / $fiyat;

            // echo 'iskonto.:'.$iskonto;


        }


        $price = $product_data['list_price'];


        if (!isset($product_data['Barkod'])) {


            if ($mode == 'close') {
                $aktif = 0;
                $mevcut = 0;
            } else if ($mode == 'open') {

                $aktif = $product_data['quantity'] > 0 ? 1 : 0;
                $mevcut = $product_data['quantity'] > 0 ? 1 : 0;

            }



            if(isset($product_data['product_setting']['eptt_barcode'])){

                if($product_data['product_setting']['eptt_barcode']){
                    $barcode = $product_data['product_setting']['eptt_barcode'];

                }else {

                    $barcode =  $product_data['model']  ;

                }

            }else {

                $barcode =  $product_data['model']  ;
            }

            $product_array = array(
                'Barkod' => $barcode,
                'KDVOran' => $kdv,
                'Iskonto' => $iskonto,
                'KDVOran' => $kdv,
                'KDVli' => $price,
                'KDVsiz' => (float)$price / ((100 + $kdv) / 100),
                'Miktar' => $product_data['quantity'],
                'Aktif' => $aktif, // kapatmak için false
                'Mevcut' => $mevcut,
                'ShopId' => $this->shopId, // mağaza shop id
            );

            if (isset($product_data['variants'])) {

                if ($product_data['variants']) {

                    $barcode = $product_data['model'];

                    if ($product_data['variants']['variants']) {
                        $variants = isset($product_data['variants']['variants'][0]['attributes']) ? $product_data['variants']['variants'] : $product_data['variants']['variants']['options'];

                    } else {

                        $variants = array();
                    }


                    $variant = array();

                    if ($variants) {


                        $variant['Variant'] = array();


                        foreach ($variants as $key => $option) {


                            $variant['Variant'][$key] = array();
                            $urun_secenek = array();

                            $urun_secenek['VariantAttr'] = array();

                            foreach ($option['attributes'] as $k => $attribute) {

                                // $variant->Variant->{$key}->{"Variant".($k+1)."Deger"} = $attribute['value'];

                                $urun_secenek['VariantAttr'][$k] = array();
                                $urun_secenek['VariantAttr'][$k]['Deger'] = $attribute['value'];
                                $urun_secenek['VariantAttr'][$k]['FiyatFarkiMi'] = false;
                                $urun_secenek['VariantAttr'][$k]['Fiyat'] = $option['price'];
                                $urun_secenek['VariantAttr'][$k]['Tanim'] = $attribute['name'];
                            }


                            $variant['Variant'][$key]['AnaUrunKodu'] = $product_data['model'];
                            $variant['Variant'][$key]['VariantBarkod'] = $product_data['model'] . $option['prefix'];
                            $variant['Variant'][$key]['Miktar'] = $option['quantity'];
                            $variant['Variant'][$key]['Attributes'] = $urun_secenek;;


                        }


                    }
                    $product_array['VariantListesi'] = $variant;


                }

            }


            $product_data = $product_array;

            $eptturun = new \stdClass();
            $eptturun->item = (object)$product_data;


            //print_r($eptturun);return;

            $result = $this->clientConnect('StokFiyatGuncelle3', [$eptturun]);

            //print_r($result);
            //return;

            $status = false;



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

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


            } else {
                $message = 'Ürün başarıyla Güncellenmiştir';

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


            }


        }
    }


    public function priceControl($price)
    {

        return str_replace(',', '.', $price);
    }

    public
    function close_for_sale($product_data, $api_info)
    {


        /*   $update_data = array(
               'model' => $product_data['model'],
               'kdv' => $product_data['kdv'],
               'sale_price' => $product_data['sale_price'],
               'list_price' => $product_data['list_price'],
               'quantity' => $product_data['quantity'],
               'aktif' => false ,// kapatmak için false
               'mevcut' => false,
               'iskonto' => 0 );
        */


        return $this->update_basic($product_data, $api_info, 'close');
        //print_r($return);

    }

    public
    function open_for_sale($product_data, $api_info)
    {


        /*  $update_data = array(
              'model' => $product_data['model'],
              'kdv' => $product_data['kdv'],
              'sale_price' => $product_data['sale_price'],
              'list_price' => $product_data['list_price'],
              'quantity' => $product_data['quantity'],
              'aktif' => true, // kapatmak için false
              'mevcut' => true,
              'iskonto' => 0
          );*/

        return $this->update_basic($product_data, $api_info, 'open');


    }


    public
    function get_orders($product_data, $api_info)
    {


        //return array('status'=>true,'message'=>'','result'=>array());
        // $dateTime=$product_data['request_data'];
        $tomorrow = date("Y-m-d H:i:s", strtotime("-10 day"));
        $dateTime = $tomorrow;
        $this->login($api_info);

        $baslangicTarihi = new \DateTime($dateTime);

        $bitisTarihi = new \DateTime(); // now()
        $aktifSiparisler = 0;

        $params = new \stdClass();
        $params->BaslangicTarihi = $baslangicTarihi->format(\DateTime::RFC3339);
        $params->BitisTarihi = $bitisTarihi->format(\DateTime::RFC3339);
        $params->AktifSiparisler = $aktifSiparisler;


        $result = $this->clientConnect('SiparisKontrolListesiV2', [$params]);


        return $result;
    }


    public
    function clientConnect($metod, $params)
    {
        $status = true;
        //return array('status'=>0,'message'=>'EpttAvm Api çok yakında tekrar aktif olacaktırç','result'=>array());

        ini_set("default_socket_timeout", 90);
        if (!class_exists('SoapClient')) {
            echo 'Soap Yüklü Değil';
            exit;
        }
        ini_set('display_errors', 0);
        $wss_ns = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';


        $auth = new \stdClass();
        $auth->Username = new \SoapVar($this->username, XSD_STRING, NULL, $wss_ns, NULL, $wss_ns);
        $auth->Password = new \SoapVar($this->password, XSD_STRING, NULL, $wss_ns, NULL, $wss_ns);
        $username_token = new \stdClass();
        $username_token->UsernameToken = new \SoapVar($auth, SOAP_ENC_OBJECT, NULL, $wss_ns, 'UsernameToken', $wss_ns);
        $security_sv = new \SoapVar(
            new \SoapVar($username_token, SOAP_ENC_OBJECT, NULL, $wss_ns, 'UsernameToken', $wss_ns),
            SOAP_ENC_OBJECT, NULL, $wss_ns, 'Security', $wss_ns);


        $opts = array(
            'http' => array(
                'user_agent' => 'PHPSoapClient'
            ),
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );
        $context = stream_context_create($opts);
        ini_set('soap.wsdl_cache_enabled', 0);
        ini_set("default_socket_timeout", 90);
        $client = new \SoapClient('https://ws.pttavm.com:93/service.svc/service?wsdl', [
            'soap_version' => SOAP_1_1,
            'stream_context' => $context,
            'exceptions' => true,
            'connection_timeout' => 90,
            'trace' => true
        ]);

        $error = '';
        $result = null;


        try {
            $soap_header = new \SoapHeader($wss_ns, 'Security', $security_sv, true);
            $client->__setSoapHeaders($soap_header);


            $result = $client->__soapCall($metod, $params);


        } catch (\SoapFault $exception) {

            $error = $exception->getMessage();

        }

        if ($error) {

            $status = false;
        }


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


    }


}
