151 lines
4.7 KiB
PHP
151 lines
4.7 KiB
PHP
<?php
|
|
/**
|
|
* API - Crear mensaje programado / recordatorio
|
|
*/
|
|
|
|
require_once '../config/config.php';
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('Access-Control-Allow-Origin: *');
|
|
header('Access-Control-Allow-Methods: POST');
|
|
header('Access-Control-Allow-Headers: Content-Type');
|
|
|
|
requireAuthentication();
|
|
|
|
try {
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
error_log('📥 schedule_message.php - Input recibido: ' . json_encode($input));
|
|
|
|
if (!$input) {
|
|
throw new Exception('Datos inválidos');
|
|
}
|
|
|
|
// Validar campos requeridos
|
|
$userId = isset($input['user_id']) ? intval($input['user_id']) : null;
|
|
$messageType = $input['message_type'] ?? 'template';
|
|
$scheduledDate = $input['scheduled_date'] ?? null;
|
|
$scheduledTime = $input['scheduled_time'] ?? '09:00';
|
|
|
|
if (!$userId) {
|
|
throw new Exception('ID de usuario requerido');
|
|
}
|
|
|
|
if (!$scheduledDate) {
|
|
throw new Exception('Fecha programada requerida');
|
|
}
|
|
|
|
// Validar que la fecha no sea en el pasado
|
|
$scheduledDateTime = new DateTime($scheduledDate . ' ' . $scheduledTime);
|
|
$now = new DateTime();
|
|
|
|
if ($scheduledDateTime < $now) {
|
|
throw new Exception('La fecha programada no puede ser en el pasado');
|
|
}
|
|
|
|
$db = Database::getInstance();
|
|
|
|
// Verificar que el usuario existe
|
|
$user = $db->fetch("SELECT * FROM users WHERE id = ?", [$userId]);
|
|
if (!$user) {
|
|
throw new Exception('Usuario no encontrado');
|
|
}
|
|
|
|
// Preparar datos según el tipo de mensaje
|
|
$templateId = null;
|
|
$templateName = null;
|
|
$templateLanguage = 'es';
|
|
$templateParameters = null;
|
|
$messageContent = null;
|
|
|
|
if ($messageType === 'template') {
|
|
$templateId = isset($input['template_id']) ? intval($input['template_id']) : null;
|
|
$templateName = $input['template_name'] ?? null;
|
|
$templateLanguage = $input['template_language'] ?? 'es';
|
|
$templateParameters = $input['template_parameters'] ?? null;
|
|
|
|
error_log('🔍 template_parameters recibido: ' . json_encode($templateParameters));
|
|
error_log('🔍 Es array? ' . (is_array($templateParameters) ? 'Sí' : 'No'));
|
|
|
|
if (!$templateId && !$templateName) {
|
|
throw new Exception('Se requiere ID o nombre de plantilla');
|
|
}
|
|
|
|
// Si se proporcionaron parámetros, convertir a JSON
|
|
if ($templateParameters && is_array($templateParameters)) {
|
|
$templateParameters = json_encode($templateParameters, JSON_UNESCAPED_UNICODE);
|
|
error_log('✅ Convertido a JSON: ' . $templateParameters);
|
|
} else {
|
|
error_log('⚠️ No se convirtió - es null o no es array');
|
|
}
|
|
|
|
} else if ($messageType === 'text') {
|
|
$messageContent = $input['message_content'] ?? null;
|
|
|
|
if (empty($messageContent)) {
|
|
throw new Exception('Contenido del mensaje requerido');
|
|
}
|
|
} else {
|
|
throw new Exception('Tipo de mensaje no soportado');
|
|
}
|
|
|
|
// Obtener ID del admin actual
|
|
$createdBy = $_SESSION['admin_user']['id'] ?? $_SESSION['user_id'] ?? null;
|
|
|
|
// Insertar mensaje programado
|
|
$db->execute(
|
|
"INSERT INTO scheduled_messages (
|
|
user_id,
|
|
template_id,
|
|
template_name,
|
|
template_language,
|
|
template_parameters,
|
|
message_type,
|
|
message_content,
|
|
scheduled_date,
|
|
scheduled_time,
|
|
created_by,
|
|
status
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')",
|
|
[
|
|
$userId,
|
|
$templateId,
|
|
$templateName,
|
|
$templateLanguage,
|
|
$templateParameters,
|
|
$messageType,
|
|
$messageContent,
|
|
$scheduledDate,
|
|
$scheduledTime,
|
|
$createdBy
|
|
]
|
|
);
|
|
|
|
$scheduledId = $db->lastInsertId();
|
|
|
|
error_log('✅ Mensaje programado guardado con ID: ' . $scheduledId);
|
|
|
|
// Log
|
|
writeLog('INFO', "Mensaje programado creado: ID={$scheduledId}, Usuario={$userId}, Fecha={$scheduledDate} {$scheduledTime}");
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Recordatorio programado exitosamente',
|
|
'data' => [
|
|
'id' => $scheduledId,
|
|
'scheduled_date' => $scheduledDate,
|
|
'scheduled_time' => $scheduledTime,
|
|
'user_name' => $user['name'],
|
|
'phone_number' => $user['phone_number']
|
|
]
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
error_log("Error in schedule_message.php: " . $e->getMessage());
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => $e->getMessage()
|
|
]);
|
|
}
|