<?php

namespace IqContent\LaravelFilemanager\Controllers;

use IqContent\LaravelFilemanager\Events\ImageIsRenaming;
use IqContent\LaravelFilemanager\Events\ImageWasRenamed;
use IqContent\LaravelFilemanager\Events\FolderIsRenaming;
use IqContent\LaravelFilemanager\Events\FolderWasRenamed;

class RenameController extends LfmController
{
    public function getRename()
    {
        $old_name = $this->helper->input('file');
        $new_name = $this->helper->input('new_name');



        $old_file = $this->lfm->pretty($old_name);

        return $old_file->path('working_dir');


        $is_directory = $old_file->isDirectory();

        if (empty($new_name)) {
            if ($is_directory) {
                return $this->response('error', parent::getError('folder-name'));
            } else {
                return $this->response('error', parent::getError('file-name'));
            }
        }


        if ($is_directory) {
            if(config('lfm.alphanumeric_directory')){
                $new_name = $this->helper->sanitize($new_name);
                if(preg_match('/[^\w-]/i', $new_name)){
                    return $this->response('error', parent::getError('folder-alnum'));
                }
            }
        }else {
            if (config('lfm.alphanumeric_filename')) {
                $extension = $old_file->extension();
                if ($extension) {
                    $new_name = str_replace('.' . $extension, '', $new_name);
                    $new_name = $this->helper->sanitize($new_name) . '.' . $extension;
                }
            }
        }

        if($this->lfm->setName($new_name)->exists()) {
            return $this->response('error', parent::getError('rename'));
        }

        if (! $is_directory) {
            $extension = $old_file->extension();
            if ($extension) {
                $new_name = str_replace('.' . $extension, '', $new_name) . '.' . $extension;
            }
        }

        $new_file = $this->lfm->setName($new_name)->path('absolute');

        if ($is_directory) {
            event(new FolderIsRenaming($old_file->path(), $new_file));
        } else {
            event(new ImageIsRenaming($old_file->path(), $new_file));
        }

        if ($old_file->hasThumb()) {
            $this->lfm->setName($old_name)->thumb()
                ->move($this->lfm->setName($new_name)->thumb());
        }

        $this->lfm->setName($old_name)
            ->move($this->lfm->setName($new_name));

        //->renameModel($new_name)



        if ($is_directory) {
            event(new FolderWasRenamed($old_file->path(), $new_file));
        } else {
            event(new ImageWasRenamed($old_file->path(), $new_file));
        }

        return parent::$success_response;
    }
}
