<?php
$_POST = json_decode(file_get_contents("php://input"), true);	
// $_POST['email'] = 'rahul.patidar@serosoft.in';
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;

class Twilio{
    private $sid = 'AC63bff9a83ec2ace959a824c27cd1a4ab';
    private $token = 'ca9a336fd5d212d2ded58ff260259378';
    private $services = 'VAaf6a773da732cdc39702b2fdb5c14fbb';
    private $twilio;

    function __construct() {
        $this->twilio = new Client($this->sid, $this->token);
    }
    public function sendEmail($emailId) 
    {
        $this->twilio = new Client($this->sid, $this->token);
        $verification = $this->twilio->verify->v2->services($this->services)
                                            ->verifications
                                            ->create($emailId, "email");
        return $verification;
    }
    
    public function verifyOTP($emailId, $otp)
    {
        try {
            $verificationCheck = $this->twilio->verify->v2->services($this->services)->verificationChecks->create(["to" => $emailId,"code" => $otp]);
        } catch (\Throwable $th) {
            $verificationCheck = $th;
        }
        return $verificationCheck;
    }
}
if(isset($_POST['action']) && $_POST['action'] == 'sendemail' && isset($_POST['email']) && $_POST['email'])
{
    $twillioObject = new Twilio();
    $verification = $twillioObject->sendEmail($_POST['email']);
    $responce = array();
    if(isset($verification->sid) && $verification->sid)
    {
        $responce = array('status' => 'SUCCESS');
    }
    else
    {
        $responce = array('status' => 'FAILED');
    }
    echo json_encode($responce);
}

if(isset($_POST['action']) && $_POST['action'] == 'verifyemail' && isset($_POST['email']) && $_POST['email'] && isset($_POST['otp']) && $_POST['otp'])
{
    $twillioObject = new Twilio();
    $verification = $twillioObject->verifyOTP($_POST['email'], $_POST['otp']);
    $responce = array();
    if(isset($verification->status) && $verification->status == 'approved')
    {
        $responce = array('status' => 'SUCCESS');
    }
    else
    {
        $responce = array('status' => 'FAILED');
    }
    echo json_encode($responce);
}