<?php
class ControllerToolMngkargoCron extends Controller{

    use MngTrait;

    public function index(){

        //https://www.deercase.com/index.php?route=tool/mngkargo_cron&order_id=1435406


        set_time_limit(-1);

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

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

        if(!$order_id){
            $results = $this->db->query("SELECT mngkargo_id,order_id,kargo_barcode FROM ps_order_mngkargo WHERE kargo_sonuc IN(0) AND kargo_tarih > '2024-04-01' ORDER BY order_id DESC ")->rows;
        }else{
            $results = $this->db->query("SELECT mngkargo_id,order_id,kargo_barcode FROM ps_order_mngkargo WHERE order_id = '". (int)$order_id ."' ")->rows;
            echo "<br/>Bilgilendirme; Siparişe ait durum kaydı gözükmüyorsa, MNG Kargo servisinde bu siparişe ait güncelleme yapılacak yeni bir hareket / sipariş durum bilgisi verisi yok demektir.<br/><br/>";
        }

        foreach ($results as $key => $result){

            if($key >= 300){
                die();
            }
			
            $order_info       = $this->model_checkout_order->getOrder($result['order_id']);
			
            $order_id         = $result['order_id'];
            $referenceId      = $result['kargo_barcode'];

            if($order_info){
                
                try {
                    $responsive = $this->mngTrackShipment($referenceId);
                } catch (exception $e) {
                    var_dump($e) ;die();
                }



				if($responsive['status'] && $responsive['response'] && isset($responsive['response'][0])){
					
					$shipping_steps = $responsive['response'];
				
					foreach ($shipping_steps as $shipping_step){
						
						$step_query = $this->db->query(" SELECT * FROM ".DB_PREFIX."order_mngkargo_steps WHERE mng_kargo_id = '". $result['mngkargo_id'] ."' AND mng_referenceid = '". $shipping_step['referenceId'] ."' AND mng_shipmentId = '". $shipping_step['shipmentId'] ."' AND mng_order_id  = '". $result['order_id'] ."' AND  mng_eventstatus = '". $shipping_step['eventStatus'] ."' ")->row;

						if(!$step_query){

			                $this->db->query("INSERT INTO " . DB_PREFIX . "order_mngkargo_steps  SET mng_kargo_id  = '" . $result['mngkargo_id'] . "', mng_referenceid  = '" . $shipping_step['referenceId'] . "', mng_shipmentId  = '" . $shipping_step['shipmentId'] . "', mng_order_id  = '" . $result['order_id'] . "', mng_eventstatus  = '" . $shipping_step['eventStatus'] . "', mng_location = '" . $shipping_step['location'] . "', mng_deliveryto = '" . $shipping_step['mng_deliveryto'] . "', mng_deliverydatetime = '" . $shipping_step['deliveryDateTime'] . "' ");
						
						
                            if($shipping_step['eventStatus'] == 'Gönderi Hazırlandı'){

                                echo $order_id  . ' ==> ' . $shipping_step['eventStatus'] . "<br>";

                                $this->db->query("UPDATE ".DB_PREFIX."order_mngkargo SET kargo_sonuc = '1'  WHERE mngkargo_id = '". $result['mngkargo_id'] ."' ");
                                $order_status_id = 17;
                                $mesaj = "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", ". $order_info['order_id'] ." no'lu siparişiniz MNG KARGO ya teslim edilmiştir. https://kargotakip.mngkargo.com.tr/?takipNo=".$shipping_step['shipmentId']."";
                                $this->sendSms($order_info['telephone'], $mesaj);
                                $notify = 1;
                                $this->model_checkout_order->addOrderHistory($order_info['order_id'], $order_status_id, $mesaj, $notify, 1);

                            }

                            if($shipping_step['eventStatus'] == 'Transfer Aşamasında'){

                                echo $order_id  . ' ==> ' . $shipping_step['eventStatus'] . "<br>";

                                $this->db->query("UPDATE ".DB_PREFIX."order_mngkargo SET kargo_sonuc = '1'  WHERE mngkargo_id = '". $result['mngkargo_id'] ."' ");
                                $order_status_id = 17;
                                $mesaj = "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", ". $order_info['order_id'] ." no'lu siparişiniz MNG KARGO da Transfer Aşamasında dır. https://kargotakip.mngkargo.com.tr/?takipNo=".$shipping_step['shipmentId']."";
                                $this->sendSms($order_info['telephone'], $mesaj);
                                $notify = 0;
                                $this->model_checkout_order->addOrderHistory($order_info['order_id'], $order_status_id, $mesaj, $notify, 1);

                            }
                            
                            if($shipping_step['eventStatus'] == 'Teslim Edildi'){

                                echo $order_id  . ' ==> ' . $shipping_step['eventStatus'] . "<br>";

                                $this->db->query("UPDATE ".DB_PREFIX."order_mngkargo SET kargo_sonuc = '3'  WHERE mngkargo_id = '". $result['mngkargo_id'] ."' ");
                                $order_status_id = 5;
                                $mesaj = "Sayın ". $order_info['firstname'] . ' ' . $order_info['lastname'] .", ". $order_info['order_id'] ." no'lu siparişiniz MNG KARGO tarafından teslim edilmiştir.";
                                //$this->sendSms($order_info['telephone'], $mesaj);
                                $notify = 1;
                                $this->model_checkout_order->addOrderHistory($order_info['order_id'], $order_status_id, $mesaj, $notify, 1);

                            }
						
						
						

						}
					}
					
				}else{
                   //var_dump($responsive); die();
                }
			
            }


        }



    }

    private function sendSms($telephone, $mesaj)
    {
		
        /*
            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($telephone,$mesaj);
                }
            }
        */

    }

    public function index2(){


        //https://www.deercase.com/index.php?route=tool/mngkargo_cron&order_id=1435406

        $shipping_result_satatus = array(
            '0' => 0, // Kargo kaydı açıldı
            '1' => 1, // Kargoya Verildi
            '2' => 2, // Teslim Edildi
            '3' => 3, // İade Kargo
        );

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

        $log = new Log("SuratKargoLogs.txt");

        $log->write("Çalıştı");

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

        if($order_id){
            $results = $this->db->query("SELECT * FROM ps_order_suratkargo WHERE order_id = '". (int)$order_id ."' ")->rows;
        }else{
            $sql = "SELECT * FROM ps_order_suratkargo WHERE kargo_sonuc IN (0,1) AND process_status = 0 ORDER BY RAND() ";
            $results = $this->db->query($sql)->rows;

            if(count($results) == 0){
                $this->db->query("UPDATE ps_order_suratkargo SET process_status = 0 WHERE kargo_sonuc IN (0,1) ");
                $results = $this->db->query($sql)->rows;
            }
            //$results = $this->db->query("SELECT * FROM `ps_order_suratkargo` WHERE `kargo_sonuc` IN ('0','1') AND `kargo_tarih` BETWEEN '2022-11-01' AND '2022-11-31'")->rows;
        }


        echo count($results) . ' Adet kargo işlenecektir. <br>';
    
        foreach ($results as $key => $result){

            if($key >= 100){
                exit;
            }

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

                $sonuc = $this->SURAT_SONUC($order);

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

                $del_url = 'https://www.deercase.com/index.php?route=tool/suratkargo_cron/delRow&order_id=' . $result['order_id'];


                if($sonuc == "Veri Bulunamadı. Fatura bilgilerini kontrol ederek tekrar deneyiniz."){
                    echo $result['order_id'] . ' => '. $result['kargo_tarih'] . ' ? ' . $order['payment_lastname'] ." ==> " . $sonuc . ' -> <a href="'. $del_url .'" target="_blank">Kaydı Sil</a>' ."<br>";
                    $this->db->query("UPDATE ps_order_suratkargo SET kargo_url = '". $this->db->escape($sonuc) ."' WHERE suratkargo_id = '". (int)$result['suratkargo_id'] ."' ");
                }elseif($sonuc->Durum && $sonuc->TeslimatDurum){
                    

                    $this->db->query("UPDATE ps_order_suratkargo SET kargo_url = '' WHERE suratkargo_id = '". (int)$result['suratkargo_id'] ."' ");


                    $step_query = $this->db->query("SELECT * FROM ps_order_suratkargo_steps WHERE suratkargo_id = '". $result['suratkargo_id'] ."' AND status = '". $this->db->escape($sonuc->TeslimatDurum) ."' ")->row;

                    if(!$step_query){

                        $this->db->query("INSERT INTO ps_order_suratkargo_steps SET 
                                suratkargo_id = '". $result['suratkargo_id'] ."', 
                                order_id = '". $result['order_id'] ."', 
                                status = '". $this->db->escape($sonuc->TeslimatDurum) ."', 
                                response = '". $this->db->escape(json_encode($sonuc)) ."' ");

                        echo $result['order_id'] . " ==> " . $sonuc->TeslimatDurum . " <---> " . $sonuc->Durum .  "<br>";

                        if($sonuc->TeslimatDurum == "İade Edilecek"){

                            // İADE
                            $this->db->query("UPDATE ps_order_suratkargo SET 
                                kargo_sonuc = '3' WHERE suratkargo_id = '".(int)$result['suratkargo_id']."' ");
    
                        }else if($sonuc->TeslimatDurum == "Teslim Edildi" && $sonuc->Durum == "Teslim Edildi"){
                           // var_dump($sonuc); die();

                            $kargo_url = 'http://www.suratkargo.com.tr/' . $sonuc->TakipNo;
                                $this->db->query("UPDATE ps_order_suratkargo SET 
                                kargo_takipno = '". $this->db->escape($sonuc->TakipNo) ."', 
                                kargo_url = '". $this->db->escape($kargo_url) ."', 
                                kargo_sonuc = '2' WHERE suratkargo_id = '".(int)$result['suratkargo_id']."' ");
                                
                                $this->addHistory($order, 'TESLİM EDİLDİ', true, $sonuc, $result);
                                //die();
                        }
                        else if($sonuc->TeslimatDurum == "Tekrar Gidilecek" && $sonuc->Durum == "Alici Subede"){
                            $this->addHistory($order, 'TESLIMAT HAZIRLIK', true, $sonuc, $result);
                        }
                        else if($sonuc->TeslimatDurum == "Teslimat Hazırlık" && $sonuc->Durum == "Gönnderici Şubede"){
                            $this->addHistory($order, 'TESLIMAT HAZIRLIK', true, $sonuc, $result);
                        }
                        else if($sonuc->TeslimatDurum == "Teslimat Hazırlık" && $sonuc->Durum == "Yolda"){
                            $this->addHistory($order, 'YOLDA', true, $sonuc, $result);
                        }
                        else if($sonuc->TeslimatDurum == "Teslimat Hazırlık" && $sonuc->Durum == "Alici Subede"){
                            $this->addHistory($order, 'TESLIMAT HAZIRLIK', true, $sonuc, $result);
                        }
                        else if($sonuc->TeslimatDurum == "Teslimat Hazırlık" && $sonuc->Durum == "Aktarma Merkezinde"){
                            $this->addHistory($order, 'TESLIMAT HAZIRLIK', true, $sonuc, $result);
                        }
                        else if($sonuc->TeslimatDurum == "Teslim Edildi" && $sonuc->Durum == "İade Teslim"){
                            $this->db->query("UPDATE ps_order_suratkargo SET 
                                kargo_sonuc = '3' WHERE suratkargo_id = '".(int)$result['suratkargo_id']."' ");
                        }
                        else if($sonuc->TeslimatDurum == "Teslimat Hazırlık" && $sonuc->Durum == "Gruplandi"){
                            $this->addHistory($order, 'TESLIMAT HAZIRLIK', true, $sonuc, $result);
                        }
                        else if($sonuc->TeslimatDurum == "Teslimat Hazırlık" && $sonuc->Durum == "Kargo Subede"){
                            $this->addHistory($order, 'TESLIMAT HAZIRLIK', true, $sonuc, $result);
                        }
                        else{
                            var_dump($sonuc); 
                        }

                    }else{
                        if($result['kargo_takipno'] == ''){
                            $this->db->query("DELETE FROM ps_order_suratkargo_steps WHERE step_id = '". $step_query['step_id'] ."' ");
                        }
                        echo $result['order_id'] . ' => '. $sonuc->Durum . ' - ' . $sonuc->TeslimatDurum ." ==> İşlenmiş durum <br>";
                    }

                    
                    
                    
                }else{
                    echo "Başka bir durum var! <br>";
                    var_dump($sonuc); die();
                }

                $this->db->query("UPDATE ps_order_suratkargo SET process_status = 1 WHERE suratkargo_id = '". (int)$result['suratkargo_id'] ."' ");
                $this->db->query("UPDATE ps_order_suratkargo SET process_count = process_count + 1 WHERE suratkargo_id = '". (int)$result['suratkargo_id'] ."' ");


            }else {
                $this->db->query("DELETE FROM ps_order_suratkargo WHERE suratkargo_id = '". (int)$result['suratkargo_id'] ."' ");
                echo $result['order_id'] . " ==> Sipariş bulunamadı! <br>";
            }
        }

    }

    private function addHistory($order_info, $sonuc, $notify = false, $kargo_sonuc, $result = array()){

        
        $order_status_id = 0;

        if($kargo_sonuc->TakipNo){
            $this->db->query("UPDATE ps_order_suratkargo SET kargo_takipno = '". $this->db->escape($kargo_sonuc->TakipNo) ."' WHERE suratkargo_id = '".(int)$result['suratkargo_id']."' ");
        }

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

        $comment = "";

        if($sonuc == 'TESLİM EDİLDİ'){
            $comment = "Kargonuz Teslim Edilmiştir";
            $order_status_id = 5;
            $this->db->query("UPDATE ps_order_suratkargo SET process_status = 1 WHERE suratkargo_id = '".(int)$result['suratkargo_id']."' ");
        }else if($sonuc == 'TESLIMAT HAZIRLIK'){
            $comment = "Merhaba ". $order_info['firstname'] ." ". $order_info['lastname'] .", ". $order_info['order_id'] ." no'lu Siparişinizi size ulaşması için kargoya verdik. <br>";
            $comment .= '<a target="_blank" href="https://www.suratkargo.com.tr/Default/_KargoTakip?kargotakipNo='. $kargo_sonuc->TakipNo .'"> Kargo Takip Linkiniz: '. $kargo_sonuc->TakipNo ."</a>";
            $order_status_id = 17;
        }
        else if($sonuc == 'YOLDA'){
            $comment = "Merhaba ". $order_info['firstname'] ." ". $order_info['lastname'] .", ". $order_info['order_id'] ." no'lu Siparişinizi dağıtıma çıkarıldı!";
            $comment .= '<a target="_blank" href="https://www.suratkargo.com.tr/Default/_KargoTakip?kargotakipNo='. $kargo_sonuc->TakipNo .'"> Kargo Takip Linkiniz: '. $kargo_sonuc->TakipNo ."</a>";
            $order_status_id = 19;
        }
        

        if($order_status_id){
           $this->model_checkout_order->addOrderHistory($order_info['order_id'], $order_status_id, $comment, $notify, 1);
        }


    }

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

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

        $this->db->query("UPDATE ps_order_suratkargo SET kargo_sonuc = 5 WHERE order_id = '". (int)$order_id ."' ");



    }

    public function OAuthRedirectURI()
    {

        //https://www.deercase.com/index.php?route=tool/mngkargo_cron/OAuthRedirectURI

        //İstemcinizin güvenlik dizgisi: I5nC6kV8eB4gA6uF1wJ8bH2iC2nP4nB0fV1bM5oQ4dH5yW4gC1
        echo "OAuthRedirectURI";
    }


}