<?php
require_once 'auth_check.php';
require_once 'db.php';
session_start();

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized'
    ]);
    exit;
}

try {
    $db = getDB1Connection();

    $query = $db->prepare("SELECT staff_directory FROM utilisateurs WHERE id = ?");
    $query->execute([$_SESSION['user_id']]);
    $result = $query->fetch(PDO::FETCH_ASSOC);

    if (!$result || !$result['staff_directory']) {
        throw new Exception('Staff directory not configured');
    }

    $rootPath = $result['staff_directory'];

    function scanDirectory($dir) {
        $result = [];
        $items = scandir($dir);

        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;

            $path = $dir . '/' . $item;
            if (is_dir($path)) {
                $result[] = [
                    'type' => 'directory',
                    'name' => $item,
                    'path' => str_replace($_SERVER['DOCUMENT_ROOT'], '', $path),
                    'children' => scanDirectory($path)
                ];
            }
        }

        return $result;
    }

    $tree = scanDirectory($rootPath);

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

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}