<?php
/**
 * Server File Browser
 * Lists XML and ZIP files available on the server
 */

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

// Security: Define allowed directories (IMPORTANT - Configure this!)
$allowedDirectories = [
    '/home/user/data',           // Example directory
    '/var/www/uploads',          // Example directory
    '/home/claude',              // Example directory
    // Add your actual data directories here
];

try {
    // Get request data
    $input = json_decode(file_get_contents('php://input'), true);
    $scanDirectory = $input['scan_directory'] ?? '';
    
    // If no directory specified, use first allowed directory
    if (empty($scanDirectory)) {
        $scanDirectory = $allowedDirectories[0] ?? '';
    }
    
    // Security check: Ensure directory is in allowed list
    $isAllowed = false;
    foreach ($allowedDirectories as $allowed) {
        if (strpos(realpath($scanDirectory), realpath($allowed)) === 0) {
            $isAllowed = true;
            break;
        }
    }
    
    if (!$isAllowed) {
        throw new Exception('Access to this directory is not allowed');
    }
    
    if (!is_dir($scanDirectory)) {
        throw new Exception('Directory does not exist');
    }
    
    // Scan for XML and ZIP files
    $files = [];
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($scanDirectory, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $ext = strtolower($file->getExtension());
            
            if ($ext === 'xml' || $ext === 'zip') {
                $files[] = [
                    'name' => $file->getFilename(),
                    'path' => $file->getPathname(),
                    'size' => $file->getSize(),
                    'modified' => $file->getMTime(),
                    'type' => $ext
                ];
            }
        }
    }
    
    // Sort by name
    usort($files, function($a, $b) {
        return strcmp($a['name'], $b['name']);
    });
    
    echo json_encode([
        'success' => true,
        'files' => $files,
        'directory' => $scanDirectory,
        'count' => count($files)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
