<?php 

class AdminMediaManagerController extends Controller {
    
    public function __construct(){ 
        $this->beforeFilter('csrf', array('on' => 'post'));
        $this->beforeFilter('backend.auth.role:Administrator,User,HR');    
    }
    
    public function getIndex() {                         
    }
    
    public function getList() {
        $page = Input::get("current");
        $sort = Input::get("sort");
        $search = Input::get("searchPhrase");    

        MediaItem::resolveConnection()->getPaginator()->setCurrentPage($page);
        if (!empty($search)) {
            $query = MediaItem::where(function ($query) use ($search) {
                $query->orWhere('filename', 'like', "%{$search}%");
            });
        } else {
            $query = MediaItem::query();
        }
        if (empty($sort)) {
            $rows = $query->paginate(Input::get("rowCount"));    
        } else {
            foreach ($sort as $field => $direction) {
                if(empty($direction) || !str_is(strtolower($direction),"desc")){
                    $order_direction = "asc";    
                }
                $rows = $query->orderBy($field, strtolower($direction))->paginate(Input::get("rowCount"));
                break;
            }
        }

        $result = array(
            "total"             => $rows->getTotal(),
            "current"           => $rows->getCurrentPage(), 
            "rowCount"          => Input::get("rowCount"),
            "rows"              => $rows->getCollection()  
        );
        
        return Response::json($result); 
    }
    
    public function getMedia($mediaId) {
        if (!is_numeric($mediaId)) {
            App::abort(400);
        }
        $mediaItem = MediaItem::find($mediaId);
        if (!$mediaItem) {
            return Response::json(null);
        }
        return Response::json($mediaItem);
    }
    
    public function postMedia($mediaId) {
        if (!is_numeric($mediaId)) {
            App::abort(400);
        }
        
        $data = array(
            'title' => Input::get('title', null, true),
            'alt'   => Input::get('alt', null, true),
            'author'   => Input::get('author', null, true)
        );
        
        $validator = Validator::make(
            $data,
            array(
                'title' => 'max:150',
                'alt' => 'max:150',
                'author' => 'max:150'
            )
        );
        
        if ($validator->fails()) {
            $result = array (
                'success' => false,
                'error' => 'validation',
                'validation'  => $validator->messages()->toArray()
            );
            return Response::json($result);
        }
        
        $mediaItem = MediaItem::find($mediaId);
        if (!$mediaItem) {
            $result = array (
                'success' => false,
                'error'   => 'not found'
            );
            return Response::json($result);
        }
        
        $mediaItem->title = htmlspecialchars($data['title'], ENT_QUOTES, 'UTF-8');
        $mediaItem->alt = htmlspecialchars($data['alt'], ENT_QUOTES, 'UTF-8');
        $mediaItem->author = htmlspecialchars($data['author'], ENT_QUOTES, 'UTF-8');

        $mediaItem->save();
        
        $result = array (
            'success' => true,
            'mediaItem'  => $result
        );
        return Response::json($mediaItem);
    }
    
    public function getMore() {
        $validator = Validator::make(
            Input::all(),
            array(
                'lastId' => 'integer',
                'typeFilter' => 'array',
                'relatedFilter' => 'alpha_dash',
                'searchString' => '' 
            )
        );
        if ($validator->fails()) {
            return Response::json(array('rows' => array()));
        }
        
        $lastId = Input::get("lastId");
        $typeFilter = Input::get("typeFilter");
        $relatedFilter = Input::get("relatedFilter"); 
        $searchString = Input::get("searchString");

        $query = MediaItem::query();
        
        if (!empty($typeFilter)) {
            $realFilter = array_intersect($typeFilter, array("image", "video", "document"));
        } else {
            $realFilter = array("none");
        }
        $query->whereIn('media_type', $realFilter);
        
        if (!empty($relatedFilter)) {
            $query->where('related_type', $relatedFilter); 
        }  
        
        if ($searchString && strlen(trim($searchString)) > 2) {
            $query->where(function ($q) use ($searchString) {
                $q->where('original_filename', 'like', '%' . $searchString . '%')
                    ->orWhere('title', 'like', '%' . $searchString . '%')
                    ->orWhere('filename', 'like', '%' . $searchString . '%');
            });
        }
        
        if ($lastId && is_numeric($lastId)) {
            $query->where('id', '<', $lastId);
        }
        
        $rows = $query->orderBy('id', 'desc')->take(Input::get("rowCount"));
        
        $result = array( 
            "rowCount"          => Input::get("rowCount"),
            "rows"              => $rows->get()  
        );
        //var_dump(\DB::getQueryLog());
        return Response::json($result); 
    }
    
    public function postUpload($uploadType = 'media_manager') {
        $user = Auth::backend()->user();

        if (!$user->hasPermission('cms.manage')) {
            App::abort(403);
        }
        $file = Input::file('file');
        
        $relatedType = Input::get('relatedContentType');
        
        $destinationPath = Config::get('path.internal.media');

        $originalFilename = $file->getClientOriginalName();
        
        $extension = $file->getClientOriginalExtension();
        $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $originalFilename);
        
        $mediaType = $this->getMediaType($extension);
        if (!$mediaType) {
            return Response::json('error', 403); 
        }
        
        $newFilename = urlize($withoutExt);
        $finalName = $newFilename . '.' . $extension;
        //Checks for colliding filenames
        $i = 1;
        while (file_exists($destinationPath . '/' . $finalName)) {
            $finalName = $newFilename . '-' . $i . '.' . $extension;
            $i++;
            //for safety
            if ($i > 100) {
                return Response::json('error', 400);
            }
        }
        
        $upload_success = Input::file('file')->move($destinationPath, $finalName);
        
        if( $upload_success ) {
            $mediaItem = new MediaItem(array (
                'filename'          => $finalName,
                'original_filename' => $originalFilename,
                'title'             => $originalFilename,
                'extension'         => $extension,  
                'related_type'      => $relatedType,
                'media_type'        => $mediaType,
                'backend_user_id'   => $user->id
            ));
            
            if ($mediaType == MediaItem::MEDIA_TYPE_IMAGE) {
                //Generates internal thumbnail
                $img = Image::make($destinationPath . '/' . $finalName);
                $mediaItem->width = $img->width();
                $mediaItem->height = $img->height();
                $img->fit(200, 200);
                $img->save(Config::get('path.internal.thumbs') . '/' . getFileNameSize($finalName, '200x200'));
            } 
            
            $mediaItem->save();
            
            if ($uploadType == 'editor') {
                $editorImage = array(
                    'filelink' => url('/uploads/media/' . $mediaItem->filename)
                );
                return Response::json($editorImage, 200);   
            } else {
                return Response::json($mediaItem, 200);
            }
        } else {
            return Response::json('error', 400);
        }
    }
    
    public function postDelete()
    {                                        
        $itemId = Input::get('id');
        if (!is_numeric($itemId)) {
            return Response::json(false);
        }
        
        $user = Auth::backend()->user();

        if(!$user->hasPermission('cms.manage')){
            return Response::json(false);    
        }
        
        $item = MediaItem::find($itemId);
     
        if (!$item) {
            return Response::json(false);
        }
        
        // Deletes main file
        $filename = $item->filename;
        $mediaPath = Config::get('path.internal.media');
        if (file_exists($mediaPath . '/' . $filename)) {
            unlink($mediaPath . '/' . $filename);
        }
        
        // Deletes thumbs (for images)
        if ($item->media_type == MediaItem::MEDIA_TYPE_IMAGE) {
            $thumbsPath = Config::get('path.internal.thumbs');
            $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $filename);
            $ext = pathinfo($mediaPath . '/' . $filename, PATHINFO_EXTENSION); 
            
            foreach (glob($thumbsPath . "/" . $withoutExt . "_*." . $ext) as $thumb) {
                unlink($thumb);
            }
        }
        
        MediaItem::destroy($itemId);
        return Response::json(true);
    }
    
    public function getUpdateImageSizes() {
        $images = MediaItem::where('media_type', 'image')->get();
        $mediaPath = Config::get('path.internal.media');
        foreach ($images as $image) {
            try {
                $img = Image::make($mediaPath . '/' . $image->filename);
                echo $image->filename . ': ' . $img->width() . ' x ' . $img->height() . '<br>';
                $image->width = $img->width();
                $image->height = $img->height();
                //$image->title = $image->original_filename;
                $image->save();  
                $img->destroy();
            } catch (Exception $e) {
                echo 'ERROR WITH IMAGE: ' . $image->id . ' - ' . $image->filename . '<br>';
            }  
        } 
    }
    
    private function getMediaType ($ext) {
        $allowedExts = Config::get('backoffice/media.allowedExts');
        foreach ($allowedExts as $type => $allowedExt) {
            if (in_array($ext, $allowedExt)) {
                return $type;
            }
        }
        return false;
    }
}