<?php

namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Http\Client;
use Zend\Http\Client\Adapter\Curl;
use Zend\Http\Client as HttpClient;
use Zend\Http\Request;
use Zend\Stdlib\Parameters;
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;
use Zend\Mail\Transport\SmtpOptions;
use Zend\Mail\Transport\Exception;
use Zend\Debug\Debug;
use Zend\Json\Json;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver\TemplateMapResolver;
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Session\Container;

/**
 * Description of RestAPIClientController
 *
 * @author hello42
 */
class RestAPIClientController extends AbstractActionController {

    public $apiUrl = '';
    public $apiAdminUrl = '';

    public function apiUrl() {
        return $this->config()->getConfig()->api->url;
    }

    public function apiAdminUrl() {
        return $this->config()->getConfig()->api->adminUrl;
    }

    public function get($url) {
        return $this->dispatchRequestAndDecodeResponse($url, "GET");
    }

    public function post($url, $data) {
        return $this->dispatchRequestAndDecodeResponse($url, "POST", $data);
    }

    public function put($url, $data) {
        return $this->dispatchRequestAndDecodeResponse($url, "PUT", $data);
    }

    public function delete($url) {
        return $this->dispatchRequestAndDecodeResponse($url, "DELETE");
    }

    protected function dispatchRequestAndDecodeResponse($url, $method, $data = null) {
        $sessionUser = new Container('userlogin');
        $token =  isset($sessionUser->user_token)?$sessionUser->user_token:'' ;
        $request = new Request();
        $request->getHeaders()->addHeaders(array(
            'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
            //'authorization'=>'82a9b0be694c1b4d80815564a27611a834df6399df3cf3141375c0dd5adcf517'
            'authorization'=>''
        ));     
        $request->setUri($url);
        $queryString = $request->getUri($url)->getQuery();
        
        if($token!=''){
            if($method=='GET' && (isset($queryString) && $queryString!='')){
                $url = $url."&access_token=".$token;
            }elseif($method=='POST' && $queryString!=''){
                $url = $url."&access_token=".$token;
            }
            else{
                $url = $url."?access_token=".$token;
            }
        }
        $request->setUri($url);
        $request->setMethod($method);
        if ($data) {
            $request->setPost(new Parameters($data));
        }
        $httpClient = new HttpClient();
        $httpClient->setOptions(array('timeout'=>60));
        $response = $httpClient->dispatch($request);        

        //echo "<pre>";print_r($response->getStatusCode());
        //echo "<pre>";print_r($response->getContent()); exit;
        # should interogate response status, throwing appropiate exceptions for error codes
        //return json_decode($response->getBody(), true);
        return $response;
    }

    public function sendMail($data = array()) {
        $id = $this->config()->getConfig()->company->companyId;
        $compJsonData = $this->getCompanySetupDetails($id);

        $params = [
            'company_info' => $compJsonData,
            'user_info' => $data,
        ];

        $template = $this->getEmailTemplate($params);
        $fromName = $compJsonData['site_title'];
        $fromEmail = $compJsonData['global_email'];
        $email = $data['user_email'];
        $subject = "Welcome to ".' '.$compJsonData['com_name'];
        $transport = new SmtpTransport();
        $options = new SmtpOptions(array(
            'host' => $this->config()->getConfig()->smtpMail->host,
            'connection_class' => 'login',
            'connection_config' => array(
                'tls' => 'tls',
                'username' => $this->config()->getConfig()->smtpMail->username,
                'password' => $this->config()->getConfig()->smtpMail->password,
            ),
            'port' => $this->config()->getConfig()->smtpMail->port,
        ));

        $html = new MimePart($template);
        $html->type = "text/html";
        $body = new MimeMessage();
        //$body->addPart($html);
        $body->setParts(array($html,));

        $mail = new Message();
        $mail->setBody($body);
        $mail->setFrom($fromEmail, $fromName);
        $mail->setTo($email);
        $mail->setSubject($subject);
        $transport->setOptions($options);
        $sent = true;
        try {
            $transport->send($mail);
        } catch (\Zend\Mail\Transport\Exception\ExceptionInterface $e) {
            $sent = false;
        }
        if ($sent) {
            $status = "success";
        } elseif (!$sent) {
            $status = "fail";
        }
        return $status;
    }

    public function getCompanySetupDetails($id) {
        $url = $this->apiUrl() . "/company-setup/" . $id;
        $resp = $this->get($url);
        $compJsonData = Json::decode($resp->getBody(), true);
        return $compJsonData;
    }

    public function getCompanyWaterMarkDetails($id) {
        $val = '{"where": {"company_id": "' . $id . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/company-watermark-setting/?filter=" . $val;
        $resp = $this->get($url);
        $compJsonData = Json::decode($resp->getBody(), true);
        return $compJsonData;
    }

    public function getThirdPartyDetails($id) {
        $val = '{"where": {"company_id": "' . $id . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/company-api-configuration/?filter=" . $val;
        $resp = $this->get($url);
        $compJsonData = Json::decode($resp->getBody(), true);
        return $compJsonData;
    }

    public function getEmailTemplate($arrData = array()) {
        //Debug::dump($arrData); exit;
        $compData = $arrData['company_info'];
        $templateName = $arrData['user_info']['template_name'];
        $userInfo = $arrData['user_info'];

        $view = new PhpRenderer();
        $resolver = new TemplateMapResolver();

        $header = $resolver->setMap(array(
            'mailTemplate' => __DIR__ . '/../../view/application/emailtemplate/' . $templateName . '.phtml',
        ));

        $view->setResolver($resolver);
        $viewModel = new ViewModel(['user_info' => $userInfo, 'comp_info' => $compData]);
        $viewModel->setTemplate('mailTemplate');
        $template = $view->render($viewModel);
        return $template;
    }

    public function sendSMS($arrData = array()) {
        $templateName = $arrData['template_name'];
        $mobileNumber = $arrData['mobile'];
        $userName = $arrData['user_name'];

        $id = $this->config()->getConfig()->company->companyId;
        $compJsonData = $this->getCompanySetupDetails($id);

        $template = $this->getSmsTemplate($templateName);
        //echo '<pre>';print_r($template);die();
        if ($templateName == "acc_verify_code") {
            $code = isset($arrData['otp'])?$arrData['otp']:'';
            $array = explode('<variable>', $template);
            $array[0] = $array[0] . $userName;
            $array[1] = $array[1] . $code;
            $array[2] = $compJsonData['site_title'];
            $array[3] = $compJsonData['site_name'];
            $message = urlencode(implode("", $array));
        } else if ($templateName == "refer_earn") {
            $array = explode('<variable>', $template);
            $array[0] = $array[0] . $userName;
            $array[1] = $array[1] . $arrData['referral_key'];
            $array[2] = $array[2] . $arrData['referral_amt'];
            $array[3] = $array[3] . $compJsonData['site_name'];
            $message = urlencode(implode("", $array));
        } else if ($templateName == "booking") {
            $array = explode('<variable>', $template);
            $array[0] = $array[0] . $userName;
            $array[1] = $array[1] . $arrData['booking_ref_no'];
            $array[2] = $array[2] . $arrData['pickup_time'];
            $array[3] = $array[3] . $arrData['estimated_price'];
            $array[4] = $array[4] . $compJsonData['site_name'];
            $message = urlencode(implode("", $array));
        }
        $apiId = $this->config()->getConfig()->smsApi->apiId;
        $url = $this->apiUrl() . "/sms_apis/" . $apiId;
        $resp = $this->get($url);
        $sms_api = Json::decode($resp->getBody(), true);

//Debug::dump($sms_api); //exit;

        $api_base_uri = $sms_api['api_base_uri'];
        $api_username = $sms_api['api_username'];
        $api_password = $sms_api['api_password'];
        $api_sender_id = $sms_api['api_sender_id'];
        $url = "$api_base_uri?username=$api_username&password=$api_password&to=91$mobileNumber&from=$api_sender_id&udh=&text=$message&dlr-mask=19&dlr-url";
        //die;
        /* $curl_handle=curl_init();
          curl_setopt($curl_handle,CURLOPT_URL,$url);
          curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
          curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
          $result = curl_exec($curl_handle);
          if ($result === FALSE) {
          die('Curl failed: ' . curl_error($curl_handle));
          }
          curl_close($curl_handle);
          echo $result; */
        $client = new Client($url, array(
            'maxredirects' => 0,
            'timeout' => 30
        ));
        $client->setAdapter(Curl::class);
        // Performing a POST request
        $client->setMethod('POST');
        //Set data
        $response = $client->send();
        if ($response->isSuccess()) {
            $resp = $response->getBody();
        } else {
            $resp = "Request is failed";
        }
        return $resp;
    }

    public function getSmsTemplate($templateName) {
        $val = '{"where": {"msg_sku": "' . $templateName . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/sms_template/?filter=" . $val;
        $resp = $this->get($url);
        $smsTemplateData = Json::decode($resp->getBody(), true);

        $template = $smsTemplateData[0]['message'];
        return $template;
    }

    /*     * *******************************************************************
      Purpose            : get image height.
      Parameters         : null
      Returns            : height
     * ********************************************************************* */

    public function getHeight($image) {
        $sizes = getimagesize($image);
        $height = $sizes[1];
        return $height;
    }

    /*     * *******************************************************************
      Purpose            : get image width.
      Parameters         : null
      Returns            : width
     * ********************************************************************* */

    public function getWidth($image) {
        $sizes = getimagesize($image);
        $width = $sizes[0];
        return $width;
    }

    public function resizeImage($image, $width, $height, $scale) {
        $newImageWidth = ceil($width * $scale);
        $newImageHeight = ceil($height * $scale);
        $newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
        $source = imagecreatefromjpeg($image);
        imagecopyresampled($newImage, $source, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $width, $height);
        imagejpeg($newImage, $image, 90);
        chmod($image, 0777);
        return $image;
    }


    public function generateOtp() {
        $alphabet = '1234567890';
        $pcode = array(); //remember to declare $pcode as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 5; $i++) {
            $n = rand(0, $alphaLength);
            $pcode[] = $alphabet[$n];
        }
        return $act = implode($pcode);
        //$act = '12345';
        return $act;
    }

}