<?php
// rec2.php - update rec2 using survey_id (preferred) or phone fallback, then play audio3 and continue flow
header('Content-Type: text/xml; charset=utf-8');

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

// Debug logging of incoming Twilio requests (temporary; remove when stable)
file_put_contents(__DIR__ . '/twilio_requests.log', date('c') . " rec2 REQUEST\nGET: " . json_encode($_GET) . "\nPOST: " . json_encode($_POST) . "\n\n", FILE_APPEND);

include __DIR__ . '/db.php'; // provides $conn or null

$phone     = isset($_GET['phone']) ? trim($_GET['phone']) : '';
$survey_id = isset($_GET['survey_id']) ? intval($_GET['survey_id']) : 0;
$digits    = isset($_POST['Digits']) ? trim($_POST['Digits']) : null;

// Normalize phone
$phone = preg_replace('/[^\d+]/', '', $phone);

if ($digits && $conn) {
    if ($survey_id) {
        $stmt = $conn->prepare("UPDATE surveys SET rec2 = ? WHERE id = ? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('si', $digits, $survey_id);
            if (! $stmt->execute()) {
                error_log('rec2: update by id failed: ' . $stmt->error);
            }
            $stmt->close();
        } else {
            error_log('rec2: prepare update by id failed: ' . $conn->error);
        }
    } elseif ($phone) {
        // fallback: update latest row for this phone
        $stmt = $conn->prepare("UPDATE surveys SET rec2 = ? WHERE phone_number = ? ORDER BY created_at DESC LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('ss', $digits, $phone);
            if (! $stmt->execute()) {
                error_log('rec2: fallback update by phone failed: ' . $stmt->error);
            }
            $stmt->close();
        } else {
            error_log('rec2: fallback prepare failed: ' . $conn->error);
        }
    } else {
        error_log('rec2: received digits but no survey_id and no phone provided.');
    }
} elseif ($digits && ! $conn) {
    error_log('rec2: received digits but DB connection not available. Phone: ' . $phone . ' survey_id: ' . $survey_id);
}

// Decide next step after audio3. If audio3 is the final audio, use Hangup after Play.
// If there are more audios or steps, replace $nextUrl with the next endpoint and use Redirect.
// For this deployment we'll assume audio3 is the final audio and hang up after it.
// If you want to chain more audio, set $nextUrl and use Redirect instead of Hangup.

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<Response>
  <Play>https://survey.taimart.co.ke/survey-app/audio/audio3.mp3</Play>
  <Hangup/>
</Response>";
?>
