<?php
// rec1.php - create survey row on first GET, update rec1 when Digits posted
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') . " rec1 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']) : '';
$digits = isset($_POST['Digits']) ? trim($_POST['Digits']) : null;

// Normalize phone: keep digits and leading plus only
$phone = preg_replace('/[^\d+]/', '', $phone);

// Ensure we have a survey_id to reference; create a new row if none provided
$survey_id = isset($_GET['survey_id']) ? intval($_GET['survey_id']) : 0;

if (!$survey_id && $phone && $conn) {
    // Insert a new survey row and get its id
    $stmt = $conn->prepare("INSERT INTO surveys (phone_number, created_at) VALUES (?, NOW())");
    if ($stmt) {
        $stmt->bind_param('s', $phone);
        if ($stmt->execute()) {
            $survey_id = $stmt->insert_id;
        } else {
            error_log('rec1: initial insert failed: ' . $stmt->error);
        }
        $stmt->close();
    } else {
        error_log('rec1: initial insert prepare failed: ' . $conn->error);
    }
}

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

// Build action URL for rec2 including survey_id and phone
$actionUrl = 'https://survey.taimart.co.ke/survey-app/rec2.php?phone=' . rawurlencode($phone);
if ($survey_id) {
    $actionUrl .= '&survey_id=' . intval($survey_id);
}

// Always return valid TwiML
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

// Gather wraps Play so DTMF pressed during playback is captured.
// timeout set to 60 (maximum allowed). finishOnKey '#' is included so user can submit immediately.
// If you expect a fixed-length input, add numDigits="N" to the Gather tag.
echo "<Response>
  <Gather input=\"dtmf\" finishOnKey=\"#\" timeout=\"60\" action=\"$actionUrl\" method=\"POST\">
    <Play>https://survey.taimart.co.ke/survey-app/audio/audio2.mp3</Play>
  </Gather>
  <Redirect>$actionUrl</Redirect>
</Response>";
?>
