<?php
/**
 * API: save_virtual_office_message.php
 * SAC 2026 Kernel V4.1.61 MC/MB
 * 
 * Guarda un nuevo mensaje en la oficina virtual.
 */

require_once 'config.php';

if (!isset($_SESSION['user_id'])) {
    response(['error' => 'No autorizado'], 401);
}

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'];
$data = json_decode(file_get_contents('php://input'), true);

if (!$data) {
    response(['error' => 'Datos inválidos'], 400);
}

$sender_id = $user_id;
$sender_name = $user_name;
$receiver_id = intval($data['receiverId']);
$type = $data['type'];
$content = $data['content'];
$attachments = isset($data['attachments']) ? json_encode($data['attachments']) : null;
$is_ai_response = isset($data['isAiResponse']) ? intval($data['isAiResponse']) : 0;

try {
    $stmt = $pdo->prepare("INSERT INTO virtual_office_messages (sender_id, sender_name, receiver_id, type, content, attachments, is_ai_response) 
                           VALUES (?, ?, ?, ?, ?, ?, ?)");
    
    if ($stmt->execute([$sender_id, $sender_name, $receiver_id, $type, $content, $attachments, $is_ai_response])) {
        response(['success' => true, 'id' => $pdo->lastInsertId()]);
    } else {
        response(['error' => 'Error al guardar el mensaje'], 500);
    }
} catch (PDOException $e) {
    response(['error' => 'Error de base de datos: ' . $e->getMessage()], 500);
}
?>