<?php
    require_once('call_flow_functions.php');
    header('Content-Type: application/xml; charset=UTF-8');
    $message_url = "/shared/serve_audios.php?path=";

    // Validate and sanitize call_id
    $call_id = isset($_REQUEST['call_id']) ? (int)$_REQUEST['call_id'] : 0;

    // Fetch call history securely
    $call_id = htmlspecialchars((string)$call_id, ENT_QUOTES, 'UTF-8');
    $call_history = fetch_table_data('call_histories', 'id', $call_id);
    $from_number = htmlspecialchars(format_number($call_history['from_number'] ?? ''), ENT_QUOTES, 'UTF-8');
    $to_number = htmlspecialchars(format_number($call_history['to_number'] ?? ''), ENT_QUOTES, 'UTF-8');
    $call_flow = get_call_flow($to_number);
    $base_url = base_url();

    // Optional: validate call_flow values
    $end_call_time = isset($call_flow['end_call_time']) ? (int)$call_flow['end_call_time'] : 0;
    if($call_history['first_person_leave'] == 1){
        echo '<?xml version="1.0" encoding="UTF-8"?>';
        echo "<Response>
                    <Hangup/>
            </Response>";
    }
    else{

        if (isset($call_flow['is_hang_up_call_terminate']) && $call_flow['is_hang_up_call_terminate'] == 0) {
            sleep($end_call_time);
        }

        // Sanitize SIDs (assuming they are alphanumeric)
        $second_person_call_sid = preg_replace('/[^a-zA-Z0-9]/', '', $call_history['second_person_call_sid']);
        $cnf_sid = preg_replace('/[^a-zA-Z0-9]/', '', $call_history['conference_sid']);

        remove_participant_from_conference($to_number, $cnf_sid, $second_person_call_sid);
    }
?>
