<?php

namespace App\Http\Controllers;
use App\User;
use App\Media;
use App\About;
use App\Setting;
use App\Categories;
use View, DB, File, Auth, Mail;
use App\ImageHandler;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Input;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use Illuminate\Routing\Controller as BaseController;

class AdminController extends BackendController {

	public function index(){
		$media = DB::table('media')->count();
		return view('admin.adminpage', ['media'=>$media]);
	}
	public function media(){
		$media  	= DB::table('media')->orderBy('id', 'DESC')->paginate(10);
		$countmedia = DB::table('media')->count();
		return view('admin.media', ['media'=>$media, 'countmedia'=>$countmedia]);
	}
	public function showaddmedia(){
		$categories = Categories::lists('name', 'id');
		return view('admin.addmedia', ['categories'=>$categories]);
	}
	public function addnewmedia(Request $request){
		$validator 	= Validator::make(
            $request->only('title', 'upimage', 'category', 'description'),
            Media::$validators
        );
        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator);
        } else{
			$media 			= new Media;
			$media->title 	= $request->input('title');
			$args 			= array('image' => '', 'filename' => '');
			if($request->hasFile('upimage')){
				$args['image'] 	= $request->file('upimage');
				$args['type'] 	= 'upload';
				$args['folder'] = 'downloads/images';
				$media->name 	= ImageHandler::upload($args);
			}
			$filepath 		= config('view.downloadpath') .$media->name;
			$filepaththumb 	= config('view.downloadpath') . 'thumb/' .$media->name;
			$imgthumb 		= Image::make($filepath)->resize(600, null, function ($constraint) {
								$constraint->aspectRatio();
							})->save($filepaththumb);
			if ($request->hasFile('upfile')) {
				/*$args['image'] 	= $request->file('upfile');
				$args['type'] 	= 'upload';
				$args['folder'] = 'downloadfile/file';
				$media->file 	= ImageHandler::upload($args);*/
				$imageName = uniqid(). '-' .$request->file('upfile')->getClientOriginalName();
			    $request->file('upfile')->move(
			        getcwd() . '/content/files/downloadfile/', $imageName
			    );
			    $media->file = $imageName;
			    $media->typeFile = 'file';
			} else {
				if ($request->has('urldownload')) {
					$media->file = $request->input('urldownload');
					$media->typeFile = 'url';
				}
			}
			$media->slug 		= str_slug($request->input('title'));
			$media->description = html_entity_decode($request->input('description'));
			$media->tags 		= htmlspecialchars($request->input('tags'));
			$media->category_id = $request->input('category');
			$media->save();
			$request->session()->flash('flash_message', 'Successfully added new media.');
			$request->session()->flash('flash_type', 'alert-success');
			return redirect()->route('media');
			//return Redirect::to('/admin/media');
		}
	}
	public function showeditmedia($slug){
		$media  	= Media::where("slug", "=", $slug)->first();
		$categories = Categories::lists('name', 'id');
		$categorySelect = Categories::where('id', '=', $media->category_id)->first();
		return view('admin.editmedia', ['media'=>$media, 'categories'=>$categories, 'categorySelect'=>$categorySelect]);
	}
	public function editmedia(Request $request, $slug){
		$media = Media::where("slug", "=", $slug)->first();
        $rules = Media::$validators;
        $rules['upimage'] = 'image';

		$validator 	= Validator::make(
            $request->only('title', 'upimage', 'description'),
            $rules
        );
        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator);
        } else {
			$delpaththumb 	= config('$request->input') . 'thumb/' .$media->name;
			$delthumb 		= File::delete($delpaththumb);
        	$media->title 	= $request->input('title');
			$args 			= array('image' => '', 'filename' => '');
			if($request->hasFile('upimage')){
				$delpath 		= config('view.downloadpath') . $media->name;
				$delimage 		= File::delete($delpath);
				$args['image'] 	= $request->file('upimage');
				$args['type'] 	= 'upload';
				$args['folder'] = 'downloads/images';
				$media->name 	= ImageHandler::upload($args);
				
				$filepath 		= config('view.downloadpath') . $media->name;
				$filepaththumb 	= config('view.downloadpath') . 'thumb/' . $media->name;
				$imgthumb 		= Image::make($filepath)->resize(600, null, function ($constraint) {
					    			$constraint->aspectRatio();
								})->save($filepaththumb);
			}
			
			if ($request->hasFile('upfile')) {
				$imageName = uniqid(). '-' .$request->file('upfile')->getClientOriginalName();
			    $request->file('upfile')->move(
			        getcwd() . '/content/files/downloadfile/', $imageName
			    );
			    $media->file = $imageName;
				$media->typeFile = 'file';
			} else {
				if ($request->has('urldownload')) {
					$media->file 	= $request->input('urldownload');
					$media->typeFile = 'url';
				}
			}
			
			$media->slug 		= str_slug($request->input('title'));
			$media->description = html_entity_decode($request->input('description'));
			$media->tags 		= $request->input('tags');
			$media->category_id = $request->input('category');
			$media->save();
			$request->session()->flash('flash_message', 'Successfully Updated Media.');
			$request->session()->flash('flash_type', 'alert-success');
			return redirect()->route('media');
			//return Redirect::to('/admin/media');
		}
	}
	public function delete(Request $request, $id){
		$media 			= Media::find($id);
		$media->delete();
		$filepath 		= config('view.downloadpath') . $media->name;
		$filepaththumb 	= config('view.downloadpath') . 'thumb/' . $media->name;
		$delimage 		= File::delete($filepath);
		$delthumb 		= File::delete($filepaththumb);
		$request->session()->flash('flash_message', 'Successfully delete media.');
		$request->session()->flash('flash_type', 'alert-success');
		return redirect()->route('media');
		//return Redirect::to('/admin/media');
	}
	public function showsettings(){
		$settings 	= Setting::first();
		return view('admin.settings', $settings);
	}
	public function postsettings(Request $request){
		$settings 	= Setting::first();
		$args 		= array('image' => '', 'folder' => 'settings', 'filename' => '', 'type' => 'upload');
		$validator 	= Validator::make(
            $request->only('username', 'email', 'password'),
            Setting::$validators
        );
        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator);
        } else{
			$settings->sitename 	= $request->input('sitename');
			$settings->headline 	= $request->input('headline');
			$settings->subheadline  = $request->input('subheadline');
			if($request->hasFile('logo')){
				$args['image'] 	= $request->file('logo');
				$settings->logo = ImageHandler::upload($args);
			}
			if($request->hasFile('favicon')){
				$args['image']     = $request->file('favicon');
				$settings->favicon = ImageHandler::upload($args);
            }
            $settings->theme       = $request->input('theme');
			$settings->googleplus  = $request->input('googleplus');
			$settings->facebook    = $request->input('facebook');
			$settings->twitter     = $request->input('twitter');
			$settings->disqus 	   = $request->input('disqus');
			$settings->gganalytic  = $request->input('gganalytic');
			$settings->username	   = $request->input('username');
			$settings->email	   = $request->input('email');
			$settings->password	   = bcrypt($request->input('password'));
			$settings->ads728x90   = $request->input('ads728x90');
			$settings->ads300x250  = $request->input('ads300x250');
			$settings->save();
			$user = User::where('id', '=', Auth::user()->id)->first();
			$user->email 	= $settings->email;
			$password_request = $request->input('password');
			if(isset($password_request) && $password_request != ""):
				$user->password = $settings->password;
			endif;
			$user->save();
			$request->session()->flash('flash_message', 'Successfully updated site settings.');
			$request->session()->flash('flash_type', 'alert-success');
			return redirect()->route('settings');
			//return view('admin.settings');
		}
	}
	public function showcategories(){
		$categories  = Categories::orderBy('id', 'ASC')->get();
		$parentCate  = Categories::orderBy('id', 'ASC')->get();
		return view('admin.categoriespage', ['categories'=>$categories, 'parentCate'=>$parentCate]);
	}
	public function addcategory(Request $request){
		$validator = Validator::make(
            $request->only('name', 'url_slug', 'order'),
            Categories::$validators
        );
        if ($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator);
        } else{
        	$category 			= new Categories;
        	$category->name 	= $request->name;
        	$category->url_slug = $request->url_slug;
        	$category->order 	= $request->order;
        	$category->parentID = $request->parentID;
        	if ($request->parentID != 0) {
        		$category->level = 2;
        	}else {
        		$category->level = 1;
        	}
        	$category->save();
        	$categories  = Categories::orderBy('id', 'ASC')->get();
			$parentCate  = Categories::orderBy('id', 'ASC')->get();
			$request->session()->flash('flash_message', 'Successfully Add Category.');
			$request->session()->flash('flash_type', 'alert-success');
			return redirect()->route('getcategories', array('categories'=>$categories, 'parentCate'=>$parentCate));
			//return view('admin.categoriespage', ['categories'=>$categories, 'parentCate'=>$parentCate]);
        }
	}
	public function	showcategory($url_slug){
		$category   = Categories::where("url_slug", "=", $url_slug)->first();
		$parentCate = Categories::where("id", "!=", $category->id)->get();
       	$categories = Categories::where("url_slug", "!=", $url_slug)->orderBy('id', 'ASC')->get();
		$parent  	= Categories::orderBy('id', 'ASC')->get();
		return view('admin.editcategory', ['categories'=>$categories, 'category'=>$category, 'parentCate'=>$parentCate, 'parent'=>$parent]);
	}
	public function editcategory(Request $request, $url_slug){
		$category   	= Categories::where("url_slug", "=", $url_slug)->first();
        $rules			= Categories::$validators;
        $rules['name']	= 'required|min:3|unique:categories,name,' . $category->id;
		$validator 		= Validator::make(
            $request->only('name', 'url_slug', 'order'),
            $rules
        );
        if ($validator->fails())
        {
            return Redirect::back()->withInput()->withErrors($validator);
        } else{
        	$category->name 	= $request->name;
        	$category->url_slug = $request->url_slug;
        	$category->order 	= $request->order;
        	$category->parentID = $request->parentID;
        	if ($request->parentID != 0) {
        		$category->level = 2;
        	}else {
        		$category->level = 1;
        	}
        	$category->save();
			$parentCate  = Categories::orderBy('id', 'ASC')->get();
			$request->session()->flash('flash_message', 'Successfully updated site Category.');
			$request->session()->flash('flash_type', 'alert-success');
			return redirect()->route('getcategories', array('parentCate'=>$parentCate));
			//return view('admin.categoriespage', ['parentCate'=>$parentCate]);
        }
	}
	public function deletecategory(Request $request, $id){		
		$category = Categories::find($id);
		$category->delete();
		$request->session()->flash('flash_message', 'Successfully delete category.');
		$request->session()->flash('flash_type', 'alert-success');
		$parentCate = Categories::orderBy('id', 'ASC')->get();
		return redirect()->route('getcategories', array('parentCate'=>$parentCate));
	}

	public function showadminabout(){
		$about = DB::table('about')->where('id', '=', 1)->first();
		return view('about.adminabout', ['about'=>$about]);
	}
	public function updateabout(Request $request){
		$updateabout = About::where('id', '=', 1)->first();
		$updateabout->contentabout = $request->contentabout;
		$updateabout->save();
		$request->session()->flash('flash_message', 'Successfully updated site About.');
		$request->session()->flash('flash_type', 'alert-success');
		return redirect()->route('about');
	}
}
