<?php
namespace Leadlion\Web2Sms\Helper;

use \Magento\Framework\App\Helper\AbstractHelper;

class Web2Sms extends AbstractHelper
{
	const SMS_ENABLED_KEY   = 'sendsms_settings/sendsms/sendsms_settings_active';
    const SMS_API_KEY       = 'sendsms_settings/sendsms/sendsms_settings_apikey';
    const SMS_SECRET_KEY    = 'sendsms_settings/sendsms/sendsms_settings_secretkey';
    const SMS_SENDER_PHONE  = 'sendsms_settings/sendsms/sendsms_settings_senderphone';
    const SMS_ACC_MODE  = 'sendsms_settings/sendsms/sendsms_settings_mode';
    const SMS_RECEIPT  = 'sendsms_settings/sendsms/sendsms_settings_recipient';
    const SMS_ACC_TYPE  = 'sendsms_settings/sendsms/sendsms_settings_acctype';

    protected $scopeConfig;
    protected $storeDate;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Stdlib\DateTime\DateTime $date
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->storeDate = $date;
    }

    /**
     * @param $phone
     * @param $message
     * @param $type
    */
    public function sendSMS($phone, $message, $type = 'order')
    {
		$sendSMSEnabled = $this->scopeConfig->getValue(self::SMS_ENABLED_KEY,\Magento\Store\Model\ScopeInterface::SCOPE_STORE);

        if (!$sendSMSEnabled) {
            return false;
        }

		if (empty($phone) || empty($message)) {
            return false;
        }
		
        $smsApiKey = $this->scopeConfig->getValue(self::SMS_API_KEY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        $smsSecretKey = $this->scopeConfig->getValue(self::SMS_SECRET_KEY, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        $smsAccType = $this->scopeConfig->getValue(self::SMS_ACC_TYPE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        $smsAccMode = $this->scopeConfig->getValue(self::SMS_ACC_MODE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        $smsReceipt = $this->scopeConfig->getValue(self::SMS_RECEIPT, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
		
		$accTypeUrl = '/'.$smsAccType.'/message';
		$curlurl = 'https://www.web2sms.ro'.$accTypeUrl;

        if (!$smsApiKey || !$smsSecretKey) {
            return false;
        }
		
		if($smsAccMode){
			$phone = $smsReceipt;
		}
		
		$phone = $this->validatePhone($phone);
		
		if(!$phone){
			return false;
		}

        $apiKey = $smsApiKey;
        $secret = $smsSecretKey;
        $nonce = time();
        $method = "POST";
        $url = $accTypeUrl;
        $sender = $this->scopeConfig->getValue(self::SMS_SENDER_PHONE, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
        $recipient = $phone;
        $message = $message;
        $visibleMessage = "";
        $scheduleDate = ''; //Format timestamp
        $validityDate = ''; //Format timestamp
        $callbackUrl = '';
        $string = $apiKey . $nonce . $method . $url . $sender .
            $recipient . $message . $visibleMessage . $scheduleDate .
            $validityDate . $callbackUrl . $secret;

        $signature = hash('sha512', $string);
        $data = array(
            "apiKey" => $apiKey,
            "sender" => $sender,
            "recipient" => $recipient,
            "message" => $message,
            "scheduleDatetime" => $scheduleDate,
            "validityDatetime" => $validityDate,
            "callbackUrl" => $callbackUrl,
            "userData" => "",
            "visibleMessage" => $visibleMessage,
            "nonce" => $nonce);
        $ch = curl_init($curlurl);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":" . $signature);
        $header = array();
        $header[] = 'Content-type: application/json';
        $header[] = 'Content-length: ' . strlen(json_encode($data));
		//file_put_contents(BP . '/var/log/we2sms.log', __FILE__ . ' > ' .__LINE__ . $message . PHP_EOL,FILE_APPEND);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $postResult = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($postResult === false || $httpcode > 400)
        {
            return false;
        }
        return true;
    }

    /**
     * @param $phone
     * @return string
     */
    public function validatePhone($phone)
    {
        $phone = preg_replace('/\D/', '', $phone);
        if (substr($phone, 0, 2) == '07' && strlen($phone) == 10) {
            $phone = $phone;
        } else {
            $phone = false;
        }
        return $phone;
    }

    /**
     * @param $string
     * @return string
     */
    public function cleanDiacritice($string)
    {
        $bad = array(
            "\xC4\x82",
            "\xC4\x83",
            "\xC3\x82",
            "\xC3\xA2",
            "\xC3\x8E",
            "\xC3\xAE",
            "\xC8\x98",
            "\xC8\x99",
            "\xC8\x9A",
            "\xC8\x9B",
            "\xC5\x9E",
            "\xC5\x9F",
            "\xC5\xA2",
            "\xC5\xA3",
            "\xC3\xA3",
            "\xC2\xAD",
            "\xe2\x80\x93");
        $cleanLetters = array("A", "a", "A", "a", "I", "i", "S", "s", "T", "t", "S", "s", "T", "t", "a", " ", "-");
        return str_replace($bad, $cleanLetters, $string);
    }
}
