<?php
// call.php - hardened outbound call creator
// - validates and encodes phone
// - inserts a survey row and passes survey_id to rec1.php
// - uses prepared statements for DB writes
// - catches Twilio exceptions and logs errors
// - never prints PHP errors to Twilio

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

require_once __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;

include __DIR__ . '/db.php'; // must set $conn (mysqli) or null

// Temporary request logging for debugging (remove when stable)
file_put_contents(__DIR__ . '/twilio_requests.log', date('c') . " call.php REQUEST\nMETHOD: " . $_SERVER['REQUEST_METHOD'] . "\nPOST: " . json_encode($_POST) . "\n\n", FILE_APPEND);

// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: text/plain; charset=utf-8', true, 405);
    echo "Method not allowed.";
    exit;
}

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

if (empty($phone)) {
    error_log('call.php: empty or invalid phone in POST: ' . json_encode($_POST));
    header('Content-Type: text/html; charset=utf-8', true, 400);
    echo "<p>Invalid phone number. Please go back and enter a valid phone number.</p>";
    exit;
}

// Twilio credentials - replace with environment variables in production
$twilioSid   = 'AC956d8d0d69a72975e29f45cd81f17b2b';
$twilioToken = '9ce3e292028372cc59ac63bd2c36977a';
$twilioFrom  = '+17407362374';

// Insert placeholder survey row (if DB available) and capture id
$survey_id = 0;
if ($conn) {
    $stmt = $conn->prepare("INSERT INTO surveys (phone_number, created_at) VALUES (?, NOW())");
    if ($stmt) {
        $stmt->bind_param('s', $phone);
        if ($stmt->execute()) {
            $survey_id = (int)$stmt->insert_id;
        } else {
            error_log('call.php: DB insert failed: ' . $stmt->error);
        }
        $stmt->close();
    } else {
        error_log('call.php: DB prepare failed: ' . $conn->error);
    }
} else {
    error_log('call.php: DB connection not available when creating survey row for ' . $phone);
}

// Build webhook URL for Twilio (always rawurlencode the phone)
$webhookUrl = 'https://survey.taimart.co.ke/survey-app/rec1.php?phone=' . rawurlencode($phone);
if ($survey_id) {
    $webhookUrl .= '&survey_id=' . intval($survey_id);
}

// Initialize Twilio client and create the call
$client = new Client($twilioSid, $twilioToken);

try {
    $call = $client->calls->create(
        $phone,
        $twilioFrom,
        ['url' => $webhookUrl]
    );
    // Log call SID for debugging
    error_log('call.php: Twilio call created SID=' . ($call->sid ?? 'unknown') . ' phone=' . $phone . ' survey_id=' . $survey_id);
} catch (\Twilio\Exceptions\RestException $e) {
    // Twilio-specific error (invalid number, geo permissions, etc.)
    error_log('call.php: Twilio RestException: ' . $e->getMessage() . ' phone=' . $phone);
    header('Content-Type: text/html; charset=utf-8', true, 200);
    echo "<p>Unable to place the call right now. Please try again later.</p>";
    exit;
} catch (\Exception $e) {
    // Any other error
    error_log('call.php: General exception: ' . $e->getMessage() . ' phone=' . $phone);
    header('Content-Type: text/html; charset=utf-8', true, 200);
    echo "<p>Internal error. Please try again later.</p>";
    exit;
}

// On success, redirect back to index (or show a confirmation)
header('Location: index.php');
exit;
