36716-vm/api/broadcast_sms.php
2025-12-07 05:00:42 +00:00

71 lines
2.0 KiB
PHP

<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../telnyx/config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => '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.']);
}