<?php

namespace Mnv\Admin\Controllers;

if (!defined('MNV_CMS')) {
    die('Hacking attempt!');
}

use Mnv\Core\AdminMnv;

use Mnv\Core\Collections\Contracts\Filesystem\FileNotFoundException;
use Mnv\Core\Filesystem\FilesystemManager;

/**
 * Class FileManagerAdmin
 * @package Mnv\Admin\Controllers
 */
class FileManagerAdmin extends AdminMnv
{

    public function fetch()
    {

        $response = array();
        $downloadableFile = null;

        $this->smarty->assign('activeItem', 'filemanager');
        $this->smarty->assign('title', lang('fileManager:title'));

        if ($this->request->hasFile('file')) {
            $downloadableFile = $this->request->files->get('file', '');
        }

        $path   = $this->request->get('path', '/');
        $file   = $this->request->get('file', '');
        $folder = $this->request->get('folder');

        $filesystem = new FilesystemManager('', $path);

        if ($filesystem->path != '') {
            $upPath = realpath($filesystem->realPath . '/../');
            $upPath = str_replace(GLOBAL_ROOT, '', $upPath);
        } else {
            $upPath = $filesystem->path;
        }

        $this->smarty->assign('path', $filesystem->path);
        $this->smarty->assign('upPath', $upPath);

        /** загрузка нового файла */
        if ($this->action == 'upload') {

            if (preg_match('/[^0-9a-zA-Z\-_\. ]/i', $downloadableFile->getClientOriginalName())) {
                $this->errors['fileNameCharacters'] = true;
                $response = array('status' => 400, 'message' => lang('fileManager:errors:5'));
            }
            if (empty($this->errors)) {
                if ($downloadableFile->move($filesystem->realPath,  $downloadableFile->getClientOriginalName())) {
                    $response = array('status' => 200, 'message' => lang('fileManager:messages:1'));
                } else {
                    $response = array('status' => 500, 'message' => lang('fileManager:errors:0'));
                }
            }

            response()->json($response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();

        }

        /** добавление директории */
        else if ($this->action == 'add_folder') {

            if (preg_match('/[^0-9a-zA-Z\-_\. ]/i', $folder['name'])) $this->errors['fileNameCharacters'] = true;
            if (empty($this->errors)) {
                if (!$filesystem->isDirectory($filesystem->realPath . $folder['name'])) {
                    $filesystem->makeDirectory($filesystem->realPath . $folder['name']);
                    $this->messages['folder'] = true;
                } else {
                    $this->errors['folder'] = true;
                }
            }
        }

        /** удаление файла / директории */
        else if ($this->action == 'remove') {
            if ($filesystem->isFile($filesystem->realPath . $file['name'])) {
                if ($filesystem->delete($filesystem->realPath . $file['name'])) {
                    $this->messages['deletedFile'] = true;
                } else {
                    $this->errors['deleteFile'] = true;
                }
            } else if ($filesystem->isDirectory($filesystem->realPath . $file['name'])) {
                if ($filesystem->deleteDirectory($filesystem->realPath . $file['name'])) {
                    $this->messages['deletedFolder'] = true;
                } else {
                    $this->errors['deleteFolder'] = true;
                }
            }
        }

        /** редактирование файла */
        else if ($this->action == 'edit') {
            try {
                $file['content'] = $filesystem->get($filesystem->realPath . $file['name'], false);
                $this->smarty->assign('file', $file);
            } catch (FileNotFoundException $e) {
                $this->errors['fileNotFound'] = true;
            }
        }

        /** сохранение редактируемого файла */
        else if ($this->action == 'save') {
            if ($filesystem->exists($filesystem->realPath . $file['name'])) {
                if ($filesystem->put($filesystem->realPath . $file['name'], $file['content'])) {
                    $this->messages['saved'] = true;
                } else {
                    $this->errors['save'] = true;
                }
            }
        }

        /** получение всех директорий и файла по указанному пути */
//        var_dump($filesystem->realPath);
//        var_dump($filesystem->path);
        if ($filesystem->exists($filesystem->realPath)) {
            $list['dirs'] = $filesystem->getDirectories(FilesystemManager::$_hidden_folders);
            $files = $filesystem->files($filesystem->realPath, false);
            foreach ($files as $file) {
                $list['files'][] = [
                    'is_dir'    => false,
                    'path'      => $file->getPath(),
                    'name'      => $file->getFilename(),
                    'size'      => $file->getSize(),
                    'mtime'     => is_writable($file) ? $filesystem->lastModified($file) : ''
                ];
            }
        }


        if (!empty($list)) $this->smarty->assign('list', $list);

        if (!empty($this->errors)) $this->smarty->assign('errors', $this->errors);
        if (!empty($this->messages)) $this->smarty->assign('messages', $this->messages);
        if (!empty($this->action)) $this->smarty->assign('action', $this->action);

        if ($this->permissions('filemanager')) {
            return $this->smarty->fetch('views/file-manager/index.tpl');
        }

        $this->smarty->assign('title', 'Access Denied');
        return $this->smarty->fetch('accessIsDenied.tpl');
    }


}

