<?php
class ControllerToolYkCron2 extends Controller{

    use MngArasYurticiTrait;

    public function index(){

        set_time_limit(-1);

        $shipping_result_satatus = array(
            '0' => 0, // Kargo kaydı açıldı
            '1' => 1, // Kargo Yüklendi - Sorun Yok
            '2' => 2, // Kargo Yüklendi ----- Kuryede/zimmetlendi (dağıtıma çıktı)
            '3' => 3, // Teslim Edildi ----- Sorun Yok
            '4' => 4, // Borçlandırma  --- İade
        );

        //operationMessage => Kargo teslim edilmiştir.

        echo "It Worked!";

        $kargo_sonuc = 0;
        if(isset($this->request->get['kargo_sonuc'])){
            $kargo_sonuc = $this->request->get['kargo_sonuc'];
        }

        $log = new Log("YurticiKargoLogs_".$kargo_sonuc.".txt");
        $log->write("Dosya çalıştı!");


        $this->load->model('checkout/order');
        $this->load->model('extension/module/logo');

        //$results = $this->db->query("SELECT * FROM ps_order_yurticikargo WHERE kargo_sonuc = '". (int)$kargo_sonuc ."' ORDER BY RAND() LIMIT 70 ")->rows;
        $results = $this->db->query("SELECT * FROM ps_order_yurticikargo WHERE order_id BETWEEN 191168 AND 191409 AND kargo_sonuc = 0 ")->rows;


       // var_dump($results); die();

        foreach ($results as $result){
            $order = $this->model_checkout_order->getOrder($result['order_id']);

            if($order AND !in_array($order['order_status_id'], array(11,75,2))){
                $sonuc = $this->YURTICI_TAKIPLINKI($order);  //var_dump($sonuc['shipping_steps']); die();

                if($sonuc['shipping_steps'] AND @count($sonuc['shipping_steps']) > 1){
                    $shipping_return = '';
                    foreach ($sonuc['shipping_steps'] as $step){

                        $step_query = $this->db->query("SELECT * FROM ps_order_yurticikargo_steps WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' AND event_name = '". $this->db->escape($step->eventName) ."' AND reason_name = '". $this->db->escape($step->reasonName) ."' ")->row;

                        if(!$step_query){
                            $this->db->query("INSERT INTO ps_order_yurticikargo_steps SET 
                                yurticikargo_id = '". $result['yurticikargo_id'] ."', 
                                event_name = '". $this->db->escape($step->eventName) ."', 
                                reason_name = '". $this->db->escape($step->reasonName) ."' ");

                            if($step->eventName == 'Borçlandırma' AND $step->reasonName != 'Varış Merkezi Hatası'){
                                $shipping_return = 'Borçlandırma';
                                $this->db->query("UPDATE ps_order_yurticikargo SET return_status = '1'  WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' ");
                            }

                            if($step->eventName == 'Kargo Yüklendi' AND $step->reasonName == 'Sorun Yok'){

                                $this->db->query("UPDATE ps_order_yurticikargo SET
                                    kargo_sonuc = '1',
                                    kargo_url = '". $this->db->escape($sonuc['link']) ."',
                                    last_status = '". $this->db->escape($step->eventName) ."'
                                    WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' ");
                                $this->addHistory($order, $sonuc, $step->eventName, true);
                                $this->model_extension_module_logo->orderSave($result['order_id']);
                            }
                            else if($step->reasonName == 'Kuryede/zimmetlendi (dağıtıma çıktı)'){
                                $this->db->query("UPDATE ps_order_yurticikargo SET
                                    kargo_sonuc = '2',
                                    last_status = '". $this->db->escape($step->reasonName) ."'
                                    WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' ");
                                $this->addHistory($order, $sonuc, $step->reasonName, true);
                            }
                            else if($step->eventName == 'Teslim Edilmedi / Bekletiliyor Şubede' AND $step->reasonId == 'AAB'){
                                $this->db->query("UPDATE ps_order_yurticikargo SET
                                    kargo_sonuc = '2',
                                    last_status = '". $this->db->escape($step->reasonName) ."'
                                    WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' ");
                                $this->addHistory($order, $sonuc, $step->eventName, true, $step->unitName);
                            }
                            else if($step->eventName == 'Borçlandırma' AND $shipping_return){
                                $this->db->query("UPDATE ps_order_yurticikargo SET
                                    kargo_sonuc = '4',
                                    last_status = '". $this->db->escape($step->reasonName) ."'
                                    WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' ");
                                $this->addHistory($order, $sonuc, $step->eventName, true);
                            }
                            else if($step->eventName == 'Teslim Edildi' AND $step->reasonName == 'Sorun Yok'){

                                $return_info = $this->db->query("SELECT * FROM ps_order_yurticikargo WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' ")->row;
                                if(!$return_info['return_status']){
                                    $this->db->query("UPDATE ps_order_yurticikargo SET
                                    kargo_sonuc = '3',
                                    last_status = '". $this->db->escape($step->eventName) ."'
                                    WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' ");
                                    $this->addHistory($order, $sonuc, $step->eventName, true);
                                }


                            }

                        }


                    }


                }else if($sonuc['shipping_steps'] AND @count($sonuc['shipping_steps']) == 1){
                    /*
                                        $step_query = $this->db->query("SELECT * FROM ps_order_yurticikargo_steps WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' AND event_name = '". $this->db->escape($sonuc['shipping_steps']->eventName) ."' AND reason_name = '". $this->db->escape($sonuc['shipping_steps']->reasonName) ."' ")->row;

                                        if(!$step_query){
                                            if($sonuc['shipping_steps']->eventName == 'Kargo Yüklendi' AND $sonuc['shipping_steps']->reasonName == 'Sorun Yok'){
                                                $this->db->query("UPDATE ps_order_yurticikargo SET
                                                        kargo_sonuc = '1',
                                                        kargo_url = '". $this->db->escape($sonuc['link']) ."',
                                                        last_status = '". $this->db->escape($sonuc['shipping_steps']->eventName) ."'
                                                        WHERE yurticikargo_id = '". $result['yurticikargo_id'] ."' ");
                                                $this->addHistory($order, $sonuc, $sonuc['shipping_steps']->eventName, true);
                                                $this->model_extension_module_logo->orderSave($result['order_id']);
                                                //var_dump($result['order_id']);
                                            }
                                        } **/




                }

            }

        }



    }

    private function addHistory($order_info, $sonuc, $event, $notify, $unitName = ''){

        $this->load->language('tool/yurtici_cron');

        $this->load->model('checkout/order');

        $order_status_id = $order_info['order_status_id'];

        $comment = '';
        if($event == 'Kargo Yüklendi'){
            $comment = sprintf($this->language->get('text_kargo_yuklendi'), $order_info['firstname'], $order_info['lastname'], $order_info['order_id'], $sonuc['link']);
            $order_status_id = 17;
            $mesaj = "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", ". $order_info['order_id'] ." no'lu siparişiniz Yurtiçi Kargo'ya teslim edilmiştir.  ". $sonuc['link'];
            if($notify){
                $this->sendSms($order_info, $mesaj);
            }

        }else if($event == 'Kuryede/zimmetlendi (dağıtıma çıktı)'){
            $comment .= "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", ". $order_info['order_id'] . " no'lu siparişiniz gün içerisinde adresinize teslim edilmek üzere dağıtıma çıkarılmıştır. Takip Linki (".$sonuc['link'].")";
            $order_status_id = 19;
            $mesaj = "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", ". $order_info['order_id'] . " no'lu siparişiniz gün içerisinde adresinize teslim edilmek üzere dağıtıma çıkarılmıştır. Takip Linki (".$sonuc['link'].")";
            if($notify){
                $this->sendSms($order_info, $mesaj);
            }
        }else if($event == 'Teslim Edilmedi / Bekletiliyor Şubede'){
            $comment .= "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", Ürün teslimatınız başarısız olduğu için Yurtiçi Kargo şubesinde bekletilmektedir. Kargonuzu ".$unitName." Şubesinden teslim alabilirsiniz. ";
            $order_status_id = 18;
            $mesaj = "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", Ürün teslimatınız başarısız olduğu için Yurtiçi Kargo şubesinde bekletilmektedir. Kargonuzu ".$unitName." Şubesinden teslim alabilirsiniz. ";
            if($notify){
                $this->sendSms($order_info, $mesaj);
            }
        }else if($event == 'Borçlandırma'){
            $comment .= "Kargo alıcı tarafından kabul edilmedi. Teslim alinamayan Kargo geri gönderildi.";
            $order_status_id = 21;
        }else if($event == 'Teslim Edildi'){
            $comment = sprintf($this->language->get('text_kargo_teslim_edildi'), $order_info['firstname'], $order_info['lastname'], $order_info['order_id']);
            $order_status_id = 5;
        }

        if ($order_info) {
            $this->model_checkout_order->addOrderHistory($order_info['order_id'], $order_status_id, $comment, $notify, 1);
            echo $order_info['order_id'] . " Başarılı! <br>";
        }

    }

    private function sendSms($order_info, $mesaj)
    {

        $log = new Log("YurticiSendSmsLog.txt");
        $log->write($mesaj);

        #NetGSM 2020/06/08 BILAL
        if($this->config->get('netgsm_status')) {
            $this->load->model('setting/setting');
            $netgsm_ayarlari = $this->model_setting_setting->getSetting('netgsm');

            if($netgsm_ayarlari['netgsm_status'] == 1){
                $netgsmsms = new Netgsmsms($netgsm_ayarlari['netgsm_user'],$netgsm_ayarlari['netgsm_pass'],$netgsm_ayarlari['netgsm_input_smstitle'],isset($netgsm_ayarlari['netgsm_turkishChar']));
                $smsgonder = $netgsmsms->sendSMS($order_info['telephone'],$mesaj);
            }
        }

        #NetGSM 2020/06/08 BILAL

    }

    public function testsms()
    {
        $this->sendSms(array('telephone'=> '5453773801'), "deneme mesajı");

    }

    public function getOrderShippingInfo(){

        if(isset($this->request->get['order_id'])){
            $order_id = $this->request->get['order_id'];
        }else{
            $order_id = 0;
        }

        if($order_id){

            $this->load->model('checkout/order');
            $order_info = $this->model_checkout_order->getOrder($order_id);

            $shipping_info = $this->db->query("SELECT * FROM ps_order_yurticikargo WHERE order_id = '". (int)$order_id ."'  ")->row;

            $sonuc = $this->YURTICI_TAKIPLINKI($order_info);

            if(isset($sonuc['operationMessage'])){
                if($sonuc['operationMessage'] == "Kargo teslim edilmiştir."){
                    $this->db->query("UPDATE ps_order_yurticikargo SET kargo_sonuc = '2' WHERE yurticikargo_id = '". $shipping_info['yurticikargo_id'] ."' ");
                    $this->model_checkout_order->addOrderHistory($order_id, 5, "Kargo teslim edilmiştir.", 0, 1);
                    echo $sonuc['operationMessage'] ."<br>";
                }else if($sonuc['operationMessage'] == "Kargo Teslimattadır."){
                    $this->addHistory($order_info, $sonuc);
                    $this->db->query("UPDATE ps_order_yurticikargo SET kargo_sonuc = '1', kargo_url = '". $this->db->escape($sonuc['link']) ."' WHERE yurticikargo_id = '". $shipping_info['yurticikargo_id'] ."' ");
                }else{
                    $this->db->query("UPDATE ps_order_yurticikargo SET last_status = '". $this->db->escape($sonuc['operationMessage']) ."' WHERE yurticikargo_id = '". $shipping_info['yurticikargo_id'] ."' ");
                }
            }else{
                echo "Herhangi bir sonuç bulunamadı. <br>";
            }


        }else{
            echo "Sipariş no yanlış! <br>";
        }


    }

    public function getShippingReport()
    {

        //60840

        //https://www.deercase.com/index.php?route=tool/yurtici_cron/getShippingReport


        if(isset($this->request->get['order_id'])){
            $order_id = $this->request->get['order_id'];
        }else{
            $order_id = 0;
        }

        $sonuc = 0;
        if($order_id){
            $this->load->model('checkout/order');

            $order_info = $this->model_checkout_order->getOrder($order_id);
            //$order_info['kargo_barcode'] = '100060840';

            // var_dump($order_info); die();

            $sonuc = $this->YURTICI_TAKIPLINKI($order_info);
            var_dump($sonuc); die();
            foreach ($sonuc['shipping_steps'] as $step){

                echo $step->eventName . '    ' . $step->reasonName. '<br>';
            }

        }

        //var_dump($sonuc); die();
    }

    public function yurticiGidenGelenSorgulama()
    {

        $results = $this->db->query("SELECT * FROM ps_return_yurticikargo WHERE status = 1 ")->rows;

        $this->load->model('checkout/order');

        foreach ($results as $result){
            $order_info = $this->model_checkout_order->getOrder($result['order_id']);

            $response = $this->YURTICI_GIDEN_GELEN($order_info);

            if($response){

                foreach ($response['invDocFieldVOArray'] as $res_row){

                    $rew_row_query = $this->db->query("SELECT * FROM ps_return_yurticikargo_steps WHERE return_yurticikargo_id = '". $result['return_yurticikargo_id'] ."' AND event_name = '". $this->db->escape($res_row['name']) ."' ")->row;
                    if(!$rew_row_query){
                        $this->db->query("INSERT INTO ps_return_yurticikargo_steps SET return_yurticikargo_id = '". $result['return_yurticikargo_id'] ."', event_name = '". $this->db->escape($res_row['name']) ."'  ");

                        if($res_row['name'] == "İade Onay Kodu"){
                            $this->load->model('checkout/order');
                            $order_status_id = 20; // İade sürecinde
                            $iade_takip_link = '<a target="_blank" href="'. $response['takip_linki'] .'">' . $response['takip_linki'] . '</a>';
                            $comment = sprintf("%d nolu iade kodunuz işleme alınmıştır. İade Takip Linki:" . $iade_takip_link ,$result['order_id']);
                            $this->model_checkout_order->addOrderHistory($order_info['order_id'],$order_status_id,$comment ,false);
                        }

                    }



                }


            }

        }


    }

    public function shippingCancelManuel()
    {

        //https://www.deercase.com/index.php?route=tool/yurtici_cron/shippingCancelManuel

        $order_id = 97468;

        //$results = $this->db->query("SELECT * FROM ps_order_yurticikargo WHERE order_id = '". $order_id ."' ")->row;

        $results['sender_type'] = 1;
        $results['kargo_barcode'] = '100097764';

        if($results){

            if($results['sender_type'] == 3){
                $wsUserName  = $this->config->get('yurticikargo_gonderici_odemeli_tahsilatli_teslimat_kullanici_adi');
                $wsPassword = $this->config->get('yurticikargo_gonderici_odemeli_tahsilatli_teslimat_sifre');
            }else{
                $wsUserName  = $this->config->get('yurticikargo_gonderici_odemeli_kullanici_adi');
                $wsPassword = $this->config->get('yurticikargo_gonderici_odemeli_sifre');
            }


            $wsLanguage = 'TR';
            $talep_no = $results['kargo_barcode'];


            $serviceurl = 'http://webservices.yurticikargo.com:8080/KOPSWebServices/ShippingOrderDispatcherServices?wsdl';
            $client 	= new SoapClient($serviceurl);
            $send		= array('wsUserName' => $wsUserName, 'wsPassword' => $wsPassword, 'userLanguage' => $wsLanguage, 'cargoKeys' => $talep_no);

            $response = $client->cancelShipment($send);

            $this->db->query("DELETE FROM ps_order_yurticikargo WHERE order_id = '". $order_id ."' ");


            var_dump($response); die();

        }



    }

    public function shippingCancel()
    {

        //https://www.deercase.com/index.php?route=tool/yurtici_cron/shippingCancel

        /*
                $wsUserName  = $this->config->get('yurticikargo_gonderici_odemeli_kullanici_adi');
                $wsPassword = $this->config->get('yurticikargo_gonderici_odemeli_sifre');
                $wsLanguage = 'TR';
                $talep_no = '100049042';



                $serviceurl = 'http://webservices.yurticikargo.com:8080/KOPSWebServices/ShippingOrderDispatcherServices?wsdl';
                $client 	= new SoapClient($serviceurl);
                $send		= array('wsUserName' => $wsUserName, 'wsPassword' => $wsPassword, 'wsLanguage' => $wsLanguage, 'keys' => array($talep_no),'keyType' => '0', 'addHistoricalData' => true,'onlyTracking' => false);

                $response = $client->queryShipment($send);
                $responseArr = $response->ShippingDeliveryVO->shippingDeliveryDetailVO;

                //var_dump($responseArr); die();

                foreach ($responseArr->shippingDeliveryItemDetailVO->invDocCargoVOArray as $item){
                    var_dump($item);
                    var_dump("----------------<br>");
                } */

        $order_id = 97468;

        $results = $this->db->query("SELECT * FROM ps_order_yurticikargo WHERE order_id = '". $order_id ."' ")->row;

        if($results){

            if($results['sender_type'] == 3){
                $wsUserName  = $this->config->get('yurticikargo_gonderici_odemeli_tahsilatli_teslimat_kullanici_adi');
                $wsPassword = $this->config->get('yurticikargo_gonderici_odemeli_tahsilatli_teslimat_sifre');
            }else{
                $wsUserName  = $this->config->get('yurticikargo_gonderici_odemeli_kullanici_adi');
                $wsPassword = $this->config->get('yurticikargo_gonderici_odemeli_sifre');
            }


            $wsLanguage = 'TR';
            $talep_no = $results['kargo_barcode'];


            $serviceurl = 'http://webservices.yurticikargo.com:8080/KOPSWebServices/ShippingOrderDispatcherServices?wsdl';
            $client 	= new SoapClient($serviceurl);
            $send		= array('wsUserName' => $wsUserName, 'wsPassword' => $wsPassword, 'userLanguage' => $wsLanguage, 'cargoKeys' => $talep_no);

            $response = $client->cancelShipment($send);

            $this->db->query("DELETE FROM ps_order_yurticikargo WHERE order_id = '". $order_id ."' ");


            var_dump($response); die();

        }



    }

    public function kargoMerge()
    {

        $results = $this->db->query("SELECT order_id FROM ps_order_yurticikargo LIMIT 10 ")->rows;

        foreach ($results as $result){
            $order = $this->db->query("SELECT * FROM ps_order WHERE order_id = '". $result['order_id'] ."' ")->row;
            if($order){
                if($order['payment_code'] == 'cod'){
                    $sender_type = 3;
                }else if($order['payment_code'] == 'iyzico_checkout_form'){
                    $sender_type = 1;
                }

                $this->db->query("UPDATE ps_order_yurticikargo SET sender_type = '". $sender_type ."' WHERE order_id = '". $result['order_id'] ."' ");

            }

        }

    }

    public function createReturnShippingCode()
    {

        //https://www.deercase.com/index.php?route=tool/yurtici_cron/createReturnShippingCode

        $this->load->model('checkout/order');

        $order_info = $this->model_checkout_order->getOrder('110827');

        $return = $this->YURTICI_RETURN_SHIPPING_CODE($order_info);
        var_dump($return); die();

    }

    public function returnShippingCancel()
    {

        //https://www.deercase.com/index.php?route=tool/yurtici_cron/returnShippingCancel&order_id=110827
        if(isset($this->request->get['order_id'])){
            $order_id = (int)$this->request->get['order_id'];
        }else{
            $order_id = 0;
        }

        $this->load->model('checkout/order');
        $order_info = $this->model_checkout_order->getOrder($order_id);
        if($order_info){
            $this->YURTICI_CANCEL_RETURN_SHIPPING_CODE($order_info);
        }




    }

    public function saveOrderManuel()
    {

        //https://www.deercase.com/index.php?route=tool/yurtici_cron/saveOrderManuel

        $this->load->model('checkout/order');

        $order_info = $this->model_checkout_order->getOrder('110827');


        $return = $this->YURTICI_($order_info);
        var_dump($return); die();

    }

}