<?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($_POST['id']) || empty($_POST['id'])) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'No document ID provided']);
    exit;
}

$document_id = $_POST['id'];
$title = $_POST['title'] ?? 'Untitled Document';
$content = $_POST['content'] ?? '';

try {
    $db = getDB1Connection(); // Utilise la connexion appropriée
    
    // Vérifier si l'utilisateur a le droit de modifier ce document
    $check = $db->prepare("SELECT user_id FROM workspace_documents WHERE id = :id");
    $check->bindParam(':id', $document_id);
    $check->execute();
    
    $doc = $check->fetch(PDO::FETCH_ASSOC);
    
    if (!$doc || $doc['user_id'] != $_SESSION['user_id']) {
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Document not found or access denied']);
        exit;
    }
    
    // Mettre à jour le document
    $stmt = $db->prepare("UPDATE workspace_documents SET 
                        title = :title, 
                        content = :content, 
                        updated_at = NOW() 
                        WHERE id = :id");
    $stmt->bindParam(':title', $title);
    $stmt->bindParam(':content', $content);
    $stmt->bindParam(':id', $document_id);
    $stmt->execute();
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true
    ]);
} catch (PDOException $e) {
    header('Content-Type: application/json');
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}