<?php
// audio1.php - play intro audio and gather DTMF (hardened)
ob_start();

ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error_log.txt');

include __DIR__ . '/db.php'; // safe include; should not echo

// Get and normalize phone
$phone = isset($_GET['phone']) ? trim($_GET['phone']) : '';
$phone = preg_replace('/[^\d+]/', '', $phone); // keep digits and leading plus

// Build absolute, encoded action URL
$actionUrl = 'https://survey.taimart.co.ke/survey-app/rec1.php?phone=' . rawurlencode($phone);

// Clean any captured output (strip BOM and leading whitespace)
$buf = ob_get_clean();
$buf = preg_replace('/^\xEF\xBB\xBF/', '', $buf);
$buf = preg_replace('/^\s+/', '', $buf);

// Return TwiML
header('Content-Type: text/xml; charset=utf-8');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<Response>
  <Gather input=\"dtmf\" finishOnKey=\"#\" timeout=\"60\" action=\"$actionUrl\" method=\"POST\">
    <Play>https://survey.taimart.co.ke/survey-app/audio/audio1.mp3</Play>
  </Gather>
  <Redirect>$actionUrl</Redirect>
</Response>";
