<?php
namespace App\Libs;
use Twilio\Rest\Client;
use Illuminate\Http\Request;
use App\Models\Req;
use App\Models\Members;
class Whatsapp 
{
    public static function getTokens() {
        $data['sid']    = "AC896a51e456ed7ea09e6c69c2633e2d0a";
        $data['token']  = "18458e6208482252a066d3cab7eb7a5a";
        $data['from'] = "whatsapp:+14155238886";
        return $data;
    }
    public static function sendConfirmMessage($phone,$media, $name) {
        $tokens = Whatsapp::getTokens();
        $sid = $tokens['sid'];
        $token = $tokens['token'];
        $twilio = new Client($sid, $token);
        $from = $tokens['from'];
        $x = json_encode(["1"=>"12/1","2"=>"3pm"]);
        $msg = "Thank you ".$name." for your confirmation";
        $message = $twilio->messages
            ->create("whatsapp:{$phone}", // to
                array(
                    "from" => "{$from}",
                    "body" => "{$msg}",
                    "mediaUrl" => [$media]
                    // "mediaUrl" => ['https://images.unsplash.com/photo-1518717758536-85ae29035b6d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80']
                )
            );
            
        return $message->sid;
    }
    public static function sendMessage($phone,$msg = "") {
        $tokens = Whatsapp::getTokens();
        $sid = $tokens['sid'];
        $token = $tokens['token'];
        $twilio = new Client($sid, $token);
        $from = $tokens['from'];
        $x = json_encode(["1"=>"12/1","2"=>"3pm"]);
        $message = $twilio->messages
            ->create("whatsapp:{$phone}", // to
                array(
                    "from" => "{$from}",
                    "contentSid" => "HXb5b62575e6e4ff6129ad7c8efe1f983e",
                    "contentVariables" => "{$x}",
                    "body" => "{$msg}"
                )
            );
        return $message->sid;
    }
    public static function webhook(Request $request) {
        $data = $request->all();
        $jsonContent = json_encode($data, JSON_PRETTY_PRINT);
        $from = $request->input('From');
        $response = strtolower(trim($request->input('Body')));
        $msgid = $request->input('OriginalRepliedMessageSid');
        $l = new Req();
        $l->response = $jsonContent;
        $l->msgid = $msgid;
        $l->body = $response;
        $l->from_num = $from;
        $l->save();
        $out['msgid'] = $msgid;
        $out['response'] = $response;
        return $out;
        
    }
}