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

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

if (!isset($_SESSION['user_id']) || !isset($_GET['path'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid request'
    ]);
    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'];
    $requestedPath = $rootPath . $_GET['path'];

    if (!str_starts_with(realpath($requestedPath), realpath($rootPath))) {
        throw new Exception('Access denied');
    }

    $files = [];
    if (is_dir($requestedPath)) {
        $items = scandir($requestedPath);
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;

            $path = $requestedPath . '/' . $item;
            $relativePath = str_replace($rootPath, '', $path);

            $files[] = [
                'name' => $item,
                'path' => $relativePath,
                'type' => is_dir($path) ? 'directory' : getFileType($item),
                'size' => is_file($path) ? filesize($path) : 0,
                'modified' => date('Y-m-d H:i:s', filemtime($path))
            ];
        }
    }

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

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

function getFileType($filename) {
    $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $types = [
        'txt' => 'text',
        'md' => 'text',
        'pdf' => 'pdf',
        'jpg' => 'image',
        'jpeg' => 'image',
        'png' => 'image',
        'gif' => 'image'
    ];
    return $types[$extension] ?? 'default';
}