<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';

/* ---------- LOGGING ---------- */
file_put_contents(
    '/home/twilio_logs/voice.log',
    "\n==== ".date('Y-m-d H:i:s')." ====\n".
    "RAW REQUEST:\n".print_r($_REQUEST,true),
    FILE_APPEND
);


/* ---------- DESTINATION (ORDER MATTERS) ---------- */
// WebRTC -> To
// SIP -> Called / SipTo
$to =
    $_REQUEST['To']
    ?? $_REQUEST['Called']
    ?? $_REQUEST['SipTo']
    ?? '';

$callerId = $_REQUEST['callerId']
    ?? '+13073175382';

/* ---------- CLEAN SIP ---------- */
if (stripos($to, 'sip:') === 0) {
    $to = substr($to, 4);
    $to = explode('@', $to)[0];
}

/* ---------- FAIL SAFE ---------- */
if (empty($to)) {
    ?>
    <Response>
        <Say>Invalid destination</Say>
    </Response>
    <?php
    exit;
}

/* ---------- EXTENSIONS ---------- */
$extensions = ['100','101','102','103'];

if (in_array($to, $extensions, true)) {
    ?>
    <Response>
        <Dial answerOnBridge="true" timeout="30">
            <Sip>sip:<?php echo $to; ?>@lunavo.sip.us1.twilio.com</Sip>
        </Dial>
    </Response>
    <?php
    exit;
}

/* ---------- INCOMING CALLS ---------- */
$from = $_REQUEST['From'] ?? '';
// If From does NOT start with 'client:', it is an incoming PSTN call
if (stripos($from, 'client:') === false) {
    ?>
    <Response>
        <Dial answerOnBridge="true">
            <Client>user_1</Client>
            <Client>user_2</Client>
        </Dial>
    </Response>
    <?php
    exit;
}

/* ---------- PSTN ---------- */
$number = preg_replace('/[^0-9\+]/', '', $to);
if ($number[0] !== '+') {
    $number = '+'.$number;
}
?>
<Response>
    <Dial answerOnBridge="true" callerId="<?php echo htmlspecialchars($callerId); ?>">
        <Number><?php echo htmlspecialchars($number); ?></Number>
    </Dial>
</Response>
