<?php
	require_once('call_flow_functions.php');
    header('Content-Type: application/xml; charset=UTF-8');
    $message_url = "/shared/serve_audios.php?path=";
    
    // Sanitize the call_id input
    $call_id = isset($_REQUEST['call_id']) ? (int)$_REQUEST['call_id'] : 0;
    $call_id = htmlspecialchars((string)$call_id, ENT_QUOTES, 'UTF-8');
	$call_history = fetch_table_data('call_histories', 'id', $call_id);
    $base_url = base_url();
    
    if (isset($call_history['id']) && $call_history['owner_connected'] == 0) {
        $to_number = format_number($call_history['to_number']);
        $call_flow = get_call_flow($to_number);
        $status_chk = check_status($to_number, $call_history['call_sid']);
        header('Content-Type: text/xml');
        echo '<?xml version="1.0" encoding="UTF-8"?>';

        if ($status_chk == "in-progress") {
            $call_duration_after_user_connect = $call_flow['call_duration_after_user_connect'];
            $call_sid = $_POST['CallSid'];

            update_call($call_id, 'second_person_call_sid', $call_sid);
            update_call($call_id, 'owner_connected', 1);
            update_call($call_id, 'count_participants', 2);
            $conference_sid = $call_history['conference_sid'];
            $statusCallback = htmlspecialchars("$base_url/signalwire_call/conference_connect.php?call_id=$call_id", ENT_QUOTES, 'UTF-8');
            echo "<Response>
                      <Dial timeLimit='" . htmlspecialchars($call_duration_after_user_connect, ENT_QUOTES, 'UTF-8') . "'>
                          <Conference maxParticipants='4' startConferenceOnEnter='false'
                                  endConferenceOnExit='false' beep='false' statusCallback='" . $statusCallback ."' statusCallbackEvent='start end join leave'>
                              MyConference_$call_id
                          </Conference>
                      </Dial>
                  </Response>";
        } else {
            echo "<Response>
                      <Hangup/>
                  </Response>";
        }
    }
?>
