<?php
/**
 * File Editor API — List directory tree (admin only)
 */
require_once __DIR__ . '/../../app/core/bootstrap.php';
auth_require_login();
header('Content-Type: application/json');

$user = auth_user();
if (($user['role'] ?? '') !== 'admin') {
    http_response_code(403); echo json_encode(['ok'=>false,'error'=>'Admin only']); exit;
}

$ROOT = realpath(__DIR__ . '/../../');

// Directories to show (relative to root)
$SHOW_DIRS = ['public', 'app', 'migrations', 'scripts'];
// Extensions to show in tree
$SHOW_EXT  = ['php','css','js','html','json','txt','sql','md','yml','yaml','xml','htaccess'];
// Dirs to skip entirely
$SKIP_DIRS = ['uploads','node_modules','.git','vendor','storage'];

function scan_dir(string $dir, string $root, array $skipDirs, array $showExt, int $depth = 0): array {
    if ($depth > 6) return [];
    $items = [];
    try {
        $entries = scandir($dir);
    } catch (Throwable $e) { return []; }
    
    foreach ($entries as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        $abs = $dir . DIRECTORY_SEPARATOR . $entry;
        $rel = ltrim(str_replace($root, '', $abs), '/\\');
        $rel = str_replace('\\', '/', $rel);

        if (is_dir($abs)) {
            if (in_array($entry, $skipDirs, true)) continue;
            $children = scan_dir($abs, $root, $skipDirs, $showExt, $depth + 1);
            if ($children) {
                $items[] = ['type'=>'dir','name'=>$entry,'path'=>$rel,'children'=>$children];
            }
        } elseif (is_file($abs)) {
            $ext = strtolower(pathinfo($entry, PATHINFO_EXTENSION));
            if (!in_array($ext, $showExt, true) && $entry !== '.htaccess') continue;
            $items[] = ['type'=>'file','name'=>$entry,'path'=>$rel,'ext'=>$ext,'size'=>filesize($abs)];
        }
    }
    // Sort: dirs first, then files
    usort($items, fn($a,$b) => ($a['type']==='dir'?0:1) <=> ($b['type']==='dir'?0:1) ?: strcmp($a['name'],$b['name']));
    return $items;
}

$tree = [];
foreach ($SHOW_DIRS as $d) {
    $abs = $ROOT . DIRECTORY_SEPARATOR . $d;
    if (!is_dir($abs)) continue;
    $children = scan_dir($abs, $ROOT, $SKIP_DIRS, $SHOW_EXT);
    $tree[] = ['type'=>'dir','name'=>$d,'path'=>$d,'children'=>$children];
}

echo json_encode(['ok'=>true,'tree'=>$tree]);
