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

72 lines
2.1 KiB
PHP

<?php
require_once '../vendor/autoload.php';
require_once '../db/config.php';
require_once '../telnyx/config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$client_id = $_POST['client_id'] ?? null;
$message = $_POST['message'] ?? null;
if (empty($client_id) || empty($message)) {
http_response_code(400);
echo json_encode(['error' => 'Client ID and message are required']);
exit;
}
// Fetch client phone number
$stmt = db()->prepare("SELECT phone FROM clients WHERE id = ?");
$stmt->execute([$client_id]);
$client = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$client || empty($client['phone'])) {
http_response_code(404);
echo json_encode(['error' => 'Client not found or phone number is missing']);
exit;
}
$recipient_phone = $client['phone'];
// Initialize Telnyx
\Telnyx\Telnyx::setApiKey(TELNYX_API_KEY);
try {
$response = \Telnyx\Message::create([
'from' => TELNYX_MESSAGING_PROFILE_ID, // Your Telnyx sending number or messaging profile ID
'to' => $recipient_phone,
'text' => $message,
]);
// Log the message to the database
$log_stmt = db()->prepare("INSERT INTO sms_logs (client_id, user_id, sender, recipient, message, status) VALUES (?, ?, ?, ?, ?, ?)");
$log_stmt->execute([
$client_id,
$_SESSION['user_id'], // Assuming admin/coach is logged in
TELNYX_MESSAGING_PROFILE_ID,
$recipient_phone,
$message,
'sent' // or $response->status
]);
echo json_encode(['success' => true, 'message_id' => $response->id]);
} catch (\Telnyx\Exception\ApiErrorException $e) {
http_response_code(500);
echo json_encode(['error' => 'Telnyx API error: ' . $e->getMessage()]);
// Log the failure
$log_stmt = db()->prepare("INSERT INTO sms_logs (client_id, user_id, sender, recipient, message, status) VALUES (?, ?, ?, ?, ?, ?)");
$log_stmt->execute([
$client_id,
$_SESSION['user_id'],
TELNYX_MESSAGING_PROFILE_ID,
$recipient_phone,
$message,
'failed'
]);
}