<?php

declare(strict_types=1);

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

require_once __DIR__ . '/../../src/secure_workspace.php';
require_once __DIR__ . '/../../src/Auth/AuthManager.php';
require_once __DIR__ . '/../../src/Projects/TaskManager.php';
require_once __DIR__ . '/../../src/Permissions/PermissionManager.php';

try {
    AuthManager::requireAuth();
    
    $user = AuthManager::getCurrentUser();
    $company = $company ?? null;
    
    if (!$company) {
        http_response_code(403);
        echo json_encode(['error' => 'No workspace selected']);
        exit;
    }
    
    $companyId = (int)$company['id'];
    $userId = (int)$user['id'];
    $method = $_SERVER['REQUEST_METHOD'];
    
    // Get request data
    $input = json_decode(file_get_contents('php://input'), true) ?? [];
    
    switch ($method) {
        case 'GET':
            // Get comments for a task
            if (!PermissionManager::hasPermission($userId, $companyId, 'tasks_view')) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($_GET['task_id'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Task ID required']);
                exit;
            }
            
            $comments = TaskManager::getTaskComments((int)$_GET['task_id']);
            echo json_encode(['success' => true, 'comments' => $comments]);
            break;
            
        case 'POST':
            // Add comment
            if (!PermissionManager::hasPermission($userId, $companyId, 'tasks_view')) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($input['task_id']) || empty($input['comment'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Task ID and comment required']);
                exit;
            }
            
            $commentId = TaskManager::addComment(
                (int)$input['task_id'],
                $userId,
                $input['comment']
            );
            
            echo json_encode(['success' => true, 'comment_id' => $commentId]);
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
