<?php
require_once 'db_connection.php';
require_once 'encryption_config.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'User not logged in.']);
    exit();
}

$data = json_decode(file_get_contents('php://input'), true);

$chatId = $data['chat_id'] ?? null;
$message = $data['message'] ?? null;
$userId = $_SESSION['user_id'];

if (!$chatId || !$message) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Chat ID and message are required.']);
    exit();
}

if (empty($ENCRYPTION_KEY)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Encryption key is missing.']);
    exit();
}

$key = $ENCRYPTION_KEY;
$iv = random_bytes(16);
$cipheredMessage = openssl_encrypt($message, 'aes-256-cbc', $key, 0, $iv);

if (!$cipheredMessage) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to encrypt the message.']);
    exit();
}

try {
    $stmt = $pdo->prepare("
        INSERT INTO messages (conversation_id, sender_id, content, sent_at, iv)
        VALUES (:chat_id, :sender_id, :content, NOW(), :iv)
    ");
    $stmt->execute([
        'chat_id' => $chatId,
        'sender_id' => $userId,
        'content' => $cipheredMessage,
        'iv' => base64_encode($iv),
    ]);

    $messageId = $pdo->lastInsertId();
    echo json_encode(['success' => true, 'message_id' => $messageId]);
} catch (PDOException $e) {
    error_log("Message sending error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'An error occurred while sending the message.']);
}
?>
