<?php

namespace Mnv\Admin\Controllers;

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

use Mnv\Core\AdminMnv;
use Mnv\Core\Filesystem\FilesystemManager;
use Mnv\Core\Uploads\Uploader;

/**
 * Class UploadsAdmin
 * @package Mnv\Admin\Controllers
 */
class UploadsAdmin extends AdminMnv
{
    // TODO: Сделать сортировку по дате (и по расширению)

    public function fetch()
    {
        $options = [];
        $path       = $this->request->get('path', '/');
        $folder     = $this->request->get('folder', '');
        $fileIds    = $this->request->get('fileIds', '');


        $name     = $this->request->get('name','');
        $query    = $this->request->get('query','');
        $type     = $this->request->get('type', '');
        $filters  = $this->request->get('filters', '');

//        print_r($this->request);
        $filesystem = new FilesystemManager('/uploads', $path);


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

        /** добавление новой директории */
        if ($this->action == 'new_folder') {
            if (!preg_match('/[^0-9a-zA-Z\-_\. ]/i', $name)) {
                $name = preg_replace("/\s+/", "_", $name);
                if (!$filesystem->isDirectory($filesystem->realPath . $name)) {
                    if ($filesystem->makeDirectory($filesystem->realPath . $name)) {
                        /** directory large */
                        $filesystem->makeDirectory($filesystem->realPath . $name . '/large');
                        /** directory medium */
                        $filesystem->makeDirectory($filesystem->realPath . $name . '/medium');
                        /** directory small */
                        $filesystem->makeDirectory($filesystem->realPath . $name . '/small');
                    }

                    $this->response = array('status' => 200, 'message' => lang('fileManager:messages:0'), 'directory' => $name, 'type' => 'success');
                }
            } else {
                $this->response = array('status' => 500, 'error' => lang('fileManager:errors:5'), 'directory' => '', 'type' => 'error');
            }

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

        /** Удаление директории если она пустая */
        else if ($this->action == 'delete_folder') {

            if ($filesystem->exists($filesystem->realPath . $folder)) {
                $files = $filesystem->allFiles($filesystem->realPath . $folder);
                if (empty($files)) {
                    $filesystem->deleteDirectory($filesystem->realPath . $folder);
                    $this->response = array('status' => 200, 'message' => lang('fileManager:messages:3'), 'folder' => $filesystem->realPath . $folder, 'type' => 'success');
                } else {
                    $this->response = array('status' => 500, 'message' => lang('fileManager:directoryNotEmpty'), 'folder' =>$filesystem->realPath . $folder, 'type' => 'error');
                }
            }

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

        /** Удаление директории с подтверждением если она не пустая */
        else if ($this->action == 'confirm_remove_folder') {
            if ($filesystem->exists($filesystem->realPath . $folder)) {
                $files = $filesystem->allFiles($filesystem->realPath . $folder);
                if (!empty($files)) {
                    foreach ($files as $file) {
                        $childDirectory = $filesystem->basename($file->getPath());
                        if (!in_array($childDirectory, FilesystemManager::$_hidden_image_folders)) {
                            $filesystem->deleteAllFilesThisDirectory($childDirectory);
                        }
                    }
                }
                $filesystem->deleteDirectory($filesystem->realPath . $folder);
                $this->response = array('status' => 200, 'message' => lang('fileManager:messages:3'), 'folder' => $filesystem->realPath . $folder, 'type' => 'success');
            } else {
                $this->response = array('status' => 500, 'message' => lang('fileManager:errors:3'), 'folder' => $filesystem->realPath . $folder, 'type' => 'error');
            }
            response()->json($this->response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => $this->config['charset']], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }

        /** Удаление файла / удаление файлов */
        else if ($this->action == 'remove') {
            if (!empty($fileIds)) {
                if ($filesystem->deleteFiles($fileIds)) {
                    $this->response = array('status' => 200, 'message' => lang('fileManager:messages:9'), 'type' => 'success');
                } else {
                    $this->response = array('status' => 500, 'message' => lang('fileManager:errors:12'), 'type' => 'error');
                }
            } else {
                $this->response = array('status' => 500, 'message' => 'Пустой ID файла, ищите ошибку)', 'type' => 'error');
            }

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

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

            $upload = new Uploader($options, $filesystem->realPath, $filesystem->path, $this->manager['userId']);
            if ($upload->validate()) {
                $upload->upload();
            }

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

        /** получение всего что есть в папке uploads */
        else if ($this->action == 'read_more') {
//            print_r($filesystem->path);
            if ($filesystem->exists($filesystem->realPath)) {
                $list['dirs']       = $filesystem->getDirectories(FilesystemManager::$_hidden_image_folders, true);
                $where['directory'] = $filesystem->basename($filesystem->realPath);
                $list['files']      = $filesystem->all($where, $query, $filters, $type, $this->manager['userId'], $this->limit = 28, $this->page);
                $pagination = $filesystem->getTotalPage($where, $query, $filters, $type, $this->manager['userId'], $this->limit = 28, $this->page);

                $this->jsonReturn($filesystem, $where, $list, $pagination);

            } else {
                $this->response = array('status' => 403, 'error' => 'Такая директория не найдена', 'type' => 'error');
            }
            response()->json($this->response, \Mnv\Http\Response::HTTP_OK, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => $this->config['charset']], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT)->send();
            exit();
        }

        /** подгрузка файлов при скролле блока */
        else if ($this->action == 'read_more_files') {
            $where['directory'] = $filesystem->basename($filesystem->realPath);
            $list['files'] = $filesystem->all($where, $query, $filters, $type, $this->manager['userId'], $this->limit = 28, $this->page);
            $pagination = $filesystem->getTotalPage($where, $query, $filters, $type, $this->manager['userId'], $this->limit = 28, $this->page);

            $this->jsonReturn($filesystem, $where, $list, $pagination);
        }

        /** получение файла по конкретному запросу */
        else if ($this->action == 'get_file') {

            $listArr = array();

            if (!empty($fileIds)) {
                foreach ($fileIds as $id) {
                    $listArr[] = $filesystem->read($id);
                }
            }

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


    }

    private function jsonReturn($filesystem, $where, $list, $pagination)
    {
        try {
            $this->smarty->assign('list', $list);
            $items = $this->smarty->fetch('module/uploads-file-list.tpl');
//            $items = $list;
            $this->response = array('status' => 200, 'items' => $items, 'path' => $filesystem->path, 'directory' => $where['directory'], 'pagination' => $pagination, 'type' => 'success');
        } catch (\SmartyException|\Exception $e) {
            $this->response = array('status' => 403, 'items'=> $e->getMessage(), 'directory' => $where['directory'], 'pagination' => $pagination, 'type' => 'error');
        }

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

	
