<?php

/**
 * UltyScan Web Interface - Workspace Management
 */

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

define('WORKSPACE_DIR', '/usr/share/sniper/loot/workspace');
define('SNIPER_PATH', '/usr/share/sniper/sniper');

// Handle GET requests (list, view)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? 'list';

    if ($action === 'list') {
        $workspaces = [];
        if (is_dir(WORKSPACE_DIR)) {
            $dirs = scandir(WORKSPACE_DIR);
            foreach ($dirs as $dir) {
                if ($dir !== '.' && $dir !== '..' && is_dir(WORKSPACE_DIR . '/' . $dir)) {
                    $workspaces[] = $dir;
                }
            }
        }
        echo json_encode(['workspaces' => $workspaces]);
        exit;
    }

    if ($action === 'view') {
        $name = preg_replace('/[^a-zA-Z0-9\-\_\.]/', '', $_GET['name'] ?? '');
        if (empty($name)) {
            echo json_encode(['error' => 'Invalid workspace name']);
            exit;
        }

        $reportPath = WORKSPACE_DIR . '/' . $name . '/sniper-report.html';
        if (file_exists($reportPath)) {
            // Return relative web path (assuming workspace is web-accessible)
            echo json_encode(['reportPath' => '/loot/workspace/' . $name . '/sniper-report.html']);
        } else {
            echo json_encode(['reportPath' => null, 'message' => 'No report found']);
        }
        exit;
    }
}

// Handle POST requests (delete, export)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $action = $data['action'] ?? '';
    $name = preg_replace('/[^a-zA-Z0-9\-\_\.]/', '', $data['name'] ?? '');

    if (empty($name)) {
        echo json_encode(['success' => false, 'error' => 'Invalid workspace name']);
        exit;
    }

    if ($action === 'delete') {
        $cmd = SNIPER_PATH . ' -w ' . escapeshellarg($name) . ' -d 2>&1';
        // Auto-confirm the deletion
        $output = shell_exec("echo 'y' | $cmd");
        echo json_encode(['success' => true, 'output' => $output]);
        exit;
    }

    if ($action === 'export') {
        $cmd = SNIPER_PATH . ' -w ' . escapeshellarg($name) . ' --export 2>&1';
        $output = shell_exec($cmd);
        echo json_encode([
            'success' => true,
            'path' => '/usr/share/sniper/loot/' . $name . '.tar',
            'output' => $output
        ]);
        exit;
    }
}

echo json_encode(['error' => 'Invalid request']);
