<?php
    require_once('call_flow_functions.php');
    header('Content-Type: application/xml; charset=UTF-8');
    $message_url = "/shared/serve_audios.php?path=";
    
    // Sanitize all incoming parameters
    $call_sid = htmlspecialchars($_POST['CallSid'], ENT_QUOTES, 'UTF-8');
    $call_status = htmlspecialchars($_POST['CallStatus'], ENT_QUOTES, 'UTF-8');
    
    $from_number_raw = $_REQUEST['From'];
    $to_number_raw = $_REQUEST['To'];
    
    // Sanitize phone numbers
    $from_number = htmlspecialchars(format_number($from_number_raw), ENT_QUOTES, 'UTF-8');
    $to_number = htmlspecialchars(format_number($to_number_raw), ENT_QUOTES, 'UTF-8');
    
    $call_flow = get_call_flow($to_number);
    $call_data = fetchDataSingle('call_histories', ['call_sid' => $call_sid]);

    echo '<?xml version="1.0" encoding="UTF-8"?>';

    if (isset($call_data['id']) && !empty($call_data['id'])) {
        // Sanitize call data fields
        $call_id = htmlspecialchars($call_data['id'], ENT_QUOTES, 'UTF-8');
        $cnam = htmlspecialchars($call_data['cnam'], ENT_QUOTES, 'UTF-8');
        $base_url = htmlspecialchars(base_url(), ENT_QUOTES, 'UTF-8');
        $good_bye = defalt_voice_message("good_bye.wav");
        update_call($call_id, 'is_first_digit', 1);
        if (isset($_REQUEST['Digits']) && $_REQUEST['Digits'] == '1') {
            $first_user_number = get_number_disturb($to_number, 1, $call_id, "first_number");
            $second_user_number = get_number_disturb($to_number, 2, $call_data, "second_number");
            $third_user_number = get_number_disturb($to_number, 3, $call_id, "third_number");

            if (!empty($first_user_number) || !empty($second_user_number) || !empty($third_user_number)) {
                $advertisement_message = defalt_voice_message("You-are-using-invisible-intercom-ADVERTSING.wav");
                update_call_status($call_sid, 'is_visitor', 1); 

                if (isset($call_flow['id'])) {
                    $pre_notify_message = $call_flow['is_pre_notify_message'];  
                     
                    if ($pre_notify_message == 1) {
                        $door_name = "";
                        $get_door = get_door($to_number); 
                        
                        if (isset($get_door['id']) && !empty($get_door['id'])) {
                            $door_name = htmlspecialchars($get_door['door_name'], ENT_QUOTES, 'UTF-8');
                        }                   

                        $body = "$cnam $from_number is about to contact you from $door_name. Reply STOP to opt out.";
                        send_sms_to_owner($call_id, $to_number, $from_number, $body);
                    }

                    if ($call_flow['is_advertisement_default_message'] == 0) {
                        $is_advertisement_textto_speech = $call_flow['is_advertisement_textto_speech'];
                        if ($is_advertisement_textto_speech == 0) {
                            $advertisement_audio_file = $message_url . rawurlencode($call_flow['advertisement_audio_file']);
                            $advertisement_message = "<Play>$advertisement_audio_file</Play>";
                        } else {
                            $advertisement_text = htmlspecialchars($call_flow['advertisement_text'], ENT_QUOTES, 'UTF-8');
                            $advertisement_vocie_select = htmlspecialchars($call_flow['advertisement_vocie_select'], ENT_QUOTES, 'UTF-8');
                            $advertisement_message = "<Say voice='" . $advertisement_vocie_select . "'>$advertisement_text</Say>";   
                        }
                    }
                }

                $stream_data = fetchDataSingle('stream_url');
                $sc_url = "";
                if (isset($stream_data['id']) && !empty($stream_data)) {
                    $sc_url = htmlspecialchars($stream_data['stream_url'], ENT_QUOTES, 'UTF-8') . "/api/callStreaming";
                }

                if (!empty($sc_url)) {
                    $dtmf_url = $base_url . "/signalwire_call/get_dtmf_event.php";
                    get_socket_url($sc_url, $call_id, $dtmf_url);  
                    update_call($call_id, 'count_participants', 1);
                    echo "<Response>
                            <Gather input='dtmf' action='skip_ad_message.php?call_id=" . $call_id . "' method='POST' timeout='1' numDigits='1'>
                                $advertisement_message
                            </Gather>
                            <Dial> 
                                <Conference maxParticipants='4' startConferenceOnEnter='true'
                                    endConferenceOnExit='true' beep='false' statusCallback='" . $base_url . "/signalwire_call/conference_connect.php?call_id=$call_id' statusCallbackEvent='start end join leave' waitUrl='" . $base_url . "/signalwire_call/wait_call.php'>
                                    MyConference_$call_id
                                </Conference>
                            </Dial>
                          </Response>";
                }
            } else {
                echo "<Response>
                        <Redirect>no_one_available.php?call_id=$call_id</Redirect>
                    </Response>";
            }

        } else if ((isset($_REQUEST['call_pin']) && $_REQUEST['call_pin'] == 2) || (isset($_REQUEST['Digits']) && $_REQUEST['Digits'] == '2')) {
            $press2_message = $base_url . "/audio_messages/enter_your_code_now.wav";
            $message = "<Play>$press2_message</Play>";

            if (isset($call_flow['id']) && ($call_flow['press2_default_message'] == 0)) {
                $check_press2_message = $call_flow['press2_textto_speech'];

                if ($check_press2_message == 0) {
                    $press2_message = $message_url . rawurlencode($call_flow['press2_audio_file']);
                    $message = "<Play>$press2_message</Play>";
                } else {
                    $press2_text = htmlspecialchars($call_flow['press2_text'], ENT_QUOTES, 'UTF-8');
                    $press2_vocie_select = htmlspecialchars($call_flow['press2_vocie_select'], ENT_QUOTES, 'UTF-8');
                    $message = "<Say voice='" . $press2_vocie_select . "'>$press2_text</Say>";   
                } 
            }

            if (isset($_REQUEST['call_pin']) && $_REQUEST['call_pin'] == 2) {
                echo "<Response>
                    <Gather input='dtmf' action='handle_data.php?caller_code=1' method='POST' timeout='20' numDigits='4'>
                        $message
                    </Gather>
                    $good_bye
                    <Hangup/>
                </Response>";    
            } else {
                echo "<Response>
                        <Gather input='dtmf' action='handle_data.php?check_code=1' method='POST' timeout='20' numDigits='4'>
                            $message
                        </Gather>
                        $good_bye
                        <Hangup/>
                    </Response>";      
            }

        } else {
            if((isset($_REQUEST['Digits'])) && ($_REQUEST['Digits'] != '2') && ($_REQUEST['Digits'] != '1')){
                if($call_data['is_welcome'] == 0){
                    update_call($call_id, 'is_welcome', 1);
                    echo "<Response>
                        <Redirect>repeat_welcome.php?call_id=$call_id</Redirect>
                      </Response>";    
                }
                else{
                    echo "<Response>
                            <Redirect>no_response.php</Redirect>
                          </Response>";
                }
                
            }
            else{
                echo '<Response> <Hangup/> </Response>';
                die();
            }
        }

    } else {
        echo '<Response> <Hangup/> </Response>';
        die();
    }
?>
