<?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();
}

$chatId = filter_var($_GET['chat_id'] ?? null, FILTER_VALIDATE_INT);
if (!$chatId) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid Chat ID.']);
    exit();
}

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

$key = $ENCRYPTION_KEY;

try {
    $stmt = $pdo->prepare("
        SELECT 
            m.id, 
            m.sender_id, 
            m.content, 
            m.sent_at, 
            m.iv,
            e.username AS sender_name
        FROM messages m
        JOIN emails_v e ON m.sender_id = e.id
        WHERE m.conversation_id = :chat_id
        ORDER BY m.sent_at ASC
    ");
    $stmt->execute(['chat_id' => $chatId]);

    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($messages as &$message) {
        $iv = base64_decode($message['iv']);
        $decryptedContent = openssl_decrypt($message['content'], 'aes-256-cbc', $key, 0, $iv);
        $message['content'] = $decryptedContent ?: 'Decryption failed';
        unset($message['iv']);
    }

    echo json_encode(['success' => true, 'messages' => $messages]);
} catch (PDOException $e) {
    error_log("Error fetching messages: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'An error occurred while fetching messages.']);
}
?>
