<?php namespace App;

use Carbon\Carbon;
use Illuminate\Http\Request;

/**
 * Created by PhpStorm.
 * User: sunil khorwal
 * Date: 27/11/19
 * Time: 1:52 PM
 */
class WhatsApp extends Templates
{
    private $endpoint = 'https://chat.zoko.io/v2';
    private $API = [
        'message' => ['link' => '/message', 'method' => 'POST'],
        'templates' => ['link' => '/account/templates', 'method' => 'GET'],
    ];
    private $currentAPI = array();
    private $error = array();
    private $response = array();
    private $data = array();
    private $templateLanguage = 'en';

    /**
     * WhatsApp constructor.
     *
     */

    public function sendMessage(){

        $this->data = [
            "channel" => "whatsapp",
            "recipient" => $this->request->get('to'),
            "group" => false,
            "type" => $this->request->has('templateType') && !empty($this->request->get('templateType')) ? $this->request->get('templateType') : 'template',
            "message" => $this->request->get('messageString'),
            "caption" => $this->request->get('caption'),
            "templateId" => $this->templateId,
            "templateArgs" => $this->templateArgs,
            "templateLanguage" => $this->request->has('templateLanguage') ? $this->request->get('templateLanguage') : $this->templateLanguage
        ];

        $this->currentAPI = $this->API['message'];

        $response = $this->init();
        if ($this->request->has('templateTypeSystem') && $this->request->get('templateTypeSystem')) {
            $this->serviceLogs($this->request->get('to'), $this->request->get('templateTypeSystem'), $response);
        }
        return $response;
    }

    public function getMessages(){

        $this->currentAPI = $this->API['templates'];

        return $this->init();
    }

    public function serviceLogs($mobile_number, $payload, $response){
        WhatsappMessages::insert(
            [
                'request_id' => !empty($response->messageId) ? $response->messageId : '',
                'PlatformSenderId' => $mobile_number,
                'message' => $payload['templateId'],
                'payload' => json_encode($payload),
                'type' => 'message:store:system:out',
                'created_at' => Carbon::now()->toDateTimeString(),
                'response' => json_encode($response)
            ]
        );
    }

    private function init(){
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->endpoint.$this->currentAPI['link'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $this->currentAPI['method'],
            CURLOPT_POSTFIELDS => json_encode($this->data),
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json",
                "apikey: ".$this->key,
                "accept: application/json",
                "cache-control: no-cache"
            ),
        ));

        $this->response = curl_exec($curl);
        $this->error = curl_error($curl);

        curl_close($curl);

        // try{
        //     $whatsappFile = fopen(storage_path().'_'.$this->request->get('to')."_whatsapp_".time().".txt", "a") or die("Unable to open file!");
        //     $txt = $this->response;
        //     fwrite($whatsappFile, "\n". $txt);
        //     fclose($whatsappFile);
        // }catch (\Exception $e){

        // }

        if ($this->error)
            return json_decode($this->error);

        if ($this->response)
            return json_decode($this->response);

        return false;
    }
}
