<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class GalleryController extends Controller
{
	public function showGallery(){
		$data = DB::table('gallery')->latest()->paginate(12);
		return view('gallery.index',compact('data'));
	}

	public function showGalleryForAdmin(){
		$gallery = DB::table('gallery')->latest()->paginate(10);
		return view('admin.gallery.index',compact('gallery'));
	}

	public function showAddToGallery(){
		return view('admin.gallery.add');
	}

	public function showAddVideoToGallery(){
		return view('admin.gallery.addvideo');
	}

	public function addToGallery(Request $request){
		$this->validate($request,[
			'title' => 'required',
			'image' => 'required|image'
		]);
		$path = '/julian_gallery/images';
		$fileManager = new \App\Http\Controllers\FileManager;
		$fileName = $fileManager->moveFile($request,$path);
		DB::table('gallery')->insert(
			['filename' => $fileName, 'title' => $request->title]
		);
		flash('Image successfully uploaded to gallery.')->success();
		return redirect()->back();
	}

	public function addVideoToGallery(Request $request){
		$this->validate($request,[
			'title' => 'required',
			'url' => 'required|url'
		]);
		$url = parse_url($request->url);
		$videoId = substr($url['query'],2);
		DB::table('gallery')->insert(
			['filename' => $videoId, 'title' => $request->title, 'data_type' => 'video']
		);
		flash('Video successfully added to gallery.')->success();
		return redirect()->back();
	}

	public function deleteFromGallery(Request $request){
		$gallery = DB::table('gallery')->where('id',$request->file_id);
		$fileName = $gallery->get()->first()->title;
		$gallery->delete();
		flash('The file '.$fileName.' has been successfully deleted.')->success();
		return redirect()->back();
	}
}
