<?php

class ModelEntegrasyonOrderCs extends Model
{

    private $api_info = null;

    public function getFromMarket($order_number = false)
    {



        $is_active = true;


        if ($is_active) {


            $baslangicTarihi = new \DateTime(date("Y-m-d H:i:s", strtotime("+1 day")));

            $bitisTarihi = new \DateTime(date("Y-m-d H:i:s", strtotime("-10 day"))); // now()

            $end = $baslangicTarihi->format(\DateTime::RFC3339);
            $start = $bitisTarihi->format(\DateTime::RFC3339);


            if ($order_number) {
                $params = array(
                    "orderNo" => $order_number,
                    "pageSize" => 20,
                    "page" => 0);
                //"statusId"=>11
            } else {
                $params = array(
                    "startDate" => $start,
                    "endDate" => $end,
                    "pageSize" => 20,
                    "page" => 0
                    //"statusId"=>11

                );
            }




            $url = "https://apis.ciceksepeti.com/api/v1/Order/GetOrders";


            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

            $headers = array(
                "x-api-key: " . $this->api_info['apiKey'],
                "Content-Type: application/json",
            );

            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

            $data = json_encode($params);

            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

            $response = curl_exec($curl);

            curl_close($curl);




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

        } else {

            return array('status' => false, 'message' => 'Kullanım süreniz sona erdi, premium hesaba geçiş yapabilirsiniz.', 'result' => array());

        }

    }


    public function getOrders($debug = false, $mode = 'add', $api_info)
    {

        $this->api_info = $api_info;



        $orderList = array();

        $post_data['request_data']['start'] = date("Y-m-d H:i:s", strtotime("+1 day"));
        $post_data['request_data']['end'] = date("Y-m-d H:i:s", strtotime("-10 day"));

        $post_data['market'] = $this->model_entegrasyon_general->getMarketPlace('cs');

        $orders = $this->getFromMarket();//$this->model_entegrasyon_order->clientConnect($post_data, 'get_orders', 'cs', $debug);


        //print_r($orders);return ;



            if (isset($orders['result']['supplierOrderListWithBranch'])) {


                foreach ($orders['result']['supplierOrderListWithBranch'] as $order) {
                    if (!$this->model_entegrasyon_order->checkOrderByMarketPlaceOrderId($order['orderId'])) {


                        $orderx = $this->getOrder($order);




                        if (!$this->findOrderFromOrders($orderList, $orderx)) {
                            $orderList[] = $orderx;
                        } else {

                            $orderList = $this->findOrderFromOrders($orderList, $orderx);

                        }


                    }else {


                        if($order['isOrderStatusActive']){

                            $sonuc = strpos($order['orderProductStatus'],"İade");
                           if($sonuc===false){

                               $oc_order_status=$this->model_entegrasyon_order->getOrderStatus($order['orderProductStatus'], 'cs');


                           }else {
                               $oc_order_status=6;

                           }



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


                           if(!$order_info['cargo_number']){

                               $this->change_status($order['orderItemId']);

                           }

                        }else {

                            $oc_order_status=4;
                        }


              // print_r($order);

               $this->db->query("update `order` SET order_status='".$oc_order_status."',cargo_number='".$order['partialNumber']."',tracking_url='".$order['shipmentTrackingUrl']."' where market_order_id='".$order['orderId']."'");



                    }
                }
            }


            return $orderList;


    }

    public function findOrderFromOrders($orders, $order)
    {


        $result = false;

        foreach ($orders as $index => $item) {

            if ($item['order_id'] == $order['order_id']) {

                $item['products'][] = $order['products'][0];

                $item['total'] = $item['total'] + $order['total'];
                $item['totals'][0]['value'] = $item['totals'][0]['value'] + $order['totals'][0]['value'];
                $item['totals'][1]['value'] = $item['totals'][1]['value'] + $order['totals'][1]['value'];
                $item['totals'][2]['value'] = $item['totals'][2]['value'] + $order['totals'][2]['value'];

                $result = true;

                //unset($orders[$index]);
                $orders[$index] = $item;

            }

        }


        if ($result) {
            return $orders;
        } else {
            return false;
        }

    }


    public function check_order_status($orders,$api_info)
    {

        $this->api_info=$api_info;

$market_orders=$this->getOrders(false,'update',$this->api_info);


print_r($market_orders);
echo "----------------------";
        print_r($orders);
        return ;

        //$order_info=$this->getFromMarket('p',$order['market_order_id']);

        foreach ($orders as $order) {


         //   print_r($orders);


        $order_detail = $this->getFromMarket($order['market_order_id']);

        sleep(5);


        $result = array();

        if (isset($order_detail['result']['supplierOrderListWithBranch'])) {


            foreach ($order_detail['result']['supplierOrderListWithBranch'] as $csorder) {


                $query = $this->db->query("select * from `order` where market_order_id='" . $csorder['orderId'] . "'");


                $order_status = isset($csorder['orderProductStatus']) ? $csorder['orderProductStatus'] : '';
                $tracking_url = isset($csorder['shipmentTrackingUrl']) ? $csorder['shipmentTrackingUrl'] : '';
                $cargo_name = isset($csorder['cargoCompany']) ? $csorder['cargoCompany'] : '';
                $cargo_number = isset($csorder['partialNumber']) ? $csorder['partialNumber'] : '';


                $result['cs'][$query->row['order_id']] = array(
                    'status' => $order_status,
                    'tracking_url' => $tracking_url,
                    'order_id' => $order['market_order_id'],
                    'cargo_name' => $cargo_name,
                    'cargo_number' => $cargo_number,
                    'shipment_package_id' => '',
                    'invoice_link' => ''
                );



            }


        }


        }
        return $result;

    }


    public function getOrder($order)
    {


        $this->load->model('entegrasyon/general');
        $custom_data = $order['receiverName'];
        $first_name = $order['receiverName'];
        $lastname = '';
        $adres = $order['receiverAddress'];
        $sehir = $order['receiverCity'];
        $ilce = $order['receiverRegion'];
        $phone = $order['receiverPhone'];
        $postakodu = '';
        $email = $order['invoiceEmail'];
        $vergiNo = isset($order['senderTaxNumber']) ? $order['senderTaxNumber'] : '11111111111';
        $vergiDairesi = $order['senderTaxOfficeName'];

        if ($this->config->get('cs_setting_add_tc')) {

            $adres = $adres . 'Vergi/Kimlik No:' . $vergiNo;

        }

        $address_data = array(

            'firstname' => $first_name,
            'lastname' => $lastname,
            'company' => '',
            'tax_office' => '',
            'tax_id' => '',
            'address_1' => $adres,
            'address_2' => '',
            'city' => $sehir,
            'town' => $ilce,

            'postcode' => $postakodu,
            'country_id' => 215,
            'zone_id' => ''

        );


        $order_data = array(
            'id' => "",
            'firstname' => $first_name,
            'lastname' => $lastname,
            'tckimlikno' => '',
            'customer_group_id' => $this->config->get('config_customer_group_id'),
            'email' => $email,
            'telephone' => $phone,
            'fax' => '',
            'custom_field' => '',
            'newsletter' => '',
            'password' => '123456',
            'status' => 1,
            'approved' => 1,
            'safe' => 1,
            'address' => $address_data,
            'order_type' => 'cs',
            'plength' => '',
            'poption' => '',


        );


        $order_data['order_id'] = $order['orderId'];
        $order_data['invoice_prefix'] = '';
        $order_data['payment_company_id'] = $vergiDairesi;
        $order_data['payment_tax_id'] = $vergiNo;
        $order_data['invoice_no'] = 0;
        $order_data['store_id'] = $this->config->get('config_store_id');
        $order_data['store_name'] = $this->config->get('config_name');

        if ($order_data['store_id']) {
            $order_data['store_url'] = $this->config->get('config_url');
        } else {
            if ($this->request->server['HTTPS']) {
                $order_data['store_url'] = HTTP_SERVER;
            } else {
                $order_data['store_url'] = HTTP_SERVER;
            }
        }


        $order_data['comment'] = '';

        $order_data['language_id'] = $this->config->get('config_language_id');
        $order_data['currency_id'] = 1;
        $order_data['currency_code'] = $this->session->data['currency'];
        $order_data['currency_value'] = 1;//$this->currency->getValue($this->session->data['currency']);
        $order_data['ip'] = $this->request->server['REMOTE_ADDR'];

        if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
            $order_data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
            $order_data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
        } else {
            $order_data['forwarded_ip'] = '';
        }

        if (isset($this->request->server['HTTP_USER_AGENT'])) {
            $order_data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
        } else {
            $order_data['user_agent'] = '';
        }

        if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
            $order_data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
        } else {
            $order_data['accept_language'] = '';
        }

        $shipment_info = $this->getShipmenInfo($order);


        $order_data['shipping_info'] = $shipment_info;


        $shipping_address = array(
            'shipping_firstname' => $first_name,
            'shipping_lastname' => $lastname,
            'shipping_company' => '',
            'shipping_address_1' => $adres,
            'shipping_address_2' => '',
            'shipping_city' => $ilce,
            'shipping_town' => $ilce,
            'shipping_postcode' => $postakodu,
            'shipping_country_id' => 215,
            'shipping_zone_id' => '',
            'shipping_method' => $order['cargoCompany'],
            'shipping_zone' => $sehir,
            'shipping_country' => 'Türkiye',
            'shipping_address_format' => '{firstname} {lastname}
{company}
{address_1}
{address_2}
{postcode}, {city} - {zone} / {country}',
            'shipping_custom_field	' => '',

            'shipping_custom_field' => $shipment_info,
            'shipping_code' => $shipment_info['shipment_method'],


        );

        $shipment_method = 'Ciceksepeti';
        $shipment_method .= '- Platform Referans No:' . $order_data['order_id'];
        if ($shipment_info['campaign_number']) $shipment_method .= ' - Kampanya No:' . $shipment_info['campaign_number'];
        if ($shipment_info['shipping_code']) $shipment_method .= ' - Kargo No:' . $shipment_info['shipping_code'];
        if ($shipment_info['shipment_method']) $shipment_method .= ' - Kargo Metodu:' . $shipment_info['shipment_method'];
        $shipping_address['shipping_method'] = $shipment_method;

        $payment_address = array(

            'payment_firstname' => $first_name,
            'payment_lastname' => '',
            'payment_company' => '',
            'payment_address_1' => $adres,
            'payment_address_2' => '',
            'payment_city' => $sehir,
            'payment_town' => $ilce,
            'payment_postcode' => $postakodu,
            'payment_country_id' => 215,
            'payment_country' => 'Türkiye',
            'payment_zone_id' => '',
            'payment_code' => 'Çiçeksepeti',
            'payment_zone' => $sehir,
            'payment_address_format' => '{firstname} {lastname}
{company}
{address_1}
{address_2}
{postcode}, {city} - {zone} / {country}',
            'payment_custom_field' => array('Vergi Dairesi' => $vergiDairesi, 'Vergi/TC Kimlik' => $vergiNo)

        );

        $payment_method = 'Çiçeksepeti';
        if ($vergiDairesi) $payment_method .= '-Vergi Dairesi' . $vergiDairesi;
        if ($vergiNo) $payment_method .= '-Vergi/TC Kimlik:' . $vergiNo;
        $payment_address['payment_method'] = $payment_method;


        $date = str_replace('/', '-', $order['orderCreateDate']);

        $date = date_create($date);

        $order_data['order_date'] = date('Y-m-d H:i:s');

        $order_data = array_merge($order_data, $payment_address);
        $order_data = array_merge($order_data, $shipping_address);
        // $order_data['payment_address']=$payment_address;
        // $order_data['shipping_address']=$shipping_address;

        $order_data['affiliate_id'] = '';
        $order_data['commission'] = '';
        $order_data['marketing_id'] = '';
        $order_data['tracking'] = '';
        $order_data['custom_field'] = array('fatura_bilgileri' => array('vergi_dairesi' => $vergiDairesi, 'vergi_yada_kimlik_no' => $vergiNo), 'kargo_bilgileri' => $shipment_info);

        $order_data['payment_info'] = array('vergi_dairesi' => $vergiDairesi, 'vergi_yada_kimlik_no' => $vergiNo);

        $order_data['order_status_id'] = $order['orderProductStatus'];

        $order_data['products'] = array();

        $order_data['total'] = 0;

        $total = 0;
        $tax = 0;
        $subtotal = 0;


        $kdv = $order['tax'];


        $totals = array();

        $tax += ((float)$this->model_entegrasyon_order->priceFormat(($order['totalPrice'] / ((100 + $kdv) / 100) * ($kdv / 100))));
        $subtotal += (float)$this->model_entegrasyon_order->priceFormat($order['totalPrice'] / ((100 + $kdv) / 100));


        $total += (float)$order['totalPrice'];


        $order_data['totals'] = $totals;

        $order_data['products'][] = $this->getProductInfo($order);

        $order_data['total'] = $order['invoicePrice'];

        $order_data['invoice_link'] = '';


        $totals = array();
        if (!$this->config->get('easy_setting_order_price_with_tax')) {

            $totals[] = array(

                'code' => 'tax',
                'title' => 'KDV',
                'value' => $tax,
                'sort_order' => 5
            );

        }
        $totals[] = array(

            'code' => 'sub_total',
            'title' => 'Ara Toplam (KDV HARİÇ)',
            'value' => $subtotal,
            'sort_order' => 1
        );

        /*     $totals[] = array(

                 'code' => 'sub_total',
                 'title' => 'Kargo Ücreti',
                 'value' => isset($order['cargoPrice'])?$order['cargoPrice']:0,
                 'sort_order' => 3
             );*/

        $totals[] = array(

            'code' => 'total',
            'title' => 'Toplam',
            'value' => $order['invoicePrice'],
            'sort_order' => 9
        );

        $order_data['totals'] = $totals;
        $custom_data = array();
        return $order_data;


    }


    private function getProductInfo($product)
    {


        $kdv = $product['tax'];

        $price = (float)$this->model_entegrasyon_order->priceFormat($product['totalPrice'] - ($product['totalPrice'] / ((100 + $kdv) / 100) * ($kdv / 100)), 2);
        $tax = (float)$this->model_entegrasyon_order->priceFormat(($product['totalPrice'] / ((100 + $kdv) / 100) * ($kdv / 100)), 2);


        $product_data = array(
            'item_id' => '',
            'product_id' => 0,
            'variant_id' => 0,
            'name' => $product['name'],
            //  'model' => $product_info?isset($product_info['product']['model'])?$product_info['product']['model']:$product['productCode']:'',
            'model' => $product['barcode'],
            'barcode' => $product['barcode'],
            'market_product_id' => $product['productCode'],

            'option' => $this->getOrderAtrributes($product),
            'download' => '',
            'quantity' => $product['quantity'],
            'subtract' => '',
            'shipment_info' => '',
            'list_price' => $product['price'],
            'price' => $this->model_entegrasyon_order->priceFormat($product['price']),
            'total' => $this->model_entegrasyon_order->priceFormat($product['price'] * $product['quantity']),
            'tax' => $this->model_entegrasyon_order->priceFormat($tax),
            'tax_range' => $product['tax'],
            'totaltax' => (float)($tax * $product['quantity']),
            'discount' => (float)$product['discount'],
            'reward' => ''

        );


        return $product_data;

    }

    private function getOrderAtrributes($attributes)
    {

        $options = array();
        foreach ($attributes['orderItemTextListModel'] as $attribute) {
            $options[$attribute['text']] = $attribute['value'];

        }

        return $options;


    }


    private function getShipmenInfo($order)
    {
        if ($order['cargoNumber']) {


            return array(

                'shipping_code' => $order['cargoNumber'],
                'campaign_number' => $order['cargoNumber'],
                'shipment_method' => $order['cargoCompany']
            );
        } else {

            return array(

                //'shipping_code' => $order['cargoNumber'],
                'shipping_code' => $order['partialNumber'],
                // 'campaign_number' => $order['shipmentTrackingUrl'],
                'campaign_number' => $order['partialNumber'],
                'shipment_method' => $order['cargoCompany']
            );
        }


    }

    public function updateStock($order)
    {


        $isVarianter = false;
        $status = false;
        $message = '';


        foreach ($order['products'] as $orderedproduct) {


            // print_r($orderedproduct);
            $quantity = $orderedproduct['quantity'];
            $size = 1;//$orderedproduct['option']['product_size'];

            //echo $size;


            $marketPlaceProductInfo = $this->getProductFromMarketPlace($orderedproduct['model']);


            if ($marketPlaceProductInfo['result']['totalElements']) {


                $model = $marketPlaceProductInfo['result']['content'][0]['productMainId'];

                if ($size != 'Tek Ebat') {
                    $isVarianter = true;
                    $modelLenght = strlen($orderedproduct['model']);

                    $model = $orderedproduct['model'];

                    $product_info = $this->model_entegrasyon_order->getProductByOrderModel($model, 'cs');


                    //Product Founded
                    if ($product_info) {
                        $product_id = $product_info['product_id'];

                        $matched_option_info = $this->model_entegrasyon_order->getOptionValueForUpdateStock($size);


                        if ($matched_option_info) {

                            $product_option_stock = $this->model_entegrasyon_order->updateProductOptionStock($matched_option_info['oc_option_value_id'], $quantity, $product_id);

                            //$product_option_stock=true;
                            if ($product_option_stock) {

                                $status = true;
                                $message = 'Ürün Varyantı Başarıyla Güncellendi';

                            } else {

                                $message = 'Ürün Varyantı Güncellenemedi!';
                            }

                        } else {

                            $message = 'Ürün Seçenek değeri eşleştirilmemiş!';

                        }


                    } else {

                        $message = 'Ürün bulunamadı!';
                    }


                } else {

                    //echo 'Ürün Seçenekli Değil!';

                    $product_info = $this->model_entegrasyon_order->getProductByOrderModel($model, 'cs');


                    if ($product_info) {

                        $product_info['quantity'] -= (int)$orderedproduct['quantity'];
                        //  echo 'Şimdiki Stok'.$product_info['quantity'].'<br>';

                        $this->model_entegrasyon_order->updateStock($product_info);

                        $message = 'Seçeneksiz olan ürününüz bulundu ve stoğu güncellendi!';
                        $status = true;

                    } else {

                        $message = 'Seçeneksiz olan ürününüz bulunamadı!';
                    }


                }


            }

            //  $product_size=$order[];


        }

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

    }


    private function change_status($order_id)
    {


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://apis.ciceksepeti.com/api/v1/Order/readyforcargowithcsintegration',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'PUT',
            CURLOPT_POSTFIELDS => '{
  "orderItemsGroup": [
    {
      "orderItemIds": [
       '.$order_id.'
      ]
    }
  ]

}
',
            CURLOPT_HTTPHEADER => array(
                'x-api-key: '.$this->api_info['apiKey'].'',
                'Content-Type: application/json',
                'Cookie: __cf_bm=.4Ga.5MYBbJFkTIJtCxDf2viVuoVOJDa77_j3nyu9mQ-1724164377-1.0.1.1-cNAeslwvuHLFdh7yAzIKpjSCH06vCdl1h3tXAYbL7svzGkdm4YoizOdeEcWhyBCJC1U1ypX6AR0TVjntOHvh2g'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;


    }

}





