111 lines
4.2 KiB
PHP
111 lines
4.2 KiB
PHP
<?php
|
|
/**
|
|
* API: Crear orden médica desde conversación de WhatsApp
|
|
*
|
|
* GET ?solo_paciente=1&conversation_id=X → obtiene/crea paciente del contacto
|
|
* POST { paciente_id, conversation_id, local_file, media_message_id, ... }
|
|
* → crea lab_ordenes_medicas
|
|
*/
|
|
require_once __DIR__ . '/../../config/config.php';
|
|
require_once __DIR__ . '/../../classes/Database.php';
|
|
require_once __DIR__ . '/../../classes/lab/ActividadAdmin.php';
|
|
require_once __DIR__ . '/../../classes/lab/Paciente.php';
|
|
require_once __DIR__ . '/../../classes/lab/OrdenMedica.php';
|
|
|
|
// Helpers inline (similar a _helpers.php pero sin incluir todas las clases de nuevo)
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('X-Content-Type-Options: nosniff');
|
|
|
|
requireAuthentication();
|
|
|
|
$adminId = (int)($_SESSION['admin_user']['id'] ?? 0);
|
|
$db = Database::getInstance();
|
|
|
|
// ── GET: solo_paciente ─────────────────────────────────────────────────────
|
|
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['solo_paciente'])) {
|
|
$convId = (int)($_GET['conversation_id'] ?? 0);
|
|
$userId = (int)($_GET['user_id'] ?? 0);
|
|
|
|
if (!$convId && !$userId) {
|
|
echo json_encode(['success' => false, 'error' => 'conversation_id o user_id requerido']);
|
|
exit;
|
|
}
|
|
|
|
// Obtener user_id y phone_number: por conversation_id o directamente por user_id
|
|
if ($convId) {
|
|
$conv = $db->fetch(
|
|
'SELECT c.id, c.user_id, u.phone_number, u.name AS whatsapp_name
|
|
FROM conversations c
|
|
JOIN users u ON u.id = c.user_id
|
|
WHERE c.id = ?',
|
|
[$convId]
|
|
);
|
|
} else {
|
|
$conv = $db->fetch(
|
|
'SELECT u.id AS user_id, u.phone_number, u.name AS whatsapp_name
|
|
FROM users u
|
|
WHERE u.id = ?',
|
|
[$userId]
|
|
);
|
|
}
|
|
|
|
if (!$conv) {
|
|
echo json_encode(['success' => false, 'error' => 'Conversación / usuario no encontrado']);
|
|
exit;
|
|
}
|
|
|
|
$pacienteRepo = new Paciente();
|
|
$pacienteId = $pacienteRepo->obtenerOCrearDesdeWhatsapp($conv['user_id']);
|
|
$paciente = $pacienteRepo->obtener($pacienteId);
|
|
echo json_encode(['success' => true, 'paciente' => $paciente]);
|
|
exit;
|
|
}
|
|
|
|
// ── POST: crear orden ──────────────────────────────────────────────────────
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
|
|
exit;
|
|
}
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
if (!$input) {
|
|
echo json_encode(['success' => false, 'error' => 'Datos inválidos']);
|
|
exit;
|
|
}
|
|
|
|
$pacienteId = (int)($input['paciente_id'] ?? 0);
|
|
if (!$pacienteId) {
|
|
echo json_encode(['success' => false, 'error' => 'paciente_id requerido']);
|
|
exit;
|
|
}
|
|
|
|
// Construir datos de la orden
|
|
$datos = [
|
|
'paciente_id' => $pacienteId,
|
|
'conversation_id' => !empty($input['conversation_id']) ? (int)$input['conversation_id'] : null,
|
|
'local_file' => $input['local_file'] ?? null,
|
|
'media_message_id' => $input['media_message_id'] ?? null,
|
|
'medico_nombre' => $input['medico_nombre'] ?? null,
|
|
'fecha_orden' => !empty($input['fecha_orden']) ? $input['fecha_orden'] : null,
|
|
'examenes_solicitados'=> $input['examenes_solicitados']?? null,
|
|
'requiere_ayuno' => isset($input['requiere_ayuno']) ? (int)$input['requiere_ayuno'] : 0,
|
|
'horas_ayuno' => !empty($input['horas_ayuno']) ? (int)$input['horas_ayuno'] : null,
|
|
'notas_admin' => $input['notas_admin'] ?? null,
|
|
'estado' => 'pendiente',
|
|
];
|
|
|
|
try {
|
|
$orden = new OrdenMedica();
|
|
$ordenId = $orden->crear($datos, $adminId);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'orden_id' => $ordenId,
|
|
'message' => "Orden médica #$ordenId creada correctamente",
|
|
]);
|
|
} catch (Exception $e) {
|
|
error_log('[lab/crear_desde_whatsapp] ' . $e->getMessage());
|
|
echo json_encode(['success' => false, 'error' => 'Error interno: ' . $e->getMessage()]);
|
|
}
|