<?php
    session_start();
    require_once('call_flow_functions.php');
    header('Content-Type: application/xml; charset=UTF-8');
    // Sanitize and validate call_id
    $call_id = isset($_REQUEST['call_id']) ? (int)$_REQUEST['call_id'] : 0;

    // Escape all output that may be user-controlled
    $escaped_call_id = htmlspecialchars((string)$call_id, ENT_QUOTES, 'UTF-8');

    $call_history = fetch_table_data('call_histories', 'id', $call_id);
    if (!$call_history) {
        exit("No call history found");
    }

    $base_url = rtrim(base_url(), '/');
    $call_flow = get_call_flow($call_history['to_number']);
    $to_number = $call_history['to_number'];
    $is_access_granted = $call_history['is_access_granted'];
    $end_call_time = $is_access_granted == 1 ? $call_flow['end_call_time'] : $call_flow['call_duration_after_user_connect'];

    $escaped_end_call_time = htmlspecialchars((string)$end_call_time, ENT_QUOTES, 'UTF-8');

    $conference_callback_url = $base_url . "/signalwire_call/conference_connect.php?call_id=" . urlencode($call_id);

    echo '<?xml version="1.0" encoding="UTF-8"?>';
    $check_status = check_call_status($call_history['to_number'], $call_history['call_sid']);
    if($check_status == "completed"){
        $message_say = $base_url . "/signalwire_call/message_say.php?call_id=". urlencode($call_id);
        echo "<Response>
                <Say>User has left the call</Say>
            </Response>";
    }
    else{
        echo "<Response>
                <Dial timeLimit='{$escaped_end_call_time}'>
                    <Conference maxParticipants='4' startConferenceOnEnter='true'
                        endConferenceOnExit='false' beep='false' statusCallback='" . htmlspecialchars($conference_callback_url, ENT_QUOTES, 'UTF-8') . "' statusCallbackEvent='start end join leave'>
                        MyConference_{$escaped_call_id}
                    </Conference>
                </Dial>                 
        </Response>";
    }
        
    
?>
