<?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'];
    
    // Check permission
    $isOwner = PermissionManager::isOwner($userId, $companyId);
    $canManage = $isOwner || PermissionManager::hasPermission($userId, $companyId, 'projects_manage');
    
    // Get request data
    $input = json_decode(file_get_contents('php://input'), true) ?? [];
    
    switch ($method) {
        case 'GET':
            // Get all categories
            $categories = ProjectManager::getCategories($companyId);
            echo json_encode(['success' => true, 'categories' => $categories]);
            break;
            
        case 'POST':
            // Create category
            if (!$canManage) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($input['name'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Category name required']);
                exit;
            }
            
            $categoryId = ProjectManager::createCategory($companyId, [
                'name' => $input['name'],
                'color' => $input['color'] ?? '#3B82F6',
                'icon' => $input['icon'] ?? 'folder',
                'sort_order' => $input['sort_order'] ?? 0
            ]);
            
            echo json_encode(['success' => true, 'category_id' => $categoryId]);
            break;
            
        case 'PUT':
            // Update category
            if (!$canManage) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($input['id'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Category ID required']);
                exit;
            }
            
            $pdo = getPDO();
            $fields = [];
            $params = [];
            
            if (isset($input['name'])) {
                $fields[] = 'name = ?';
                $params[] = $input['name'];
            }
            if (isset($input['color'])) {
                $fields[] = 'color = ?';
                $params[] = $input['color'];
            }
            if (isset($input['icon'])) {
                $fields[] = 'icon = ?';
                $params[] = $input['icon'];
            }
            if (isset($input['sort_order'])) {
                $fields[] = 'sort_order = ?';
                $params[] = (int)$input['sort_order'];
            }
            
            if (!empty($fields)) {
                $params[] = (int)$input['id'];
                $params[] = $companyId;
                
                $sql = 'UPDATE project_categories SET ' . implode(', ', $fields) . ' WHERE id = ? AND company_id = ?';
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
            }
            
            echo json_encode(['success' => true]);
            break;
            
        case 'DELETE':
            // Delete category
            if (!$canManage) {
                http_response_code(403);
                echo json_encode(['error' => 'Permission denied']);
                exit;
            }
            
            if (empty($_GET['id'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Category ID required']);
                exit;
            }
            
            $pdo = getPDO();
            $stmt = $pdo->prepare('DELETE FROM project_categories WHERE id = ? AND company_id = ?');
            $stmt->execute([(int)$_GET['id'], $companyId]);
            
            echo json_encode(['success' => true]);
            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()]);
}
