<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Twilio\Rest\Client;
use App\Models\Members;
use App\Models\Countries;
use App\Models\Req;
use Carbon\Carbon;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use App\Libs\Whatsapp;
use Storage;
class HomeController extends Controller
{
    public function testQRCode() {
         
        $msgid = strtolower("MMad90223109f5422850d5b0a4be17d89e");
         
        
        return $this->qrCode("Santhosh", "9739955099",$msgid);
    }
    public function qrCode($name, $phone,$msgid) {
        $path = public_path('qrcode/'.$msgid.'-'.time().'.png');
        $qrCode = QrCode::format('png')->size(200)->generate('Name: '. $name.', Phone: '. $phone, $path);
        // $qrCode1 = QrCode::format('svg')->size(200)->generate('A simple example of QR code', $path);
        // $output_file = '/qrcode/' . $msgid . '.png';
        // Storage::disk('public')->put($output_file, $qrCode); //storage/app/public/img/qr-code/img-1557309130.png
        $publicURL = "qrcode/".$msgid."-".time().".png";
        // return url($publicURL);
        return view('qrcode', compact('qrCode')); 
    }
    public function sendMessages() {
        // $rs = Members::where('status','New')->get();
        $rs = Members::get();
        foreach($rs as $row) {
            $ph = $row->country.$row->phone;
            echo "Sending Message to ".$ph."<br>";
            $msgID =Whatsapp::sendMessage($ph);
            $data['msgid'] = $msgID;
            $data['status'] = "Sent";
            $data['send_date'] = Carbon::now();
            Members::where('id', $row['id'])->update($data);
        }
    }
    // public function sendWAMessage($phone) {
    //     $sid    = config('services.twilio.sid');
    //     $token  = config('services.twilio.token');
    //     $from   = config('services.twilio.whatsapp_from');
    //     $sid    = "AC896a51e456ed7ea09e6c69c2633e2d0a";
    //     $token  = "18458e6208482252a066d3cab7eb7a5a";
    //     $twilio = new Client($sid, $token);
    //     $x = json_encode(["1"=>"12/1","2"=>"3pm"]);
    //     $message = $twilio->messages
    //         ->create("whatsapp:{$phone}", // to
    //             array(
    //                 "from" => "whatsapp:+14155238886",
    //                 "contentSid" => "HXb5b62575e6e4ff6129ad7c8efe1f983e",
    //                 "contentVariables" => "{$x}",
    //                 "body" => "Your Message"
    //             )
    //         );
    //         print($message->sid);
    //     return $message->sid;
    // }
//             die();
//  $token="d8ccac73f7cdef5bb2e9d0fd9badc7f1";
//  $from = "whatsapp:+18303568380";
//         $twilio = new Client($sid, $token);
//         $toNumber = "+919739955099";
          

// echo $x;

//         $twilio->messages->create(
//             "whatsapp:{$toNumber}",
//             [
//                 "from" => $from,
//                 "contentSid" => "HXb5b62575e6e4ff6129ad7c8efe1f983e",
//                 "contentVariables" => $x,
//           "body" => "Your Message"
//             ]
//         );

//         return response()->json([
//             'status' => 'Message sent successfully'
//         ]);
//     }
    public function index() {
        
        $data = Members::get();
         
        return $this->listForm($data);
    }
    public function listForm($data) {
        $page_data['data'] = $data;
        $stats['total'] = array("color"=>"red","label"=>"Total Contacts","val"=> Members::count());
        $stats['sent'] = array("color"=>"orange","label"=>"Message Sent","val"=> Members::where('status','Sent')->count());
        $stats['attending'] = array("color"=>"#6DC912","label"=>"Attending","val"=> Members::where('attending',10)->count());
        $stats['not_attending'] = array("color"=>"#7AEBF5","label"=>"Not Attending","val"=> Members::where('attending',20)->count());
        $stats['not_confirmed'] = array("color"=>"#C9A712","label"=>"Not Confirmed","val"=> Members::where('status','Sent')->where('attending',0)->count());
        $page_data['stats'] = $stats;
        return view('members',$page_data);
    }
    public function membersFilter($slug) {
        $data = Members::get();
        if($slug == "sent") $data = Members::where('status','Sent')->get();
        if($slug == "attending") $data = Members::where('attending',10)->get();
        if($slug == "not_attending") $data = Members::where('attending',20)->get();
        if($slug == "not_confirmed") $data = Members::where('status','Sent')->where('attending',0)->get();
        return $this->listForm($data);
    }
    public function membersEdit($id) {
        $rs = Members::where('id', $id)->first();
        if($rs) {
            $data['id'] = $id;
            $data['salutation'] = $rs->salutation;
            $data['name'] = $rs->name;
            $data['country'] = $rs->country;
            $data['phone'] = $rs->phone;
            return $this->memberForm($data, "", $id, "EDIT");
        } else {
            return redirect("/");
        }
    }
    public function membersAdd() {
        $data['id'] = 0;
        $data['salutation'] = $data['name'] = $data['phone'] = $data['country'] = "";
        return $this->memberForm($data, "", "","CREATE");
    }
    public function memberForm($data, $msg,$id,$mode) {
        $params['mode'] = $mode;
        $params['btn'] = $mode == "CREATE" ? "Add New Contact" : "Update Contact";
        $params['id'] = $id;
        $params['lstSal'] = array("Mr","Mrs","Miss","Ms","Dr","Eng","");
        $params['lstCountry'] = Countries::getList();
        $params['message'] = $msg;
        $page_data['data'] = $data;
        $page_data['params'] = $params;
        return view('members-add', $page_data);
    }
    public function membersSave(Request $request) {
        $data['salutation'] = $request->salutation;
        $data['name'] = $request->name;
        $data['country'] = $request->country;
        $data['phone'] = $request->phone;
        $mode = $request->mode;
        $id = $request->id;
        if($mode == "CREATE") {
            $rs = Members::where('country', $data['country'])->where('phone', $data['phone'])->first();
            if($rs) {
                return $this->memberForm($data, "Phone number already exists for ".$rs->name,"","CREATE");
            } else {
                $l = new Members();
                $l->salutation = $data['salutation'];
                $l->name = $data['name'];
                $l->country = $data['country'];
                $l->phone = $data['phone'];
                $l->save();
                return redirect("/");
            }
        } else {
            $rs = Members::where('country', $data['country'])->where('phone', $data['phone'])->where('id','!=', $id)->first();
            if($rs) {
                return $this->memberForm($data, "Phone number already exists for ".$rs->name,$id,"EDIT");
            } else {
                Members::where('id', $id)->update($data);
                return redirect("/");
            }
        }

    }
    public function webhook(Request $request)
    {
        $out = Whatsapp::webhook($request);
        $msgid = $out['msgid'];
        $response = $out['response'];
        if($msgid != "") {
            $rs = Members::where('msgid',$msgid)->first();
            if($rs) {
                $data['attending'] = $response == "confirm" ?  10 : 20;
                
                $phone = $rs->country.$rs->phone;
                // if($data['attending'] == 10) {
                    $mediaURL = $this->qrCode($rs->name, $phone,$msgid);
                    $data['qrcode'] = $mediaURL;
                    $name = $rs->salutation." ".$rs->name;
                    $m = Whatsapp::sendConfirmMessage($phone, $mediaURL, $name);
                // }
                $data['confirmid'] = $m;
                Members::where('id', $rs->id)->update($data);
            }
        }
    //    $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->save();
    //     $from = $request->input('From');
    //     $response = strtolower(trim($request->input('Body')));

    // if ($response === 'yes') {
    //     // save confirmation
    // } elseif ($response === 'no') {
    //     // save decline
    // }

        return response('OK', 200);
    }
}


 