<?php

class ControllerExtensionModuleNetgsm extends Controller {
	private $error = array();

	public function index()
    {
        $this->load->language("extension/module/netgsm");

        $this->document->setTitle($this->language->get("heading_title"));

        $this->load->model('setting/setting');
        $this->load->model('design/layout');

        if (($this->request->server["REQUEST_METHOD"] == "POST") && $this->validate()) {
            $this->model_setting_setting->editSetting('netgsm', $this->request->post);
            $this->session->data["success"] = $this->language->get("text_success");
            if (isset($this->request->post['sayfayi_yenile']) and $this->request->post['sayfayi_yenile']) {
                $this->response->redirect($this->url->link('extension/module/netgsm', 'user_token=' . $this->session->data['user_token'], true));
            } else {
                $this->response->redirect($this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true));
            }
        }

        if (isset($this->error["warning"])) {
            $data["error_warning"] = $this->error["warning"];
        } else {
            $data["error_warning"] = "";
        }

        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true),
            'separator' => false
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_extension'),
            'href' => $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true),
            'separator' => ' :: '
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('extension/module/netgsm', 'user_token=' . $this->session->data['user_token'], true),
            'separator' => ' :: '
        );

        $data['action'] = $this->url->link('extension/module/netgsm', 'user_token=' . $this->session->data['user_token'], true);
        $data['cancel'] = $this->url->link('marketplace/extension', 'user_token=' . $this->session->data['user_token'] . '&type=module', true);
        $data['user_token'] = $this->session->data['user_token'];


        $dizi = array('netgsm_status','netgsm_turkishChar',
            'netgsm_order_refund_to_admin_control', 'netgsm_order_refund_to_admin_no', 'netgsm_order_refund_to_admin_text',
            'netgsm_neworder_to_customer_text', 'netgsm_neworder_to_customer_control',
            'netgsm_neworder_to_admin_text', 'netgsm_neworder_to_admin_no', 'netgsm_neworder_to_admin_control',
            'netgsm_newuser_to_customer_text', 'netgsm_newuser_to_customer_control',
            'netgsm_newuser_to_admin_text', 'netgsm_newuser_to_admin_no', 'netgsm_newuser_to_admin_control',
            'netgsm_input_smstitle', 'netgsm_pass', 'netgsm_user',
            'netgsm_orderstatus_change_customer_control',
            'netgsm_rehber_control','netgsm_rehber_groupname'
        );
        for ($x = 0; $x < count($dizi); $x++)          //diziye eklediğimiz değişkenlerle  alttaki kodu çoğaltıyoruz.
        {
            if (isset($this->request->post[$dizi[$x]])) {
                $data[$dizi[$x]] = $this->request->post[$dizi[$x]];
            } elseif ($this->config->get($dizi[$x])) {
                $data[$dizi[$x]] = $this->config->get($dizi[$x]);
            } else {
                $data[$dizi[$x]] = '';
            }
        }



        //sipariş durumu değiştiğinde START
        $this->load->model('localisation/order_status');
        $kargo_durumlari = $this->model_localisation_order_status->getOrderStatuses();
        $data['kargo_durumlari'] = $kargo_durumlari;

        foreach ($kargo_durumlari as $kd) {
            if (isset($this->request->post['netgsm_order_status_text_' . $kd['order_status_id']])) {
                $data['netgsm_order_status_text_' . $kd['order_status_id']] = $this->request->post['netgsm_order_status_text_' . $kd['order_status_id']];
            } elseif ($this->config->get('netgsm_order_status_text_' . $kd['order_status_id'])) {
                $data['netgsm_order_status_text_' . $kd['order_status_id']] = $this->config->get('netgsm_order_status_text_' . $kd['order_status_id']);
            } else {
                $data['netgsm_order_status_text_' . $kd['order_status_id']] = '';
            }
        }

        if (empty($data['netgsm_user']) || empty($data['netgsm_pass'])) {
            $data['netgsm_credit'] = '10Sms göndermek ve bakiyenizi görüntüleyebilmek için üyelik bilgilerinizi giriniz.';
            $data['netgsm_package'] = 'Paket ve Kampanyalarınızı görüntüleyebilmek için üyelik bilgilerinizi giriniz.';
            $data['netgsm_smstitle'] = '';
            $data['netgsm_all_title'] = '';
            $data['netgsm_login_status'] = false;
        } else {
            $netgsmsms = new Netgsmsms($data['netgsm_user'], $data['netgsm_pass']);
            $data['netgsm_credit'] = $netgsmsms->getKredi();
            $data['netgsm_smstitle'] = $this->config->get('netgsm_input_smstitle');
            $data['netgsm_all_smstitle'] = $netgsmsms->getSmsBaslik();
            $data['netgsm_package'] = $netgsmsms->getPaket();
            $inboxs = $netgsmsms->inbox();
            $inbox_data = [];
            $tmp = [];
            $data['netgsm_inbox_status'] = $inboxs['status'];
            if (isset($inboxs['status']) && $inboxs['status']==200){
                unset($inboxs['status']);
                foreach ($inboxs as $inbox){
                    if (isset($inbox['phone']) && !empty($inbox['phone'])){
                        $customer = $this->getCustomerByPhone($inbox['phone']);
                        if ($customer != null){
                            $tmp['id'] = $customer['customer_id'] ;
                            $tmp['firstname'] = $customer['firstname'] ;
                            $tmp['lastname'] = $customer['lastname'] ;
                            $tmp['name'] = $customer['firstname'] .' '. $customer['lastname'] ;
                            $tmp['email'] = $customer['email'];
                        } else {
                            $tmp['id'] = '' ;
                            $tmp['name'] = '' ;
                            $tmp['email'] = '';
                        }

                        $tmp['phone'] =$inbox['phone'];
                        $tmp['msg'] =$inbox['message'];
                        $datetime = explode(' ',$inbox['time']);
                        $tmp['date'] =$datetime[0];
                        $tmp['time'] =$datetime[1];
                        array_push($inbox_data,$tmp);
                    }
                }
            } else {
                $data['netgsm_inbox_message'] = $inboxs['message'];
            }
            /*echo '<pre>';
            print_r($inbox_data);*/
            $data['netgsm_inbox'] = $inbox_data;

            $data['netgsm_login_status'] = true;
        }

        if(isset($data['netgsm_user']) && isset($data['netgsm_pass'])){
            $netgsmsms = new Netgsmsms($data['netgsm_user'], $data['netgsm_pass']);
            $data['netgsm_girisbilgileri'] = json_decode($netgsmsms->netgsm_GirisSorgula($data['netgsm_user'],$data['netgsm_pass']));
        }else {
            $obje = array('durum'=>'danger', 'icon'=> 'fa-exclamation-triangle', 'mesaj'=>' Kullanıcı adı veya şifreniz hatalı.',
                'btnkontrol'=>'disabled','href'=>'');
            $data['netgsm_girisbilgileri'] = json_decode(json_encode($obje));
        }


        $data['version'] = VERSION;


        $this->document->addStyle('view/javascript/netgsm/lib/sweetalert2/dist/sweetalert2.css');
        $this->document->addScript('view/javascript/netgsm/lib/sweetalert2/dist/sweetalert2.all.min.js');

        $data["header"] = $this->load->controller("common/header");
		$data["column_left"] = $this->load->controller("common/column_left");
		$data["footer"] = $this->load->controller("common/footer");

		$this->response->setOutput($this->load->view("extension/module/netgsm", $data));
	}

    public function getCustomerByPhone($phone) {
        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE LOWER(telephone) like '%" . $this->db->escape(utf8_strtolower($phone)) . "%'");

        return $query->row;
    }


    protected function validate() {
        if (!$this->user->hasPermission('modify', 'extension/module/netgsm')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }
        return !$this->error;
    }
	
	 private function convertcustomers($id, $mesaj)
    {
        $this->load->model('customer/customer');
        $results = $this->model_customer_customer->getCustomer($id);

        $istenmeyen= array('[kullanıcı_ad]','[kullanıcı_soyad]','[email]', '[telefon]');
        $degisen = array  ($results['firstname'] ,$results['lastname'] , $results['email'], $results['telephone']);
        $giden = str_replace($istenmeyen,$degisen,$mesaj);
        return $giden;
    }

    private function convertorders($id, $mesaj)
    {
        $this->load->model('sale/order');
        $results = $this->model_sale_order->getOrder($id);

        $istenmeyen= array('[müşteri]','[sipariş_no]','[kargo]','[toplam]','[siparişdurumu]');
        $degisen = array  ($results['customer'],$results['order_id'],$results['shipping_code'] , $results['total'] , $results['order_status']);
        $giden = str_replace($istenmeyen,$degisen,$mesaj);
        return $giden;
    }
	
	public function SMSgonder()
    {
        $json = array();
        if(isset($this->request->post['message'])){
            $netgsmsms = new Netgsmsms($this->config->get('netgsm_user'),$this->config->get('netgsm_pass'),'',$this->config->get('netgsm_turkishChar'));
            $ordersid = $this->request->post['orders'];
            $orders = explode(',', $ordersid);
            $numarayamsj = "";
            $telefonlar = explode(',',$this->request->post['phone']);
            $i=0;
            foreach ($orders as $id) {
                if($telefonlar[$i]!=''){
                    if($this->request->post['smstype']==1) {
                        $numarayamsj .= '<mp><msg><![CDATA[' . $this->convertcustomersInbox($id, $this->request->post['message']) . ']]></msg><no>' . $netgsmsms->getphoneClear($telefonlar[$i]) . '</no></mp>' . "\n";
                    }
                    else if($this->request->post['smstype']==2){
                        $numarayamsj .= '<mp><msg><![CDATA[' . $this->convertorders($id, $this->request->post['message']) . ']]></msg><no>' . $netgsmsms->getphoneClear($telefonlar[$i]) . '</no></mp>' . "\n";
                    }
                }
                $i++;
            }
            $cevap = $netgsmsms->bulkSMScustom($numarayamsj,$this->config->get('netgsm_input_smstitle'));
            $bol = explode(' ',$cevap);
            if($bol[0]=='00')
            {
                $json['result'] = 'success';
                $json['resultmsg'] = 'Smsler başarılı bir şekilde gönderildi.';
            }
            else{
                $json['result'] = 'error';
                $json['resultmsg'] = 'Sms gönderimi başarısız. Lütfen Netgsm hesabınıza giriş yaptığınıza ve başlık seçtiğinize emin olun.' ;
            }
        }
        else
        {
            $json['result'] = 'error';
            $json['resultmsg'] = 'Sms gönderimi başarısız.';
        }
        $this->response->setOutput(json_encode($json));
    }


    private function convertcustomersInbox($id, $mesaj)
    {
        $this->load->model('customer/customer');
        $results = $this->model_customer_customer->getCustomer($id);

        $istenmeyen= array('[uye_adi]','[uye_soyadi]','[uye_telefonu]', '[uye_epostasi]');
        $degisen = array  ($results['firstname'] ,$results['lastname'], $results['telephone'], $results['email']);
        $giden = str_replace($istenmeyen,$degisen,$mesaj);
        return $giden;
    }

    public function SMSgonderinbox()
    {
        $id = $this->request->post['id'];
        $phone = $this->request->post['phone'];
        $message = $this->request->post['message'];
        $json = array();
        if(isset($message)){
            $netgsmsms = new Netgsmsms($this->config->get('netgsm_user'),$this->config->get('netgsm_pass'),'',$this->config->get('netgsm_turkishChar'));

            if ($id!=''){
                $sendMessageText = $this->convertcustomersInbox($id,$message);
            } else {
                $sendMessageText = $message;
            }
            $cevap = $netgsmsms->privateSMS($phone,$sendMessageText,$this->config->get('netgsm_input_smstitle'));

            $bol = explode(' ',$cevap);
            if($bol[0]=='00')
            {
                $json['result'] = 'success';
                $json['resultmsg'] = 'Sms gönderimi başarılı.';
            }
            else{
                $json['result'] = 'error';
                $json['resultmsg'] = 'Sms gönderimi başarısız. Lütfen Netgsm hesabınıza giriş yaptığınıza ve başlık seçtiğinize emin olun.' ;
            }
        }
        else
        {
            $json['result'] = 'error';
            $json['resultmsg'] = 'Sms gönderimi başarısız.';
        }
        $this->response->setOutput(json_encode($json));
    }

    public function SMSgonderozel()
    {
        $json = array();
        if(isset($this->request->post['message'])){
            $netgsmsms = new Netgsmsms($this->config->get('netgsm_user'),$this->config->get('netgsm_pass'),$this->config->get('netgsm_input_smstitle'), $this->config->get('netgsm_turkishChar'));

            $cevap = $netgsmsms->sendSMS($this->request->post['phone'],$this->request->post['message'],$this->config->get('netgsm_input_smstitle'));

            $bol = explode(' ',$cevap);
            if($bol[0]=='00')
            {
                $json['result'] = 'success';
                $json['resultmsg'] = 'Sms gönderimi başarılı.';
            }
            else{
                $json['result'] = 'error';
                $json['resultmsg'] = 'Sms gönderimi başarısız. Lütfen Netgsm hesabınıza giriş yaptığınıza ve başlık seçtiğinize emin olun.' ;
            }
        }
        else
        {
            $json['result'] = 'error';
            $json['resultmsg'] = 'Sms gönderimi başarısız.';
        }
        $this->response->setOutput(json_encode($json));
    }

    public function rehberAktar()
    {
        $this->load->model('customer/customer');
        $results = $this->model_customer_customer->getCustomers();

        $contacts = []; $tmp = [];
        foreach ($results as $result) {
            $tmp['firstname'] = $result['firstname'];
            $tmp['lastname'] = $result['lastname'];
            $tmp['telephone'] = $result['telephone'];
            array_push($contacts, $tmp);
        }

        $netgsmsms = new Netgsmsms($this->config->get('netgsm_user'),$this->config->get('netgsm_pass'),'',$this->config->get('netgsm_turkishChar'));
        $groupName = 'Opencart';
        if(isset($this->request->post['groupName'])){
            $groupName = $this->request->post['groupName'];
        }
        $moving = $netgsmsms->setContact($contacts, $groupName);

        $json = ['result'=>'success','resultmsg'=>'Toplam <b>'.count($contacts).'</b> müşteri <b>'.$groupName.'</b> grubuna aktarıldı.'];
        $this->response->setOutput(json_encode($json));
    }

    /*
     * Netsantral ve ses sekmesi verilerini çeker. Netsantral e bakar yoksa Sabit telefon u sorgular
     */
    public function getNetsantralReport()
    {
        $netgsmsms = new Netgsmsms($this->config->get('netgsm_user'),$this->config->get('netgsm_pass'),'',$this->config->get('netgsm_turkishChar'));
        $json = $netgsmsms->getVoipReport();
        $type = 'NETSANTRAL';
        $info = '';
        $table = '<table  data-pagination="true" id="table" name="table" class="table table-bordered table-striped dataTable no-footer"
                            data-search="true" data-search-align="left"
                            data-pagination-v-align="bottom"
                            data-click-to-select="true"
                            data-toggle="table"
                            data-page-list="[10, 25, 50, 100, 150, 200]"><thead><th>#</th><th>Tarih</th><th>Arayan</th><th>Aranan</th><th>Süre</th><th>Yön</th><th>İşlemler</th></thead><tbody>';
        $object = json_decode($json);
        if (is_object($object) && isset($object->success)){
            foreach ($object->data as $data) {
                $table .= '<tr>';
                $table .= '<td>'.$data->call_id.'</td>';
                $table .= '<td>'.$data->date.'</td>';

                $customer = $this->getCustomerByPhone(ltrim($data->caller_number,'0'));
                $c_id = '';
                $c_name = '';
                if ($customer != null) {
                    $c_id = $customer['customer_id'];
                    $c_name = $customer['firstname']. ' ' . $customer['lastname'] ;
                }

                if($c_name != ''){
                    $table .= '<td><i class="fa fa-user" style="color:#06B7F0"></i> <a href="index.php?route=customer/customer/edit&user_token='.$this->session->data['user_token'].'&customer_id='.$c_id.'" target="_blank" data-toggle="tooltip" data-placement="top" title="'.$data->caller_number.'">'.$c_name.'</a></td>';
                } else {
                    $table .= '<td>'.$data->caller_number.'</td>';
                }

                $table .= '<td>'.$data->dial_number.'</td>';
                $table .= '<td>'.$data->time.'</td>';

                $direction = '';
                switch ($data->direction){
                    case 0: //giden
                        $direction = '<i class="fa fa-arrow-circle-o-up" style="color: #3498DB;"></i> Giden';
                        break;
                    case 1:
                        $direction = '<i class="fa fa-arrow-circle-down" style="color: #2ECC71;"></i> Gelen';
                        break;
                    case 2:
                        $direction = '<i class="fa fa-arrow-circle-down" style="color: #E74C3C;"></i> Gelen Cevapsız';
                        break;
                    case 3:
                        $direction = '<i class="fa fa-arrow-circle-up" style="color: #E74C3C;"></i> Giden Cevapsız';
                        break;
                    case 4:
                        break;
                        $direction = '<i class="fa fa-arrow-circle-left" style="color: #2C3E50;"></i> <i class="fa fa-arrow-circle-right" style="color: #2C3E50;"></i> İç Arama';
                    case 5:
                        break;
                        $direction = '<i class="fa fa-arrow-circle-left" style="color: #E74C3C;"></i> <i class="fa fa-arrow-circle-right" style="color: #E74C3C;"></i> İç Cevapsız Arama';
                    default:
                        $direction = 'Bilinmiyor';
                        break;
                }
                $table .= '<td>'. $direction .'</td>';
                if (strlen($data->caller_number )==11){
                    $table .= '<td><a href="javascript:void(0);" class="btn btn-info btn-sm" onclick="netgsm_sendSMS_bulkTab(\''.$c_id.'\',\''.$data->caller_number.'\'); ">Arayana SMS Gönder</a></td>';
                } else {
                    $table .= '<td></td>';
                }
                $table .= '</tr>';
            }
            $table .= '</tbody></table>';
            $message = $table;
            $status = 'success';
            $type = 'NETSANTRAL';
            $info = $object->success->message;
        } else {
            if (is_object($object) && isset($object->error)) {
                if (in_array($object->error->code, [30, 80])) {
                    $json = $netgsmsms->getPhoneReport();

                    $table = '<table  data-pagination="true" id="table" name="table" class="table table-bordered table-striped dataTable no-footer"
                            data-search="true" data-search-align="left"
                            data-pagination-v-align="bottom"
                            data-click-to-select="true"
                            data-toggle="table"
                            data-page-list="[10, 25, 50, 100, 150, 200]"><thead><th>#</th><th>Tarih</th><th>Arayan</th><th>Süre</th><th>Yön</th><th>İşlemler</th></thead><tbody>';
                    $object = json_decode($json);
                    if (is_object($object) && isset($object->success)) {
                        foreach ($object->data as $data) {
                            $table .= '<tr>';
                            $table .= '<td>#</td>';
                            $table .= '<td>' . $data->date . '</td>';

                            $customer = $this->getCustomerByPhone(ltrim($data->caller_number,'0'));
                            $c_id = '';
                            $c_name = '';
                            if ($customer != null) {
                                $c_id = $customer['customer_id'];
                                $c_name = $customer['firstname'] . ' ' . $customer['lastname'];
                            }

                            if ($c_name != '') {
                                $table .= '<td><i class="fa fa-user" style="color:#06B7F0"></i> <a href="index.php?route=customer/customer/edit&user_token=' . $this->session->data['user_token'] . '&customer_id=' . $c_id . '" target="_blank" data-toggle="tooltip" data-placement="top" title="' . $data->caller_number . '">' . $c_name . '</a></td>';
                            } else {
                                $table .= '<td>' . $data->caller_number . '</td>';
                            }

                            $table .= '<td>' . $data->time . '</td>';

                            $direction = '';
                            switch ($data->direction) {
                                case 1:
                                    $direction = '<i class="fa fa-arrow-circle-down" style="color: #2ECC71;"></i> Gelen';
                                    break;
                                case 2: //giden
                                    $direction = '<i class="fa fa-arrow-circle-o-up" style="color: #3498DB;"></i> Giden';
                                    break;
                                case 3:
                                    $direction = '<i class="fa fa-arrow-circle-down" style="color: #E74C3C;"></i> Cevapsız';
                                    break;
                                default:
                                    $direction = 'Bilinmiyor';
                                    break;
                            }
                            $table .= '<td>' . $direction . '</td>';
                            if (in_array(strlen($data->caller_number), [10,11])) {
                                $table .= '<td><a href="javascript:void(0);" class="btn btn-info btn-sm" onclick="netgsm_sendSMS_bulkTab(\'' . $c_id . '\',\'' . $data->caller_number . '\'); ">Arayana SMS Gönder</a></td>';
                            } else {
                                $table .= '<td></td>';
                            }
                            $table .= '</tr>';
                        }
                        $table .= '</tbody></table>';
                        $message = $table;
                        $status = 'success';
                        $type = 'SES';
                        $info = $object->success->message;
                    } else {
                        if (is_object($object) && isset($object->error)) {
                            $status = 'error';
                            $message = $object->error->message;
                            $info = $object->error->message;
                        } else {
                            $message = 'Bilinmeyen Hata oluştu.';
                            $info = 'Bilinmeyen Hata oluştu.';
                            $status = 'error';
                        }
                    }
                } else {
                    $status = 'error';
                    $message = $object->error->message;
                    $info = $object->error->message;
                }
            } else {
                $message = 'Bilinmeyen Hata oluştu.';
                $info = 'Bilinmeyen Hata oluştu.';
                $status = 'error';
            }
        }
        $this->response->setOutput(json_encode(['status'=>$status, 'message'=>$message, 'type'=>$type, 'info'=>$info]));
    }
}