<?php
/**
 * ============================================================================
 * chat/ajax/decrypt-message.php - Decrypt Message Endpoint
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../../config/config.php';

header('Content-Type: application/json');
requireLogin();

try {
    $userId = getUserId();
    $messageId = intval($_POST['message_id'] ?? 0);
    
    if (!$messageId) {
        echo json_encode([
            'success' => false,
            'message' => 'Message ID is required'
        ]);
        exit;
    }
    
    $database = new Database();
    $db = $database->getConnection();
    $messageClass = new \App\Message($db);
    
    // Get user's private key (in production, this would come from client-side)
    // For now, we'll retrieve and decrypt it server-side
    $sql = "SELECT encrypted_private_key, salt, iv FROM user_encryption_keys WHERE user_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$userId]);
    $keyData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$keyData) {
        echo json_encode([
            'success' => false,
            'message' => 'Encryption keys not found. Please set up encryption first.'
        ]);
        exit;
    }
    
    // In production, user would enter password to decrypt their private key
    // For demo purposes, we'll use a stored session password or prompt user
    if (!isset($_SESSION['encryption_password'])) {
        echo json_encode([
            'success' => false,
            'needs_password' => true,
            'message' => 'Password required to decrypt messages'
        ]);
        exit;
    }
    
    $password = $_SESSION['encryption_password'];
    
    // Decrypt the private key
    $encryption = new \App\Encryption();
    $privateKey = $encryption::decryptPrivateKey([
        'encrypted_key' => $keyData['encrypted_private_key'],
        'salt' => $keyData['salt'],
        'iv' => $keyData['iv']
    ], $password);
    
    if ($privateKey === false) {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to decrypt private key. Invalid password.'
        ]);
        exit;
    }
    
    // Decrypt the message
    $result = $messageClass->decryptMessage($messageId, $userId, $privateKey);
    
    if ($result['success']) {
        echo json_encode([
            'success' => true,
            'decrypted_message' => nl2br(htmlspecialchars($result['decrypted_message'])),
            'verified' => $result['verified']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => $result['message']
        ]);
    }
    
} catch (Exception $e) {
    error_log('Decrypt message error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Failed to decrypt message: ' . $e->getMessage()
    ]);
}
?>