<?php
/*
  Plugin Name: پیام صوتی آوانک
  Plugin URI: avanak.ir
  Description: پیام صوتی آوانک
  Version: 2.2
  Requires at least: 5.2
  Requires PHP:      7.2
  Author: Amoot software
  Author URI: https://www.amootsoft.com/
  Copyright: 2024 https://www.amootsoft.com/ , Amoot software
*/


if (!defined('ABSPATH'))
{
    exit;
}


date_default_timezone_set('Asia/tehran');


if (add_shortcode('wp_callsound_dialler_form', 'diallerForm'))
{
    
}
else
{
    $avanakClass = new Avanak();
}

function diallerForm()
{
    ob_start();
    require('pages'.DIRECTORY_SEPARATOR.'di.php');
    $output = ob_get_contents();
	// $output = apply_filters('the_content',$output);
    ob_end_clean();
    return $output;
}

class Avanak
{

    protected $currentUser;
    protected $options;
    protected $pluginName = 'avanak-soundcall';
    protected $currentUserBalance;
    protected $soupDisable;

    function __construct()
    {
        // get options
        $this->getoptioninfo();
        if(class_exists("SoapClient")){
            $this->soupDisable = false;
        }else{
            $this->soupDisable = true;
        }
        // plugin load info

        add_action('plugins_loaded', array($this, 'init'), 0);

        add_action('admin_menu', array($this, 'menu'));

        // ajax login
        add_action('wp_ajax_avanak_callcound_login', array($this, 'loginAjax'));

        // file manager filelist
        add_action('wp_ajax_avanak_callcound_file_list', array($this, 'filemanagerAjxasList'));
        add_action('wp_ajax_avanak_callcound_file_delete', array($this, 'filemanagerajaxDelete'));
        add_action('wp_ajax_avanak_callcound_file_upload', array($this, 'filemanagerajaxUpload'));
        add_action('wp_ajax_avanak_callcound_file_download', array($this, 'filemanagerajaxDownload'));

        // seech ajax
        add_action('wp_ajax_avanak_callcound_speech', array($this, 'speechAjax'));


        // quick send ajax
        add_action('wp_ajax_avanak_callcound_quicksend', array($this, 'quicksend'));

        // avanak_callcound_woocommerce_setting
        add_action('wp_ajax_avanak_callcound_woocommerce_setting', array($this, 'woocommerceSaveSetting'));

        add_action('woocommerce_order_status_completed', array($this, 'WCcompleted'));
        add_action('woocommerce_order_status_processing', array($this, 'WCprocessing'));
        
        add_action('woocommerce_order_status_failed', array($this, 'WCfailed'));
        add_action('woocommerce_order_status_on-hold', array($this, 'WConhold'));
        add_action('woocommerce_order_status_cancelled', array($this, 'WCcancelled'));
        add_action('woocommerce_payment_complete', array($this, 'WCPaymentComplate'));

        // users
        //avanak_callcound_user_setting
        // add_action('wp_ajax_avanak_callcound_user_setting', array($this, 'usersAjaxSave'));

		if (class_exists('Digits')) {
			// Digits is active, use Digits mobile field
			
		} elseif (function_exists('is_woocommerce_active') && is_woocommerce_active()) {
			// WooCommerce is active, use WooCommerce mobile field
			
		} else {
			add_action('register_form', array($this, 'registerFormInput'));
			add_action('show_user_profile', array($this, 'profileFormFields'));
			add_action('edit_user_profile', array($this, 'profileFormFields'));
		}



        // dialler
        add_action('wp_callsound_dialler_form', array($this, 'diallerForm'));

		// dialer call ajax
        add_action('wp_ajax_nopriv_avanak_dillerAction', array($this, 'dillerAction'));
        add_action('wp_ajax_avanak_dillerAction', array($this, 'dillerAction'));

        add_action('wp_ajax_dillerSave', array($this, 'dillerSave'));


        // otc
        add_action('wp_ajax_sendotc', array($this, 'sendotc'));
        //amount
        add_action('wp_ajax_amount', array($this, 'amount'));


        // $this->avanakcheck_birthdays();
    }

    public function init()
    {
        //if (!current_user_can('manage_options')) wp_die('<p style="text-align:center">شما اجازه دسترسی به این افزونه را ندارید</p>');
        $this->currentUser = (wp_get_current_user() ?: null);
    }

    // create menu
    public function menu()
    {
        if (function_exists('add_options_page'))
        {
            $capability = 'manage_options';
            $submenuCap = 'manage_options';
            $menuIcon = plugin_dir_url(__FILE__).'style'.DIRECTORY_SEPARATOR.'img'.DIRECTORY_SEPARATOR.'wp_callsound.png';
            add_menu_page($this->pluginName, 'پیام صوتی آوانک', $capability , $this->pluginName, array($this, 'dashboard'), $menuIcon);
            add_submenu_page($this->pluginName, 'مدیریت حساب', 'مدیریت حساب', $submenuCap, 'avanak-setting', array($this, 'login'));
            add_submenu_page($this->pluginName, 'تنظیم woocommerce', 'تنظیم woocommerce', $submenuCap, 'avanak-woocommerce', array($this, 'woocommerce'));
            // add_submenu_page($this->pluginName, 'مدیریت کاربران', 'مدیریت کاربران', $submenuCap, 'avanak-users', array($this, 'users'));
            add_submenu_page($this->pluginName, 'تبدیل متن به صدا', 'تبدیل متن به صدا', $submenuCap, 'avanak-speech', array($this, 'speech'));
            add_submenu_page($this->pluginName, 'مدیریت پیام های صوتی', 'مدیریت پیام های صوتی', $submenuCap, 'avanak-files', array($this, 'filemanager'));
            add_submenu_page($this->pluginName, 'تنظیم شماره گیر', 'شماره گیر', $submenuCap, 'avanak-dialler', array($this, 'dialler'));
            add_submenu_page($this->pluginName, 'خدمات دیگر', 'خدمات دیگر', $submenuCap, 'avanak-services', array($this, 'service'));
            add_submenu_page($this->pluginName, 'راهنما', 'راهنما', $submenuCap, 'avanak-help', array($this, 'help'));
        }
    }

    // dashboard page
    public function dashboard()
    {
        $this->addfiles();
        require_once('dashboard.php');
    }

    public function login()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        $this->addfiles();
        require_once('pages'.DIRECTORY_SEPARATOR.'login.php');
    }

    public function loginAjax()
    {
        try {
            $serverStatic = 'https://portal.avanak.ir';
            $login = $this->connect($serverStatic, 'GetCredit', array('userName' => $_POST['username'], 'password' => $_POST['password']));

            if (false !== $login)
            {
                // $response = simplexml_load_string($login);
                $loginStatus = false;
                $userBalance = 0;

                if ($login->GetCreditResult > 0)
                {
                    $userBalance = $login->GetCreditResult;
                    $loginStatus = true;
                }
                else
                {
                    $loginStatus = false;
                }
            
                

                if($loginStatus){
                    $this->currentUserBalance = $userBalance;
                    $this->loginUpdate($serverStatic, $_POST['username'], $_POST['password']);
                    echo '<p class="yekan" style="font-size:12px;color:green">اطلاعات شما با موفقیت ذخیره شد</p>';
                }else{
                    echo '<p class="yekan" style="font-size:12px;color:red">مشخصات کاربری شما صحیح نیست</p>';
                }
            }
            else
            {
                // echo $login;
                echo '<p class="yekan" style="font-size:12px;color:red">ارتباط با سرور برقرار نشد</p>';
            }
        } catch (\Throwable $th) {
            //throw $th;
            echo $th;
        }
		
        wp_die();
    }

    public function loginUpdate($server, $username, $password)
    {
        if (get_option('AvanakLoginInfoII'))
        {
            return update_option('AvanakLoginInfoII', array($server, $username, $password));
        }
        else
        {
            return add_option('AvanakLoginInfoII', array($server, $username, $password));
        }
    }

    public function woocommerce()
    {
        $wci = get_option('AvanakWoocommerceII');
        if (!$wci)
        {
            $wci = array(0, 0, 0, 0);
        }
        $this->addfiles();
        $isWoocommeceActive = false;
        $soundList          = false;
        $activePlugin       = apply_filters('active_plugins', get_option('active_plugins'));
        if (in_array('woocommerce/woocommerce.php', $activePlugin) or in_array('persian-woocommerce/woocommerce-persian.php', $activePlugin))
        {
            $isWoocommeceActive = true;
            $soundList          = $this->getSoundList();
            $soundListArray     = array(
                $this->selectOptionSoundList($soundList, 'WCcompleted', $wci['WCcompleted'], true),
                $this->selectOptionSoundList($soundList, 'WCprocessing', $wci['WCprocessing'], true),
                $this->selectOptionSoundList($soundList, 'WCfailed', $wci['WCfailed'], true),
                $this->selectOptionSoundList($soundList, 'WConhold', $wci['WConhold'], true),
                $this->selectOptionSoundList($soundList, 'WCcancelled', $wci['WCcancelled'], true),
                $this->selectOptionSoundList($soundList, 'WCPaymentComplate', $wci['WCPaymentComplate'], true)
            );
        }
        require_once('pages'.DIRECTORY_SEPARATOR.'woocommerce.php');
    }

    public function woocommerceSaveSetting()
    {
        if (get_option('AvanakWoocommerceII'))
        {
            update_option('AvanakWoocommerceII', array(
                'WCcompleted'       => $_POST['WCcompleted'],
                'WCprocessing'          => $_POST['WCprocessing'],
                'WCfailed'          => $_POST['WCfailed'],
                'WConhold'          => $_POST['WConhold'],
                'WCcancelled'       => $_POST['WCcancelled'],
                'WCPaymentComplate' => $_POST['WCPaymentComplate']
                    )
            );
            echo 'تنظیمات با موفقیت ذخیره شد';
        }
        else
        {
            add_option('AvanakWoocommerceII', array(
                'WCcompleted'       => $_POST['WCcompleted'],
                'WCfailed'          => $_POST['WCfailed'],
                'WCprocessing'          => $_POST['WCprocessing'],
                'WConhold'          => $_POST['WConhold'],
                'WCcancelled'       => $_POST['WCcancelled'],
                'WCPaymentComplate' => $_POST['WCPaymentComplate']
                    )
            );
            echo 'تنظیمات با موفقیت به روز رسانی شد';
        }
        wp_die();
    }

    /**
     * woocommerce functions
     */
    public function WCcompleted($order_id)
    {

        $wcinfo = get_option('AvanakWoocommerceII');
        if ($wcinfo and isset($wcinfo['WCcompleted']) and ( $wcinfo['WCcompleted'] != 0))
        {
	
			$order = wc_get_order(  $order_id );
            $phone = $order->get_billing_phone();
            $responseSend = $this->WcSendSound($wcinfo['WCcompleted'], $phone);
            // $responseSend = implode($responseSend);
            $note = "پیام صوتی تکمیل سفارش برای کاربر ارسال شد.".$responseSend;
			$order->add_order_note( $note );
        }
    }

    public function WCprocessing($order_id)
    {

        $wcinfo = get_option('AvanakWoocommerceII');
        if ($wcinfo and isset($wcinfo['WCprocessing']) and ( $wcinfo['WCprocessing'] != 0))
        {
	
			$order = wc_get_order(  $order_id );
            $phone = $order->get_billing_phone();
            $responseSend = $this->WcSendSound($wcinfo['WCprocessing'],$phone);
            // $responseSend = implode($responseSend);
            $note = "پیام صوتی تکمیل سفارش برای کاربر ارسال شد.".$responseSend.'=>'.$phone;
			$order->add_order_note( $note );
        }
    }


    public function WCfailed( $order_id)
    {
        $wcinfo = get_option('AvanakWoocommerceII');
        if ($wcinfo and isset($wcinfo['WCfailed']) and ( $wcinfo['WCfailed'] != 0))
        {
            $order = wc_get_order(  $order_id );
            $phone = $order->get_billing_phone();
            $responseSend = $this->WcSendSound($wcinfo['WCfailed'],$phone);
            // $responseSend = implode($responseSend);
            $note = "پیام صوتی لغو سفارش برای کاربر ارسال شد.".$responseSend.'=>'.$phone;
			$order->add_order_note( $note );
        }
    }

    public function WConhold( $order_id)
    {
        $wcinfo = get_option('AvanakWoocommerceII');
        if ($wcinfo and isset($wcinfo['WConhold']) and ( $wcinfo['WConhold'] != 0))
        {
            $order = wc_get_order(  $order_id );
            $phone = $order->get_billing_phone();
            $responseSend = $this->WcSendSound($wcinfo['WConhold'],$phone);
            // $responseSend = implode($responseSend);
            $note = "پیام صوتی سفارش نگه داشته شده برای کاربر ارسال شد.".$responseSend.'=>'.$phone;
			$order->add_order_note( $note );
        }
    }

    public function WCcancelled( $order_id)
    {
        $wcinfo = get_option('AvanakWoocommerceII');
        if ($wcinfo and isset($wcinfo['WCcancelled']) and ( $wcinfo['WCcancelled'] != 0))
        {
            $order = wc_get_order(  $order_id );
            $phone = $order->get_billing_phone();
            $responseSend = $this->WcSendSound($wcinfo['WCcancelled'],$phone);
            $responseSend = implode($responseSend);
            $note = "پیام صوتی سفارش کنسل برای کاربر ارسال شد.".$responseSend.'=>'.$phone;
			$order->add_order_note( $note );
        }
    }

    public function WCPaymentComplate( $order_id)
    {
        $wcinfo = get_option('AvanakWoocommerceII');
        if ($wcinfo and isset($wcinfo['WCPaymentComplate']) and ( $wcinfo['WCPaymentComplate'] != 0))
        {
            $order = wc_get_order(  $order_id );
            $phone = $order->get_billing_phone();
            $responseSend = $this->WcSendSound($wcinfo['WCPaymentComplate'],$phone);
            $note = "پیام صوتی سفارش پرداخت موفق برای کاربر ارسال شد.".$responseSend.'=>'.$phone;
			$order->add_order_note( $note );
        }
    }

    public function WcSendSound($soundID,$mobile)
    {
        try{
            $loginInfo = get_option('AvanakLoginInfoII');
            $curl = curl_init();

            curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://portal.avanak.ir/webservice3.asmx/QuickSend',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => 'userName='.$loginInfo[1].'&password='.$loginInfo[2].'&messageId='.$soundID.'&number='.$mobile.'&vote=false&serverid=0',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),
            ));

            $response = curl_exec($curl);

            curl_close($curl);
            $response = simplexml_load_string($response);
            $returnText = 'Empty Response Avanak';

            switch ($response){
                case -25:
                    $returnText = 'ثبت ارسال سریع غیرفعال میباشد';
                    break;
                case -2:
                    $returnText = 'شماره اشتباه می باشد';
                    break;
                case -3:
                    $returnText = 'عدم موجودی کافی';
                    break;
                case -6:
                    $returnText = 'زمان ارسال غیرمجاز می باشد';
                    break;
                case -8:
                    $returnText = 'کد فایل صوتی اشتباه میباشد';
                    break;
                case -71:
                    $returnText = 'مدت ضبط صدا غیرمجاز میباشد';
                    break;
                case -72:
                    $returnText = 'عدم مجوز ضبط صدا';
                    break;
                case -1:
                    $returnText = 'نام کاربری یا کلمه عبور اشتباه است';
                    break;
                case -20:
                    $returnText = 'خطای ناشناخته';
                    break;
                case -102:
                    $returnText = 'عدم احراز تلفن همراه';
                    break;
                case -104:
                    $returnText = 'پنل کاربری منقضی شده است';
                    break;
                default:
                    $returnText = 'ارسال با موفقیت انجام شد'.$response.' ';
            }
            echo $returnText;
            return $returnText;
        }catch (Exception $e) {
           echo $e;
           return $e;
        }
    }

    public function service()
    {
        $this->addfiles();
        require_once('pages'.DIRECTORY_SEPARATOR.'service.php');
    }

    public function sendotc()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        $result    = $this->connect($loginInfo[0], 'SendOTP', array('userName' => $loginInfo[1], 'password' => $loginInfo[2], 'Length' => 4, 'number' => $_POST['number'], 'serverid' => 0));
        if($this->soupDisable){
            echo 'ماژول soup روی هاست شما فعال نیست و پلاگین کار نمیکند. لطفا با پشتیبانی هاست خود در ارتباط باشید.'; 
        }else{
            echo $result ? $result->SendOTPResult : 'ارسال نشد';
        }
        wp_die();
    }

    public function amount()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        $result    = $this->connect($loginInfo[0], 'GetCredit', array('userName' => $loginInfo[1], 'password' => $loginInfo[2]));
        if($this->soupDisable){
            var_dump($result);
            if($result){
                echo $result;
            }else{
                echo 'ارسال نشد';
            }
        }else{
            echo $result ? $result->GetCreditResult : 'ارسال نشد';
        }
        // echo $result ? $result->GetCreditResult : 'ارسال نشد';
        wp_die();
    }

	// این بخش به صورت موقت غیرفعال است
    // public function users()
    // {
    //     $wcInfo    = get_option('AvanakbirthDayII');
    //     $this->addfiles();
    //     $soundList = $this->selectOptionSoundList($this->getSoundList(), 'messageId', $wcInfo['messageId'], true);
    //     require_once('pages'.DIRECTORY_SEPARATOR.'users.php');
    // }

	// 
    // public function usersAjaxSave()
    // {
    //     if (get_option('AvanakbirthDayII'))
    //     {
    //         update_option('AvanakbirthDayII', array('messageId' => $_POST['messageId']));
    //     }
    //     else
    //     {
    //         add_option('AvanakbirthDayII', array('messageId' => $_POST['messageId']));
    //     }
    //     echo 'ok';
    //     wp_die();
    // }

    public function registerFormInput()
    {
        ?>
        <p>
            <label for="mobile"><?php _e('شماره موبایل') ?><br />
                <input type="mobile" name="mobile" id="mobile" class="input" value="<?php echo (isset($_POST['mobile']) ? esc_attr($_POST['mobile']) : ''); ?>" size="25" tabindex="20" />
            </label>
        </p>
        <!--<p>
            <label for="mobile"><?php _e('تاریخ تولد') ?><br />
                <input type="mobile" name="birthday" id="birthday" class="input" value="<?php echo (isset($_POST['birthday']) ? esc_attr($_POST['birthday']) : ''); ?>" size="25" tabindex="20" />
            </label>
        </p>-->
        <?php
    }

    public function profileFormFields($user)
    {
        ?>
        <table class="form-table">
            <tr>
                <th><label for="mobile">شماره موبایل</label></th>
                <td>
                    <input type="text" name="mobile" id="mobile" value="<?php echo esc_attr(get_the_author_meta('mobile', $user->ID)); ?>" class="regular-text" /><br />
                </td>
            </tr>
            <!--<tr>
                <th><label for="birthday">تاریخ تولد</label></th>
                <td>
                    <input type="text" name="birthday" id="birthday" value="<?php echo esc_attr(get_the_author_meta('birthday', $user->ID)); ?>" class="regular-text" /><br />
                </td>-->
            </tr>
        </table>
        <?php
    }

    // public function avanakcheck_birthdays()
    // {
    //     $ubstatus = get_option('AvanakbirthDayII');
    //     if ($ubstatus)
    //     {
    //         include_once ('pdate.php');
    //         $allUsers = get_users();
    //         foreach ($allUsers as $au)
    //         {
    //             $x = pdate::jdate('Y/m/d');
    //             $y = get_usermeta($au->ID, 'birthday');
    //             $z = get_usermeta($au->ID, 'b'.$x);
    //             if ($x == $y and ! $z)
    //             {
    //                 $loginInfo = get_option('AvanakLoginInfoII');
    //                 if ($loginInfo)
    //                 {
    //                     $this->connect($loginInfo[0], 'QuickSend', array('userName' => $loginInfo[1], 'password' => $loginInfo[2], 'messageId' => $ubstatus['messageId'], 'number' => get_usermeta($au->ID, 'mobile'), 'vote' => false, 'serverid' => $ubstatus[0]));
    //                 }
    //             }
    //         }
    //         $allUsers = null;
    //     }
    // }

    public function speech()
    {
        $this->addfiles();
        require_once('pages'.DIRECTORY_SEPARATOR.'speech.php');
    }

    public function speechAjax()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
			$persistCheck = $_POST['persist'];
			if(isset($persistCheck)){
				$persistCheck = 'true';
			}else{
				$persistCheck = 'false';
			}
            $result = $this->connect($loginInfo[0], 'GenerateTTS', array('userName' => $loginInfo[1], 'password' => $loginInfo[2], 'text' => $_POST['text'], 'title' => $_POST['title'],'persist' => $persistCheck));

            echo json_encode(array($loginInfo[0].'/webservice3/DownloadMessage?username='.$loginInfo[1].'&password='.$loginInfo[2].'&messageid=', $result->GenerateTTSResult));
        }
        else
        {
            echo 'login req';
        }
        wp_die();
    }

    public function speechAjaxId()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
            $result = $this->connect($loginInfo[0], 'GenerateTTS', array('userName' => $loginInfo[1], 'password' => $loginInfo[2], 'text' => $_POST['text'], 'title' => $_POST['title']));
            echo $result->GenerateTTSResult;
        }
        else
        {
            echo 'login req';
        }
        wp_die();
    }

    public function report()
    {
        
    }

    // quick send
    public function quicksend()
    {
        $result = $this->sendMessage($_POST['number'], $_POST['message_id'], $_POST['server'], true);
        echo ($result !== false ? 'پیام شما با موفقیت ارسال شد' : 'خطایی پیش آمده، لطفا مجدد اقدام کنید');
        wp_die();
    }

    // file manager page
    public function filemanager()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
            $this->addfiles();
            require_once('pages'.DIRECTORY_SEPARATOR.'files.php');
        }
        else
        {
            $this->NotLogin();
        }
    }

    // get file list table
    public function filemanagerAjxasList()
    {
        $return    = '<style>
			.status-confirmed-1 td{
				// background:green;
			}
			.status-confirmed-2 td{
				background-color: #ff00002e !important;
			}
			.status-confirmed-3 td{
				background-color: #fbff0042 !important;
			}
			</style><table class="yekan table table-bordred table-striped table-condensed table-hover" border=1>
                                <thead>
                                    <tr>
                                        <th width="50">ردیف</th>
                                        <th>عنوان</th>
                                        <th>طول</th>
                                        <th>هزینه اپراتور خارجی</th>
                                        <th>هزینه داخل شبکه</th>
                                        <th>وضعیت</th>
                                        <th>پخش</th>
                                        <th>ارسال</th>
                                        <th>حذف</th>
                                    </tr>
                                </thead>
                                <tbody>';
        $loginInfo = get_option('AvanakLoginInfoII');
		$serverStatic = 'https://portal.avanak.ir';
        if ($loginInfo)
        {
            $list = $this->connect($serverStatic, 'GetMessages', array(
                'userName' => $loginInfo[1],
                'password' => $loginInfo[2]
            ));
            if ($list)
            {

                if ($list->Message)
                {
                    $counter = 1;
                    foreach ($list->Message as $row)
                    {

						
                        $soungPath = $serverStatic.'/webservice3.asmx/DownloadMessage?username='.$loginInfo[1].'&password='.$loginInfo[2].'&messageid='.$row->Id;
												
						$curl = curl_init();

						curl_setopt_array($curl, array(
						CURLOPT_URL => $soungPath,
						CURLOPT_RETURNTRANSFER => true,
						CURLOPT_ENCODING => '',
						CURLOPT_MAXREDIRS => 10,
						CURLOPT_TIMEOUT => 0,
						CURLOPT_FOLLOWLOCATION => true,
						CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
						CURLOPT_CUSTOMREQUEST => 'GET',
						));

						$response = curl_exec($curl);

						curl_close($curl);
						// echo $response;
						if($row->Confirmed === 0){
							$statusText = 'در انتظار تایید';
						}else if($row->Confirmed === 1){
							$statusText = 'تایید شده';
						}else if($row->Confirmed === 2){
							$statusText = 'رد شده';
						}else if($row->Confirmed === 3){
							$statusText = 'در انتظار تایید تلفنی';
						}

						$responseSound = 'data:audio/mpeg;base64,'.simplexml_load_string($response);

                        $return .= '<tr class="status-confirmed-'.$row->Confirmed.'">
                                                <td>'.$this->pen($counter++).'</td>
                                                <td>'.$row->Title.'</td>
                                                <td>'.$this->pen($row->Lenght).'</td>
                                                <td>'.$this->pen(number_format($row->InternalPrice)).'</td>
                                                <td>'.$this->pen(number_format($row->ExternalPrice)).'</td>
                                                <td>'.$statusText.'</td>
                                                <td class="text-center"><span class="button button-secondary" data-base="'.$responseSound.'" onclick="playSong('."'".$responseSound."'".')">پخش</span></td>
                                                <td class="text-center"><span class="button button-secondary" onclick="quickSendModal('.$row->Id.')">ارسال سریع</span></td>
                                                <td class="text-center"><span class="button button-secondary" onclick="delSong('.$row->Id.')">حذف</span></td>
                                            </tr>';
                    }
                }
              
            }
            else
            {
                $return .= '<tr><td>رکوردی پیدا نشد</td></tr>';
            }
            $return .= '</tbody></table>';
            echo $return;
            wp_die();
        }

        /*
          $wsdl   = 'http://portal.avanak.ir/webservice3.asmx?WSDL';
          $client = new SoapClient($wsdl);
          $param  = array(
          'userName' => 'n_abooie@outlook.com',
          'password' => 'P@ssw0rd123456789'
          );
          try
          {
          $res = $client->GetMessages($param);
          echo '<pre>';
          var_dump($res);
          echo '</pre>';
          }
          catch (Exception $e)
          {
          echo '<pre>';
          var_dump($e->getMessage());
          echo '</pre>';
          }
          /*
          $loginInfo = get_option('AvanakLoginInfoII');
          if ($loginInfo)
          {
          $page = ((isset($_POST['cpage']) and $_POST['cpage'] >= 1) ? $_POST['cpage'] : 1);
          $list = $this->connect($loginInfo[0], 'GetMessagesByPage', array(
          'userName'    => $loginInfo[1],
          'password'    => $loginInfo[2],
          'showPersist' => ($_POST['file_type'] == 1 ? true : false),
          'count'       => 20,
          'currentpage' => 1, //$page,
          'order'       => 'desc'
          ));

          $return  = '<table class="yekan table table-bordred table-striped table-condensed table-hover" border=1>
          <thead>
          <tr>
          <th width="50">ردیف</th>
          <th>عنوان</th>
          <th>طول</th>
          <th>هزینه اپراتور خارجی</th>
          <th>هزینه داخل شبکه</th>
          <th>پخش</th>
          <th>ارسال</th>
          <th>حذف</th>
          </tr>
          </thead>
          <tbody>';
          var_dump($list->GetMessagesByPageResult);
          $counter = $page != 1 ? ((($page - 1) * 20) + 1) : 1;
          if (isset($list->GetMessagesByPageResult->Messages->Message))
          {
          foreach ($list->GetMessagesByPageResult->Messages->Message as $song)
          {
          $soungPath = $loginInfo[0].'/webservice3/DownloadMessage?username='.$loginInfo[1].'&password='.$loginInfo[2].'&messageid='.$song->Id;
          $return    .= '<tr>
          <td>'.$this->pen($counter++).'</td>
          <td>'.$song->Title.'</td>
          <td>'.$song->Lenght.'</td>
          <td>'.$song->InternalPrice.'</td>
          <td>'.$song->ExternalPrice.'</td>
          <td class="text-center"><span class="button button-secondary" onclick="playSong('."'".$soungPath."'".')">پخش</span></td>
          <td class="text-center"><span class="button button-secondary" onclick="quickSendModal('.$song->Id.')">ارسال سریع</span></td>
          <td class="text-center"><span class="button button-secondary" onclick="delSong('.$song->Id.')">حذف</span></td>
          </tr>';
          }
          }
          $prv    = ($page == 1 ? 0 : $page - 1);
          $return .= '<tr><td colspan="8"><span class="button" onclick="avanakFileList('.($prv).')">قبلی</span> <span class="button" onclick="avanakFileList('.($page + 1).')">بعدی</span></td></tr>';
          $return .= '<tbody></table>';
          }
          else
          {
          $return = '<p>login need</p>';
          }
          echo $return;

          wp_die();
         */
    }

    // delete song from server
    public function filemanagerajaxDelete()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
            $result = $this->connect($loginInfo[0], 'DeleteMessage', array('userName' => $loginInfo[1], 'password' => $loginInfo[2], 'messageId' => $_POST['file_id']));
            // return $result->DeleteMessageResult ?true: false;
			if($result->DeleteMessageResult){
				return wp_send_json($result);
			}else{
				return false;
			}
			
        }
        else
        {
            return false;
        }
		wp_die();
    }

    // upload file to serevr
    public function filemanagerajaxUpload()
    {
        if (isset($_FILES['file']) and isset($_FILES['file']['tmp_name']) and $_POST['title'])
        {
            $loginInfo = get_option('AvanakLoginInfoII');
			$staticSource = 'https://portal.avanak.ir/';
			$persist = false;
			if(isset($_POST['persist'])){
				$persist = "true";
			}else{
				$persist = "false";
			}

            if ($loginInfo and $loginInfo !== false)
            {
                $param  = array(
					'userName' => $loginInfo[1],
					'password' => $loginInfo[2],
					'title' => $_POST['title'],
					'file' => file_get_contents($_FILES['file']['tmp_name']),
					'Persist'=>$persist
					);
                $result = $this->connect($loginInfo[0], 'UploadMessage', $param);
                switch ($result)
                {
                    case -1:
                        echo 'login req';
                        break;
                    case -10:
                        echo 'فرمت نامناسب';
                        break;
                    case -20:
                        echo 'خطای ناشناخته';
                        break;
                    case -30:
                        echo 'اشکال در آپلود';
                        break;
                    default:
						if($result->UploadMessageResult){
							$UploadId = $result->UploadMessageResult;
							echo 'اپلود با موفقیت انجام شد.-شماره فایل صوتی : '.$UploadId;
						}else{
							echo 'اپلود با خطا مواجه شد لطفا با اوانک در ارتباط باشید';
						}
                        break;
                }
                wp_die();
            }
        }else{
			echo 'پارامتر های ارسالی نامعتبر یا خالی هستند';
		}
        wp_die();
    }

    // download song from server
    public function filemanagerajaxDownload()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
            $result = $this->connect($loginInfo[0], 'DownloadMessage', array('userName' => $loginInfo[1], 'password' => $loginInfo[2], 'messageId' => $_POST['file_id']));
            header('Content-Type: audio/x-wav, audio/wav');
            echo $result->DownloadMessageResult ?: false;
        }
        else
        {
            return false;
        }
    }

    public function contactus()
    {
        
    }

    public function help()
    {
        $this->addfiles();
        require_once('pages'.DIRECTORY_SEPARATOR.'help.php');
    }

    public function addfiles()
    {
        wp_enqueue_script('jqueryself', plugin_dir_url(__FILE__).'style/jquery.js');
        wp_enqueue_script('jquery-ui', plugin_dir_url(__FILE__).'style/jquery-ui.min.js');
        wp_enqueue_script('form', plugin_dir_url(__FILE__).'style/jquery.form.min.js', array('jquery'), 1, true);
        wp_enqueue_style('boxicon', plugin_dir_url(__FILE__).'style/icons/style.css', array(), 1, true);

        require_once('style.php');
    }

    public function NotLogin()
    {
        require_once('style.php');
        require_once('pages'.DIRECTORY_SEPARATOR.'login.php');
    }

    public function getoptioninfo()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo and $loginInfo !== false)
        {
            $this->options = $loginInfo;
            return true;
        }
        return false;
    }

    public function songList($login)
    {
        $list = $this->connect($login[0], 'GetMessages', array('userName' => $login[1], 'password' => $login[2]));
        if ($list)
        {
            $return = array();
            foreach ($list->GetMessagesResult->Message as $row)
            {
                $return[$row->Id] = $row->Title;
            }
            return $return;
        }
        else
        {
            return false;
        }
    }

    public function SoundSelectList($selectID = false, $empty = false, $name = 'messageID')
    {

        $return    = '';
        $loginInfo = get_option('AvanakLoginInfoII');
        if (false !== $loginInfo)
        {
            $list = $this->connect($loginInfo[0], 'GetMessages', array('userName' => $loginInfo[1], 'password' => $loginInfo[2]));
            if ($list)
            {
                $return = '<select id="'.$name.'" name="'.$name.'" class="yekan fw">';
                if ($empty === true)
                {
                    $return .= '<option value="0">بدون صدا</option>';
                }
                foreach ($list->GetMessagesResult->Message as $row)
                {
                    $select = '';
                    if ($selectID and $selectID == $row->Id)
                    {
                        $select = 'selected="selected"';
                    }
                    $return .= '<option value="'.$row->Id.'" '.$select.'>'.$row->Title.'</option>';
                }
                $return .= '</select>';
            }
            else
            {
                $return = '<p class="yekan" style="font-size:12px;color:red">فایل صدایی برای شما در سرور موجود نیست</p>';
            }
        }
        else
        {
            $return = '<p class="yekan" style="font-size:12px;color:red">اطلاعات ورود به سرور اشتباه است، لطفا به بخش <a href="'.admin_url('admin.php?page=wp-callsound-setting').'">مدیریت حساب</a> مراجعه کنید</p>';
        }
        return $return;
    }

    public function selectOptionSoundList($sounds, $name, $select = null, $is_empty = false)
    {
        if ($sounds !== false)
        {
            $return = '<select name="'.$name.'" id="'.$name.'" class="yekan fw">';
            if ($is_empty === true)
            {
                $return .= '<option value="0">انتخاب کنید</option>';
            }
            foreach ($sounds as $id => $value)
            {
                $selected = '';
                if ($select and $select == $id)
                {
                    $selected = ' selected="select"';
                }

				$disabled = '';
				$disabledLabelText = '';
				if($value['status'] === 1){
					$disabled = 'data-verify="1"';
				}else{
					if($value['status'] === 2){
						$disabledLabelText = '(صوت تایید نشده)';
					}else{
						$disabledLabelText = '(در انتظار تایید)';
					}
					$disabled = 'disabled';
				}

                $return .= '<option value="'.$id.'"'.$selected.' data-confirm="'.$value['status'].'" '.$disabled.'>'.$value['title'].''.$disabledLabelText.'</option>';
            }
            $return .= '</select>';
            return $return;
        }
        else
        {
            return '<p>فایلی موجود نیست</p>';
        }
    }

	public function oldSocketCurl($path,$username,$password){

		$curl = curl_init();

		curl_setopt_array($curl, array(
		CURLOPT_URL => 'https://portal.avanak.ir/webservice3.asmx/'+$path,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => '',
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 0,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => 'POST',
		CURLOPT_POSTFIELDS => 'userName='.$username.'&password='.$password.'',
		CURLOPT_HTTPHEADER => array(
			'Content-Type: application/x-www-form-urlencoded'
		),
		));

		$response = curl_exec($curl);

		curl_close($curl);
		return $response;

	}

    public function getSoundList()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if (false !== $loginInfo)
        {
            $list = $this->connect($loginInfo[0], 'GetMessages', array('userName' => $loginInfo[1], 'password' => $loginInfo[2]));
            if ($list)
            {
                $return = array();
                foreach ($list->GetMessagesResult->Message as $row)
                {
					
					if($row->Confirmed === 1){
                    	$return[$row->Id] = array('title'=>$row->Title,'status'=>1);
					}else{
						$return[$row->Id] = array('title'=>$row->Title,'status'=>0);
					}
                }
                return $return;
            }
            return false;
        }
        return false;
    }

    protected function connect($server, $fnc, $param)
    {
        
        $wsdl_old = $server.'/webservice3.asmx/'.$fnc;
        $wsdl = $server.'/webservice3.asmx?wsdl';
        
        if(class_exists("SoapClient")){
            try
            {
                $client = new SoapClient($wsdl);
                // $client = new nusoap_client($wsdl);
                try
                {
                    return $client->$fnc($param);
                    // echo $wsdl;
                    // return $client->call($param);
                    
                }
                catch (Exception $e)
                {
                    return false;
                }
            }
            catch (Exception $e)
            {
                return false;
            }
        }else{
            add_action( 'admin_notices', array($this,'php_error_soup') );
            $curl = curl_init();
            $parametrUrl = http_build_query($param);
            curl_setopt_array($curl, array(
            CURLOPT_URL =>  $wsdl_old,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 2,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $parametrUrl,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded'
            ),
            ));

            $response = curl_exec($curl);
            if (strpos($response, '<?xml') === 0) {
                if($fnc === 'GetCredit'){
                    return $this->getCreditRest($response);
                }

                
            } else {
                return false;
            }
            // echo 'bodyyyyy====';
            // var_dump($body);

        }
    }

    private function php_error_soup(){
        echo 'به دلیل ';
    }

    // Without Soap Functions To WSDL Format
    private function getCreditRest($result){
        if($result){
            $xml = simplexml_load_string($result);
            $credit_value = json_encode($xml);
            $credit_value = json_decode($xml);
            $response_array = '{
                "GetCreditResult": '.$credit_value.'
            }';
            $response_array = json_decode($response_array);

            // json_decode($response_array,true);
            return $response_array;
        }else{
            return false;
        }
    }


    public function pen($str, $mod = TRUE)
    {
        $num_a = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $key_a = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
        return ($mod) ? str_ireplace($num_a, $key_a, $str) : str_ireplace($key_a, $num_a, $str);
    }

    // set return as bool
    // next version
    public function sendMessage($number, $message_id, $service_id, $is_ajax = false, $return = 'bool')
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
            $result = $this->connect($loginInfo[0], 'QuickSend', array('userName' => $loginInfo[1], 'password' => $loginInfo[2], 'messageId' => $message_id, 'number' => $number, 'vote' => false, 'serverid' => $service_id));
            $return = $result->QuickSendResult != -1 ? 'ok' : 'no';
        }
        else
        {
            $return = '<p>login need</p>';
        }
        if ($is_ajax)
        {
            if ($return != 'bool')
            {
                echo $return;
            }
            else
            {
                echo $return;
            }
        }
        else
        {
            echo $return;
        }
        wp_die();
    }

    public function dialler()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
            $this->addfiles();
            $wcInfo     = get_option('AvanakDiallerMessageII');
            if($this->soupDisable){
                $selectList = $this->selectOptionSoundList([], 'messageId', $wcInfo['messageId'], true);
            }else{
                $selectList = $this->selectOptionSoundList($this->getSoundList(), 'messageId', $wcInfo['messageId'], true);
                $serverId   = $wcInfo['serverId'];
            }
            require_once('pages'.DIRECTORY_SEPARATOR.'diallerAdmin.php');
        }
        else
        {
            $this->NotLogin();
        }
    }

    public function dillerSave()
    {
        if (get_option('AvanakDiallerMessageII'))
        {
            update_option('AvanakDiallerMessageII', array('messageId' => $_POST['messageId'], 'serverId' => $_POST['serverId']));
        }
        else
        {
            add_option('AvanakDiallerMessageII', array('messageId' => $_POST['messageId'], 'serverId' => $_POST['serverId']));
        }
        echo 'ok';
        wp_die();
    }

    public function diallerForm()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
            ob_start();
            $output = ob_get_contents();
            //require('pages'.DIRECTORY_SEPARATOR.'dialler.php');

            wp_reset_postdata();
            echo $output;
            return ob_get_clean();
        }
        else
        {
            $this->NotLogin();
        }
    }

    public function dillerAction()
    {
        $loginInfo = get_option('AvanakLoginInfoII');
        if ($loginInfo)
        {
            // send to number
            $messageID = get_option('AvanakDiallerMessageII');
            if ($messageID and isset($messageID['messageId']))
            {
                $result = $this->sendMessage($this->pen($_POST['mobile'], false), $messageID['messageId'], $messageID['serverId'], true, 'notboll');
                echo ($result == 'ok' ? 'ok' : 'خطا در ارسال');
            }
            else
            {
                echo 'صدایی برای ارسال انتخاب نشده است';
            }
            wp_die();
        }
        else
        {
            $this->NotLogin();
        }
		wp_die();
    }

}

$avanakClass = null;
