<?php
// Kontrol buffer sesuai panduan
while (ob_get_level()) {
    ob_end_clean();
}
ob_start();

// Aktifkan error reporting untuk debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'includes/config.php';

// Fungsi untuk logging
function logError($message) {
    error_log(date('Y-m-d H:i:s') . " - " . $message . "\n", 3, "batch_calls.log");
}

try {
    // Verifikasi koneksi database
    if (!isset($db)) {
        throw new Exception("Database connection not established");
    }

    // Log start process
    logError("Starting batch calls process");

    // Ambil 10 nomor yang belum dipanggil
    $stmt = $db->prepare("
        SELECT phone_number 
        FROM target_numbers 
        WHERE status = '-'
        ORDER BY call_date ASC
        LIMIT 10
    ");
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to execute SELECT query: " . implode(" ", $stmt->errorInfo()));
    }
    
    $numbers = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Log found numbers
    logError("Found " . count($numbers) . " numbers to call");
    
    if (empty($numbers)) {
        echo json_encode([
            'success' => true,
            'numbers' => [],
            'message' => 'No numbers to call'
        ]);
        exit;
    }

    // Dapatkan Twilio client dari helper function
    $client = getTwilioClient();
    $successful_calls = [];
    
    // Lakukan panggilan untuk setiap nomor
    foreach ($numbers as $number) {
        try {
            logError("Attempting to call number: " . $number);
            
            // Format nomor telepon
            $formatted_number = preg_replace('/[^0-9+]/', '', $number);
            if (!startsWith($formatted_number, '+')) {
                $formatted_number = '+' . $formatted_number;
            }
            
            $call = $client->calls->create(
                $formatted_number,
                TWILIO_NUMBER,
                [
                    "url" => WEBHOOK_URL,
                    "statusCallback" => BASE_URL . '/callback.php',
                    "statusCallbackEvent" => ["completed"],
                    "statusCallbackMethod" => "POST"
                ]
            );
            
            // Update status di database
            $update_stmt = $db->prepare("
                UPDATE target_numbers 
                SET call_date = NOW(),
                    status = '-',
                    pressed_button = NULL
                WHERE phone_number = ?
            ");
            
            if (!$update_stmt->execute([$number])) {
                throw new Exception("Failed to update status for number: " . $number);
            }
            
            $successful_calls[] = $number;
            logError("Successfully initiated call to: " . $number);
            
        } catch (Exception $e) {
            logError("Error calling number $number: " . $e->getMessage());
            continue;  // Lanjut ke nomor berikutnya jika terjadi error
        }
    }
    
    // Response success jika ada panggilan yang berhasil
    if (!empty($successful_calls)) {
        echo json_encode([
            'success' => true,
            'numbers' => $successful_calls,
            'message' => 'Successfully initiated ' . count($successful_calls) . ' calls'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to initiate any calls'
        ]);
    }
    
} catch (Exception $e) {
    logError("Batch call error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

// Helper function
function startsWith($haystack, $needle) {
    return strpos($haystack, $needle) === 0;
} 