<?php

namespace App\Http\Controllers\Twilio;

use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Twilio\TwiML\VoiceResponse;

class TwilioTransferFallbackController
{
    public function __invoke(Request $request): Response
    {
        $voice = new VoiceResponse();

        try {
            $fromAgentId    = (int) $request->input('from_agent_id');
            $dialCallStatus = $request->input('DialCallStatus', 'no-answer');
            $fromAgent      = User::find($fromAgentId);

            // Transfer connected successfully — end cleanly
            if ($dialCallStatus === 'completed') {
                return response((string) $voice, 200)->header('Content-Type', 'text/xml');
            }

            // Target didn't answer — ring the original agent back
            if ($fromAgent) {
                $dial = $voice->dial('', ['timeout' => 30]);
                $dial->client('agent_' . $fromAgentId);
            } else {
                $voice->say('We were unable to connect your call. Goodbye.');
            }

            return response((string) $voice, 200)->header('Content-Type', 'text/xml');

        } catch (\Throwable $exception) {
            logger()->error('TwilioTransferFallbackController error', [
                'message'        => $exception->getMessage(),
                'from_agent_id'  => $request->input('from_agent_id'),
                'DialCallStatus' => $request->input('DialCallStatus'),
            ]);

            $voice->say('We were unable to connect your call. Goodbye.');
            return response((string) $voice, 200)->header('Content-Type', 'text/xml');
        }
    }
}
