<?php

namespace App\Traits;
use Illuminate\Http\Request;
use Twilio\Rest\Client;

trait MobileNumberValidatorTraits
{
    public function validatePhoneNumber($phone_number, $field_name = 'phone_num')
    {
        $sid = env('TWILIO_SECRET_ID');
        $token = env('TWILIO_TOKEN');
        $twilio = new Client($sid, $token);
        
        try{
            $phone_number = $twilio->lookups->v1->phoneNumbers($phone_number)->fetch(["countryCode" => "US"]);
        }
        catch(\Exception $e) {
            if ($e->getCode() == 20404) {
                return response()->json([
                    'errors' => ["Sorry, you have used a non-existing US mobile number."],
                    'field_name' => $field_name
                ])->setStatusCode(201);
            }
        }
    }

    public function databaseFormatNumber($mobileNumber){
        return "+1" . str_replace(array('-', '(', ')', ' '), '', $mobileNumber);
    }
}