<?php
// Matikan semua output buffering yang ada
while (ob_get_level()) {
    ob_end_clean();
}

// Mulai buffer baru
ob_start();

// Nonaktifkan error reporting
error_reporting(0);
ini_set('display_errors', 0);

require_once 'includes/config.php';

try {
    // Get audio URLs
    $stmt = $db->prepare("SELECT type, file_path FROM audio_settings");
    $stmt->execute();
    $audioFiles = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    $audioUrls = [];
    foreach ($audioFiles as $type => $path) {
        $audioUrls[$type] = BASE_URL . '/uploads/audio/' . $path;
    }

    // Get input parameters
    $digits = isset($_POST['Digits']) ? $_POST['Digits'] : null;
    $to = isset($_POST['To']) ? $_POST['To'] : null;

    // Create TwiML response
    $response = new Twilio\TwiML\VoiceResponse();

    if ($digits === null) {
        if (!isset($audioUrls['welcome'])) {
            throw new Exception('Welcome audio not found');
        }
        $gather = $response->gather(['numDigits' => 1, 'timeout' => 10, 'action' => WEBHOOK_URL]);
        $gather->play($audioUrls['welcome']);
    } 
    else if ($digits === '1') {
        if (!isset($audioUrls['confirmation'])) {
            throw new Exception('Confirmation audio not found');
        }
        $response->play($audioUrls['confirmation']);
        
        if ($to) {
            $stmt = $db->prepare("UPDATE target_numbers SET status = 'Success', pressed_button = '1', call_date = NOW() WHERE phone_number = ?");
            $stmt->execute([$to]);
        }
    } 
    else {
        if (!isset($audioUrls['error'])) {
            throw new Exception('Error audio not found');
        }
        $response->play($audioUrls['error']);
        
        if ($to) {
            $stmt = $db->prepare("UPDATE target_numbers SET status = '-', pressed_button = ?, call_date = NOW() WHERE phone_number = ?");
            $stmt->execute([$digits, $to]);
        }
    }

    // Bersihkan semua output yang ada
    ob_clean();
    
    // Set header content type
    header('Content-Type: text/xml');
    
    // Keluarkan XML response
    $xml = $response->asXML();
    // Pastikan tidak ada BOM atau whitespace
    $xml = preg_replace('/^\xEF\xBB\xBF/', '', $xml);
    $xml = preg_replace('/^\s+/', '', $xml);
    echo $xml;
    
} catch (Exception $e) {
    error_log("Webhook error: " . $e->getMessage());
    
    // Bersihkan output
    ob_clean();
    
    // Set header
    header('Content-Type: text/xml');
    
    // Buat response error
    $response = new Twilio\TwiML\VoiceResponse();
    $response->say('Maaf, terjadi kesalahan sistem.', ['language' => 'id-ID']);
    echo $response->asXML();
}

// Flush dan hentikan output buffering
ob_end_flush();