<?php

namespace App\Http\Controllers\Webhook;

use App\Http\Controllers\Controller;
use App\Models\Interaction;
use Illuminate\Http\Request;

class TwilioWebhookController extends Controller
{
    /**
     * Handles /voice/inbound
     * Routing logic: assigned agent first, then queue fallback, then voicemail.
     */
    public function inbound(Request $request)
    {
        $response = new VoiceResponse();
        $callerNumber = $request->input('From');
        $calledNumber = $request->input('To'); // Which of the 3 tenant lines was called?

        // Ensure call is recorded and play notice
        $response->say('Please note, this call is being recorded for training and monitoring purposes.', ['voice' => 'Polly.Amy']);

        $contact = Contact::where('phone_number', $callerNumber)->first();

        // 1. Try Assigned Agent First
        if ($contact && $contact->assigned_agent_id) {
            $agent = User::find($contact->assigned_agent_id);
            if ($agent && $agent->agent_status === 'available') {
                $dial = $response->dial('', ['record' => 'record-from-answer']);
                // In a real app, this might dial a SIP endpoint or Twilio Client
                $dial->client($agent->extension);
                return response($response)->header('Content-Type', 'text/xml');
            }
        }

        // 2. Fallback to appropriate Queue based on the number dialed
        // Determine queue name based on the tenant number that was called
        $queueName = 'General Intake Queue';
        // Logic to match $calledNumber to tenant's Client Line or External Line would go here

        $response->say('Please hold while we connect you to the next available agent.');
        $response->enqueue($queueName, ['waitUrl' => 'http://com.twilio.music.classical.s3.amazonaws.com/Massenet_-_Meditation_from_Thais.mp3']);

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

    /**
     * Handles /voice/status lifecycle events
     */
    public function status(Request $request)
    {
        $callSid = $request->input('CallSid');
        $status = $request->input('CallStatus'); // ringing, in-progress, completed, no-answer
        $duration = $request->input('CallDuration');

        Interaction::where('call_sid', $callSid)->update([
            'status' => $status,
            'duration' => $duration
        ]);

        return response()->json(['success' => true]);
    }

    /**
     * Handles /recording/status
     */
    public function recording(Request $request)
    {
        $callSid = $request->input('CallSid');

        Interaction::where('call_sid', $callSid)->update([
            'recording_sid' => $request->input('RecordingSid'),
            'recording_url' => $request->input('RecordingUrl')
        ]);

        return response()->json(['success' => true]);
    }
}
