<?php

declare(strict_types=1);

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

require_once __DIR__ . '/../../src/Auth/AuthManager.php';
require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/Projects/ProjectManager.php';
require_once __DIR__ . '/../../src/Permissions/PermissionManager.php';
require_once __DIR__ . '/../../src/WorkspaceSecurity.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'];
    
    $input = json_decode(file_get_contents('php://input'), true) ?? [];
    
    switch ($method) {
        case 'GET':
            // Get project
            if (!empty($_GET['id'])) {
                $project = ProjectManager::getProject((int)$_GET['id'], $companyId);
                if (!$project) {
                    http_response_code(404);
                    echo json_encode(['error' => 'Project not found']);
                    exit;
                }
                echo json_encode(['success' => true, 'project' => $project]);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'Project ID required']);
            }
            break;
            
        case 'POST':
            // Create project
            if (!PermissionManager::isOwner($userId, $companyId) && !PermissionManager::hasPermission($userId, $companyId, 'projects_create')) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($input['name'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Project name required']);
                exit;
            }
            
            $projectId = ProjectManager::createProject($companyId, $userId, $input);
            echo json_encode(['success' => true, 'project_id' => $projectId]);
            break;
            
        case 'PUT':
            // Update project
            if (!PermissionManager::isOwner($userId, $companyId) && !PermissionManager::hasPermission($userId, $companyId, 'projects_edit')) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($input['id'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Project ID required']);
                exit;
            }
            
            $result = ProjectManager::updateProject((int)$input['id'], $companyId, $userId, $input);
            echo json_encode(['success' => $result]);
            break;
            
        case 'DELETE':
            // Delete project
            if (!PermissionManager::isOwner($userId, $companyId) && !PermissionManager::hasPermission($userId, $companyId, 'projects_delete')) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($_GET['id'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Project ID required']);
                exit;
            }
            
            $result = ProjectManager::deleteProject((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()]);
}
