<?php

namespace App\Http\Controllers\Twilio;

use App\Models\Communication\Call;
use Twilio\TwiML\VoiceResponse;
use Illuminate\Http\Request;

class SdkOutboundVoiceController
{
    public function __invoke(Request $request): string
    {
        $callId = (int) $request->input('call_id');

        /** @var Call $call */
        $call = Call::query()
            ->with(['communication', 'phoneNumber'])
            ->findOrFail($callId);

        $voice = new VoiceResponse();

        $dial = $voice->dial('', [
            'callerId' => $call->from_number,
            'record' => $call->is_recorded ? 'record-from-answer' : 'do-not-record',
            'recordingStatusCallback' => route('twilio.voice.recording-status'),
//            'action' => route('twilio.voice.outbound.twiml', ['call' => $call->id]),
            'method' => 'POST',
            'answerOnBridge' => true,
        ]);

        $dial->number($call->to_number, [
            'statusCallback' => route('twilio.voice.status'),
            'statusCallbackMethod' => 'POST',
            'statusCallbackEvent' => 'initiated ringing answered completed',
        ]);

        return (string) $voice;
    }
}