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

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");
    }

    // Bersihkan call_sid untuk nomor yang pressed_button = "-"
    try {
        $clean_stmt = $db->prepare("
            UPDATE target_numbers 
            SET call_sid = NULL
            WHERE status = '-' 
            AND pressed_button = '-'
            AND call_sid IS NOT NULL
        ");
        $clean_stmt->execute();
    } catch (Exception $e) {
        logError("Error cleaning call_sid: " . $e->getMessage());
    }

    // Cek apakah ada panggilan yang masih aktif (dalam 30 detik terakhir)
    $stmt = $db->prepare("
        SELECT COUNT(*) as active_calls 
        FROM target_numbers 
        WHERE status = '-' 
        AND call_date >= DATE_SUB(NOW(), INTERVAL 30 SECOND)
        AND pressed_button IS NULL
    ");
    $stmt->execute();
    $active_calls = $stmt->fetch(PDO::FETCH_ASSOC)['active_calls'];

    // Jika masih ada panggilan aktif, skip
    if ($active_calls > 0) {
        echo json_encode([
            'success' => true,
            'message' => 'Call in progress'
        ]);
        exit;
    }

    // Ambil satu nomor yang belum dipanggil
    $stmt = $db->prepare("
        SELECT phone_number 
        FROM target_numbers 
        WHERE status = '-' AND (
            call_date IS NULL 
            OR (
                call_date IS NOT NULL 
                AND call_date < DATE_SUB(NOW(), INTERVAL 30 SECOND)
                AND (pressed_button IS NULL OR pressed_button != '1')
            )
        )
        ORDER BY call_date ASC, id ASC
        LIMIT 1
    ");
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to execute SELECT query");
    }
    
    $number = $stmt->fetchColumn();
    
    if (!$number) {
        echo json_encode([
            'success' => true,
            'message' => 'No numbers to call'
        ]);
        exit;
    }

    // Dapatkan Twilio client
    $client = getTwilioClient();
    
    // Format nomor telepon
    $formatted_number = preg_replace('/[^0-9+]/', '', $number);
    if (!startsWith($formatted_number, '+')) {
        $formatted_number = '+' . $formatted_number;
    }
    
    // Buat panggilan
    $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,
            call_sid = ?
        WHERE phone_number = ?
    ");
    
    if (!$update_stmt->execute([$call->sid, $number])) {
        throw new Exception("Failed to update status for number: " . $number);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Call initiated'
    ]);
    
} catch (Exception $e) {
    logError("Call error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

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