<?php
class ControllerToolByexpressCron extends Controller{

    use Byexpress;

    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
        );


        echo "It Worked! <br>";

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

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


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

        $follow_link = 'https://www.byexpresskargo.com.tr/kargotakip/';

        $results = $this->db->query("SELECT * FROM ps_order_byexpresskargo WHERE kargo_sonuc IN (0,1,2) ORDER BY RAND() LIMIT 100 ")->rows;


        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->lastStatus($result['kargo_barcode']);


                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_byexpresskargo_steps WHERE byexpresskargo_id = '". $result['byexpresskargo_id'] ."' AND action_station = '". $this->db->escape($step['hareket_sube']) ."' AND action_description = '". $this->db->escape($step['hareket_aciklama']) ."' ")->row;

                        if(!$step_query){
                            $this->db->query("INSERT INTO ps_order_byexpresskargo_steps SET 
                                byexpresskargo_id = '". $result['byexpresskargo_id'] ."', 
                                action_station = '". $this->db->escape($step['hareket_sube']) ."', 
                                action_description = '". $this->db->escape($step['hareket_aciklama']) ."' ");

                            if($step['hareket_aciklama'] == 'Kargo Çıkış Şubede'){

                                $this->db->query("UPDATE ps_order_byexpresskargo SET
                                    kargo_sonuc = '1',
                                    kargo_url = '". $this->db->escape($follow_link . $result['kargo_barcode']) ."',
                                    last_status = '". $this->db->escape($step['hareket_aciklama']) ."'
                                    WHERE byexpresskargo_id = '". $result['byexpresskargo_id'] ."' ");
                                $this->addHistory($order, $step, true, $follow_link . $result['kargo_barcode']);

                            }
                            else if($step['hareket_aciklama'] == 'Kargo Kuryede'){
                                $this->db->query("UPDATE ps_order_byexpresskargo SET
                                    kargo_sonuc = '2',
                                    last_status = '". $this->db->escape($step['hareket_aciklama']) ."'
                                    WHERE byexpresskargo_id = '". $result['byexpresskargo_id'] ."' ");
                                $this->addHistory($order, $step, true, $follow_link . $result['kargo_barcode']);
                            }
                            else if($step['hareket_aciklama'] == 'Kargo Iade Süreci Başlatıldı' AND $shipping_return){
                                $this->db->query("UPDATE ps_order_byexpresskargo SET
                                    kargo_sonuc = '4',
                                    last_status = '". $this->db->escape($step['hareket_aciklama']) ."'
                                    WHERE byexpresskargo_id = '". $result['byexpresskargo_id'] ."' ");
                                $this->addHistory($order, $step, true);
                            }
                            else if($step['hareket_aciklama'] == 'Kargo Teslim Edildi'){

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


                            }

                        }


                    }


                }

            }

        }



    }

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

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

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

        $order_status_id = $order_info['order_status_id'];

        if($order_status_id == 7){
            return false;
        }

        $comment = '';
        if($event['hareket_aciklama'] == 'Kargo Çıkış Şubede'){
            $comment = sprintf($this->language->get('text_kargo_yuklendi'), $order_info['firstname'], $order_info['lastname'], $order_info['order_id'], $folow_link);
            $order_status_id = 17;
            $mesaj = "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", ". $order_info['order_id'] ." no'lu siparişiniz Kargo'ya teslim edilmiştir.  ". $folow_link;
            if($notify){
                $this->sendSms($order_info, $mesaj);
            }

        }else if($event['hareket_aciklama'] == 'Kargo Kuryede'){
            $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 (".$folow_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 (".$folow_link.")";
            if($notify){
                $this->sendSms($order_info, $mesaj);
            }
        }
        else if($event['hareket_aciklama'] == 'Kargo Iade Süreci Başlatıldı'){
            $comment .= "Kargo alıcı tarafından kabul edilmedi. Teslim alinamayan Kargo geri gönderildi.";
            $order_status_id = 21;
        }else if($event['hareket_aciklama'] == 'Kargo 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 orderCarcoFind()
    {

        //https://www.deercase.com/index.php?route=tool/yurtici_cron/orderCarcoFind&ssHkey=1

        if(!isset($this->request->get['ssHkey'])){
            die();
        }


        $this->load->model('checkout/order');
        $orders = $this->db->query("SELECT order_id FROM ps_order WHERE order_id BETWEEN 191168 AND 191409 AND order_status_id > 0 ")->rows;

        $count = 0;
        foreach ($orders as $order){

            $order_info = $this->model_checkout_order->getOrder($order['order_id']);
            $sonuc = $this->YURTICI_TAKIPLINKI($order_info);
            if($sonuc['link']){
                $count++;
                echo 'OrderId: ' . $order['order_id'] . ' => ' . $sonuc['link'] . '<br>';
            }
        }

        echo 'Toplam: ' . $count;

    }

    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();

    }

    public function getZones()
    {

        die();

        //https://www.deercase.com/index.php?route=tool/byexpress_cron/getZones
        $url = 'https://api.byexpresskargo.net/AdresBilgi/IlceListesi';

        $send_data = array(
            'SozlesmeNumarasi' => (int)$this->config->get('byexpresskargo_contrat_no'),
            'KullaniciAdi' => $this->config->get('byexpresskargo_username'),
            'Sifre' => $this->config->get('byexpresskargo_password'),
        );

        $result = json_decode($this->callAPI($url, json_encode($send_data, JSON_UNESCAPED_UNICODE)), true);

        $count = 0;
        foreach ($result['value']['ilceler'] as $zone){

            $find_zone = $this->db->query("SELECT * FROM `ps_zone` WHERE `country_id` = 215 AND name = '". $this->db->escape($zone['il']) ."' ")->row;
            if($find_zone){
                $find_disc = $this->db->query("SELECT * FROM `ps_district` WHERE zone_id = '". $find_zone['zone_id'] ."' AND district_name LIKE '%".$this->db->escape($zone['adi']) ."%' ")->row;
                if(!$find_disc){
                    $count++;
                    //var_dump($zone, $find_zone); die();
                    $this->db->query("INSERT INTO ps_district SET zone_id = '". $find_zone['zone_id'] ."', district_name = '".$this->db->escape($zone['adi']) ."' ");
                    echo "INSERT INTO ps_district SET zone_id = '". $find_zone['zone_id'] ."' , district_name = '".$this->db->escape($zone['adi']) ."' <br>"; ;
                }
            }
        }

        echo $count;

        
    }

}