'Method not allowed']); exit; } $message = $_POST['message'] ?? null; if (empty($message)) { http_response_code(400); echo json_encode(['error' => 'Message is required']); exit; } // Get all clients with phone numbers $stmt = db()->prepare("SELECT id, name, phone FROM clients WHERE phone IS NOT NULL AND phone != ''"); $stmt->execute(); $clients = $stmt->fetchAll(PDO::FETCH_ASSOC); // Set up Telnyx API \Telnyx\Telnyx::setApiKey(TELNYX_API_KEY); $success_count = 0; $error_count = 0; foreach ($clients as $client) { try { $response = \Telnyx\Message::create([ 'from' => TELNYX_MESSAGING_PROFILE_ID, 'to' => $client['phone'], 'text' => $message, ]); // Log the message $log_stmt = db()->prepare("INSERT INTO sms_logs (client_id, sender, recipient, message, status) VALUES (?, ?, ?, ?, ?, ?)"); $log_stmt->execute([ $client['id'], TELNYX_MESSAGING_PROFILE_ID, $client['phone'], $message, 'sent' ]); $success_count++; } catch (\Telnyx\Exception\ApiErrorException $e) { $error_count++; // Log the failure $log_stmt = db()->prepare("INSERT INTO sms_logs (client_id, sender, recipient, message, status) VALUES (?, ?, ?, ?, ?, ?)"); $log_stmt->execute([ $client['id'], TELNYX_MESSAGING_PROFILE_ID, $client['phone'], $message, 'failed' ]); } } if ($success_count > 0) { echo json_encode(['success' => true, 'message' => "Broadcast sent to " . $success_count . " clients. " . $error_count . " failed."]); } else { http_response_code(500); echo json_encode(['error' => 'Failed to send broadcast to any clients.']); }