<?php
#функция нахождения всех файлов в папке
function managerPathFolder($params) {
    global $config, $path, $_SESSION;
    $lang = include $path . 'main_plugin/manager/lang.php';

    $dirParam = $params['managerPathFolder'] ?? '';
    $directory = realpath($path . ($dirParam ?: ''));
    if ($directory && is_dir($directory)) {
        $files = scandir($directory);
        $data = [];

        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;
            $filePath = $directory . '/' . $file;
            if (is_dir($filePath)) {
                $name = $file;
                $type = $lang[$_SESSION['lng']]['folder'];
                $items = array_diff(scandir($filePath), ['.','..']);
                $size = count($items);
            } else {
                $extension = pathinfo($file, PATHINFO_EXTENSION);
                $name = $extension ? $file : pathinfo($file, PATHINFO_FILENAME);
                $type = $lang[$_SESSION['lng']]['file'];
                $size = filesize($filePath);
            }
            $data[] = [
                'name' => $name,
                'path' => ($dirParam ?: '') . "/" . $file,
                'type' => $type,
                'size' => $size,
                'creationTime' => date('Y-m-d H:i:s', filemtime($filePath)),
            ];
        }
        array_unshift($data, ['rootFolder' => basename($path)]);
        return ['items' => $data];
    }
    return ['error' => "Invalid path: {$dirParam}"];
}

// проверка на существование папки в буфере
function checkFolderForFile($params) {
    global $_SESSION;
    $exists = !empty($_SESSION['managerClipboardFile']['path']);
    return ['exists' => $exists ? 1 : 0];
}

// проверка на существование файла с таким же именем
function checkSameName($params) {
    global $path, $_SESSION;
    if (!empty($params['managerSettingsInsert'])) {
        $clipboard = $_SESSION['managerClipboardFile']['path'];
        $newPath = $path . $params['currentPath'] . '/' . basename($clipboard);
    } else {
        $newPath = $path . $params['currentPath'] . DIRECTORY_SEPARATOR . ($params['name'] ?? '');
    }
    return ['exists' => file_exists($newPath) ? 1 : 0];
}

// проверка буфера обмена
function managerClipboard($params) {
    global $path, $_SESSION;
    $in = $params['managerClipboard'] ?? '';
    $filePath = realpath($path . '/' . $in);
    if ($filePath && file_exists($filePath)) {
        $_SESSION['managerClipboardFile'] = ['path' => $filePath, 'action' => $params['action'] ?? ''];
        return ['message' => 1];
    }
    return ['message' => 0];
}

// вставка из буфера обмена
function managerSettingsInsert($params) {
    global $path, $_SESSION;
    $dest = realpath($path . '/' . ($params['managerSettingsInsert'] ?? ''));
    if (!$dest) return ['message' => 0, 'error' => 'Invalid destination'];
    if (empty($_SESSION['managerClipboardFile']['path'])) return ['message' => 0, 'error' => 'Clipboard empty'];
    $clipboard = $_SESSION['managerClipboardFile']['path'];
    $action = $_SESSION['managerClipboardFile']['action'];
    $newPath = $dest . '/' . basename($clipboard);
    if ($action === 'cut') {
        $ok = rename($clipboard, $newPath);
        return ['message' => $ok ? 1 : 0];
    }
    if ($action === 'copy') {
        $copyDir = function($src, $dst) use (&$copyDir) {
            if (is_dir($src)) {
                if (!is_dir($dst)) mkdir($dst, 0755, true);
                foreach (array_diff(scandir($src), ['.','..']) as $f) {
                    $copyDir($src."/".$f, $dst."/".$f);
                }
            } else {
                copy($src, $dst);
            }
        };
        $copyDir($clipboard, $newPath);
        return ['message' => 1];
    }
    return ['message' => 0, 'error' => 'Invalid action'];
}

// переименование
function managerSettingsRename($params) {
    $curr = realpath($GLOBALS['path'] . '/' . ($params['managerSettingsRename'] ?? ''));
    $new = $params['managerNamePath'] ?? '';
    $ok = $curr && rename($curr, dirname($curr).'/'.$new);
    return ['message' => $ok ? 1 : 0];
}

// удаление
function managerSettingsDelete($params) {
    $target = realpath($GLOBALS['path'] . '/' . ($params['managerSettingsDelete'] ?? ''));
    $del = function($p) use (&$del) {
        if (is_dir($p)) {
            foreach (array_diff(scandir($p), ['.','..']) as $f) $del($p.'/'.$f);
            return rmdir($p);
        }
        return unlink($p);
    };
    $ok = $target ? $del($target) : false;
    return ['message' => $ok ? 1 : 0];
}

// свойства файла/папки
function managerSettingsProperties($params) {
    global $config, $path, $_SESSION;
    $lang = include $path . 'main_plugin/manager/lang.php';
    $curr = realpath($path . '/' . ($params['managerSettingsProperties'] ?? ''));
    if (!$curr) return ['error' => 'not_found'];
    $info = [
        ['label'=>$lang[$_SESSION['lng']]['name'],'value'=>basename($curr)],
        ['label'=>$lang[$_SESSION['lng']]['type'],'value'=>is_dir($curr)?$lang[$_SESSION['lng']]['folder']:$lang[$_SESSION['lng']]['file']],
        ['label'=>$lang[$_SESSION['lng']]['location'],'value'=>str_replace($path,'',dirname('/'.$curr))],
        ['label'=>$lang[$_SESSION['lng']]['size'],'value'=>is_dir($curr)?'-':filesize($curr).' байт'],
        ['label'=>$lang[$_SESSION['lng']]['creation_time'],'value'=>date('Y-m-d H:i:s',filectime($curr))],
        ['label'=>$lang[$_SESSION['lng']]['last_modified_time'],'value'=>date('Y-m-d H:i:s',filemtime($curr))]
    ];
    return ['properties'=>$info];
}

// создание
function managerSettingsCreate($params) {
    $name = $params['managerSettingsCreate'] ?? '';
    $type = $params['managerType'] ?? '';
    $parent = realpath($GLOBALS['path'].'/'.($params['managerNamePath'] ?? ''));
    if (!$parent) return ['message'=>'invalid_parent'];
    $full = $parent.'/'.$name;
    if (file_exists($full)) return ['message'=>'exists'];
    $ok = ($type==='папка')?mkdir($full):file_put_contents($full,'')!==false;
    return ['message'=>$ok?1:'noSuccess'];
}

// открыть страницу
function newPath($params) {
    global $path, $_SESSION;
    $page = simplexml_load_file($path.'/'.($params['newPath']??'').'.page.php');
    $out = [
        'right'=>GetBlock($page->rblock->block,'right'),
        'left'=>GetBlock($page->lblock->block,'left'),
        'content'=>(string)$page->content->{$_SESSION['lng']}
    ];
    $_SESSION['page_url']=$params['newPath']??'';
    return $out;
}

// загрузка файла менеджером
function pathLoad($params) {
    global $path;
    $f = $_FILES['pathFile'] ?? null;
    if (!$f || $f['error']!==UPLOAD_ERR_OK) return ['error'=>'upload_error'];
    $ext=strtolower(pathinfo($f['name'],PATHINFO_EXTENSION));
    if (!in_array($ext,['jpg','png','txt','pdf'])) return ['error'=>'ext'];
    $dir=realpath($path.'/'.($params['pathLoad']??''));
    if (!$dir||!is_writable($dir)) return ['error'=>'dir'];
    $name=pathinfo($f['name'],PATHINFO_FILENAME); $i=1; $final=$name;
    while(file_exists("$dir/$final.$ext")) $final=$name.'_'.($i++);
    $file="$dir/$final.$ext";
    return move_uploaded_file($f['tmp_name'],$file)?['path'=>str_replace('\\','/',$file)]:['error'=>'move'];
}
?>
