<?php

declare(strict_types=1);

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

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

try {
    AuthManager::requireAuth();
    
    $user = AuthManager::getCurrentUser();
    $company = WorkspaceSecurity::getCurrentWorkspace();
    
    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 task or list tasks
            if (!empty($_GET['id'])) {
                if (!PermissionManager::hasPermission($userId, $companyId, 'tasks_view')) {
                    http_response_code(403);
                    echo json_encode(['error' => 'Permission denied']);
                    exit;
                }
                
                $taskId = (int)$_GET['id'];
                $task = TaskManager::getTask($taskId, $companyId);
                
                if (!$task) {
                    http_response_code(404);
                    echo json_encode(['error' => 'Task not found']);
                    exit;
                }
                
                echo json_encode(['success' => true, 'task' => $task]);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'Task ID required']);
            }
            break;
            
        case 'POST':
            // Create task
            if (!PermissionManager::hasPermission($userId, $companyId, 'tasks_create')) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($input['project_id']) || empty($input['title'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Project ID and title required']);
                exit;
            }
            
            $taskId = TaskManager::createTask(
                (int)$input['project_id'],
                $companyId,
                $userId,
                $input
            );
            
            echo json_encode(['success' => true, 'task_id' => $taskId]);
            break;
            
        case 'PUT':
            // Update task
            if (!PermissionManager::hasPermission($userId, $companyId, 'tasks_edit')) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($input['id'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Task ID required']);
                exit;
            }
            
            $result = TaskManager::updateTask(
                (int)$input['id'],
                $companyId,
                $userId,
                $input
            );
            
            echo json_encode(['success' => $result]);
            break;
            
        case 'DELETE':
            // Delete task
            if (!PermissionManager::hasPermission($userId, $companyId, 'tasks_delete')) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($_GET['id'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Task ID required']);
                exit;
            }
            
            $result = TaskManager::deleteTask(
                (int)$_GET['id'],
                $companyId,
                $userId
            );
            
            echo json_encode(['success' => $result]);
            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()]);
}
