<?php namespace App;

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

define('ZOKO', 1);
define('NARAD', 2);

/**
 * Created by PhpStorm.
 * User: sunil khorwal
 * Date: 27/11/19
 * Time: 1:52 PM
 */
class WhatsApp extends Templates
{
    private static $SALES_INBOX_ID = ['sales' => 4.0, 'payment' => 1.0];
    private $provider = NARAD;
    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 setProvider(){
        if ($this->request->get('message_type') != 'payment' && $this->provider == NARAD) {

            $payload = [
                'type' => 'outgoing',
                'name' => $this->getSenderName(),
                'chat_id' => 'Narad',//$this->data['templateId'],
                'sender_id' => $this->data['recipient'],
                'phone_number' => $this->data['recipient'],
                'email' => null,
                'message' => $this->data['message'],
                'timestamp' => Carbon::now()->timestamp,
                'inbox' => [
                    'id' => self::$SALES_INBOX_ID[$this->request->get('message_type')] ?? self::$SALES_INBOX_ID['sales']
                ]
            ];

//            if($this->request->has('templateType')) {
//                $attachement = [
//                    "data_url" => isset($this->request->get('templateType')[0])
//                ];
//
//
//                $payload['attachments'] = [
//                    $attachement
//                ];
//            }

            $this->data = $payload;
            $this->endpoint = _env('NARAD_HOST');
            $this->currentAPI['link'] = _env('NARAD_MESSAGE_URL');
            $this->currentAPI['method'] = 'POST';
        }
    }

    private function getSenderName(){
        $senderName = $this->data['recipient'];
        if (isset($this->data['id_type']) && $this->data['id_type'] == 'application_id' && isset($this->data['id'])){
            $application = ConsumerApplication::where('id', $this->data['id'])->first(['name', 'co_applicant_name', 'mobile_number', 'co_applicant_mobile_number']);
            if(isset($application->id)){
                if ($this->data['recipient'] == $application->mobile_number){
                    $senderName = $application->name;
                }else if($this->data['recipient'] == $application->co_applicant_mobile_number){
                    $senderName = $application->co_applicant_name;
                }else{
                    $senderName = 'Loan Id: '.$this->data['id'];
                }
            }
        }

        return $senderName;
    }

    private function init(){

        $this->setProvider();

        $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,
                "CF_ACCESS_KEY:"._env('NARAD_CF_ACCESS_KEY'),
                "CF_SECRET_KEY:"._env('NARAD_CF_SECRET_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;
    }
}
