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

$db2 = getDB2Connection();
$action = isset($_POST['action']) ? $_POST['action'] : '';

switch ($action) {
    case 'get_documents':
        // Retrieve user's personal documents
        $stmt = $db2->prepare("SELECT * FROM workspaces WHERE user_id = ? AND project_id IS NULL ORDER BY updated_at DESC");
        $stmt->execute([$_SESSION['user_id']]);
        $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'documents' => $documents]);
        break;
        
    case 'get_projects':
        // Retrieve all projects
        $stmt = $db2->query("SELECT * FROM workspace_projects ORDER BY created_at DESC");
        $projects = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // For each project, get associated documents (logs)
        foreach ($projects as &$project) {
            $stmt = $db2->prepare("SELECT * FROM workspaces WHERE project_id = ? ORDER BY updated_at DESC");
            $stmt->execute([$project['id']]);
            $project['logs'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        
        header('Content-Type: application/json');
        echo json_encode(['success' => true, 'projects' => $projects]);
        break;
        
    case 'get_document':
        // Retrieve a specific document
        $document_id = isset($_POST['document_id']) ? $_POST['document_id'] : 0;
        $stmt = $db2->prepare("SELECT * FROM workspaces WHERE id = ?");
        $stmt->execute([$document_id]);
        $document = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($document && ($document['user_id'] == $_SESSION['user_id'] || $document['project_id'] !== null)) {
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'document' => $document]);
        } else {
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Document not found or access denied']);
        }
        break;
        
    case 'save_document':
        $document_id = isset($_POST['document_id']) ? $_POST['document_id'] : 0;
        $title = isset($_POST['title']) ? $_POST['title'] : 'Untitled';
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        $project_id = isset($_POST['project_id']) ? $_POST['project_id'] : null;
        
        if ($document_id) {
            // Update existing document
            $stmt = $db2->prepare("SELECT * FROM workspaces WHERE id = ?");
            $stmt->execute([$document_id]);
            $document = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($document && ($document['user_id'] == $_SESSION['user_id'] || (isset($_SESSION['role']) && $_SESSION['role'] == 1))) {
                $stmt = $db2->prepare("UPDATE workspaces SET title = ?, content = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$title, $content, $document_id]);
                
                header('Content-Type: application/json');
                echo json_encode(['success' => true, 'document_id' => $document_id]);
            } else {
                header('Content-Type: application/json');
                echo json_encode(['error' => 'Permission denied']);
            }
        } else {
            // Create new document
            $stmt = $db2->prepare("INSERT INTO workspaces (title, content, user_id, project_id, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())");
            $stmt->execute([$title, $content, $_SESSION['user_id'], $project_id]);
            
            $document_id = $db2->lastInsertId();
            
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'document_id' => $document_id]);
        }
        break;
        
    case 'delete_document':
        $document_id = isset($_POST['document_id']) ? $_POST['document_id'] : 0;
        
        $stmt = $db2->prepare("SELECT * FROM workspaces WHERE id = ?");
        $stmt->execute([$document_id]);
        $document = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($document && ($document['user_id'] == $_SESSION['user_id'] || (isset($_SESSION['role']) && $_SESSION['role'] == 1))) {
            $stmt = $db2->prepare("DELETE FROM workspaces WHERE id = ?");
            $stmt->execute([$document_id]);
            
            header('Content-Type: application/json');
            echo json_encode(['success' => true]);
        } else {
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Permission denied']);
        }
        break;
        
    case 'create_project':
        $name = isset($_POST['name']) ? $_POST['name'] : '';
        $description = isset($_POST['description']) ? $_POST['description'] : '';
        
        if (!empty($name)) {
            $stmt = $db2->prepare("INSERT INTO workspace_projects (name, description, created_by, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->execute([$name, $description, $_SESSION['user_id']]);
            
            $project_id = $db2->lastInsertId();
            
            header('Content-Type: application/json');
            echo json_encode(['success' => true, 'project_id' => $project_id]);
        } else {
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Project name is required']);
        }
        break;
        
    case 'associate_to_project':
        $document_id = isset($_POST['document_id']) ? $_POST['document_id'] : 0;
        $project_id = isset($_POST['project_id']) ? $_POST['project_id'] : 0;
        
        if ($document_id && $project_id) {
            $stmt = $db2->prepare("SELECT * FROM workspaces WHERE id = ?");
            $stmt->execute([$document_id]);
            $document = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($document && $document['user_id'] == $_SESSION['user_id']) {
                $stmt = $db2->prepare("UPDATE workspaces SET project_id = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$project_id, $document_id]);
                
                header('Content-Type: application/json');
                echo json_encode(['success' => true]);
            } else {
                header('Content-Type: application/json');
                echo json_encode(['error' => 'Permission denied']);
            }
        } else {
            header('Content-Type: application/json');
            echo json_encode(['error' => 'Document ID and Project ID are required']);
        }
        break;
        
    default:
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Invalid action']);
}
?>