<?php
require_once 'auth_check.php';
require_once 'db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'No document ID provided']);
    exit;
}

$document_id = $_GET['id'];

try {
    $db = getDB1Connection(); // Utilise la connexion appropriée
    $stmt = $db->prepare("SELECT * FROM workspace_documents WHERE id = :id AND user_id = :user_id");
    $stmt->bindParam(':id', $document_id);
    $stmt->bindParam(':user_id', $_SESSION['user_id']);
    $stmt->execute();
    
    $document = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$document) {
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Document not found or access denied']);
        exit;
    }
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'document' => $document
    ]);
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}