<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\JobCategory;

class JobCategoryController extends Controller
{
	public function slugGenerator($slug){
		$lettersNumbersSpacesHypens = '/[^\-\s\pN\pL]+/u';
		$spacesDuplicateHypens = '/[\-\s]+/';
		$slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug, 'UTF-8'));
		$slug = preg_replace($spacesDuplicateHypens, '-', $slug);
		$slug = trim($slug, '-');
		$slug = $slug.'-'.time();
		return $slug;
	}

	public function showJobCategoriesForAdmin(){
		$categories = JobCategory::latest()->paginate(10);
		return view('admin.category.index',compact('categories'));
	}

	public function showAddJobCategory(){
		return view('admin.category.add');
	}

	public function addJobCategory(Request $request){
		$this->validate($request,[
			'name' => 'required',
			'description' => 'required',
			'job_titles' => 'required',
			'image' => 'required|image'
		]);
		$path = '/images';
		$fileManager = new \App\Http\Controllers\FileManager;
		$fileName = $fileManager->moveFile($request,$path);
		$category = new JobCategory;
		$category->name = $request->name;
		$category->description = $request->description;
		$category->job_titles = $request->job_titles;
		$category->image = $fileName;
		$category->slug = $this->slugGenerator($request->name);
		$category->save();
		flash('New job category successfully added.')->success();
		return redirect('/admin/category');
	}

	public function deleteCategory(Request $request){
		$category = JobCategory::find($request->category_id);
		$categoryName = $category->name;
		$category->delete();
		flash('The category '.$categoryName.' has been successfully deleted.')->success();
		return redirect()->back();
	}

	public function editCategory(Request $request){
		$this->validate($request,[
			'name' => 'required',
			'description' => 'required',
			'job_titles' => 'required'
		]);
		$category = JobCategory::find($request->category_id);
		$path = '/images';
		$fileManager = new \App\Http\Controllers\FileManager;
		if($fileManager->fileUploaded($request)){
			$fileName = $fileManager->moveFile($request,$path);
			$category->image = $fileName;
		}
		$category->name = $request->name;
		$category->description = $request->description;
		$category->job_titles = $request->job_titles;
		$category->slug = $this->slugGenerator($request->name);
		$category->save();
		flash('Category successfully edited.')->success();
		return redirect()->back();
	}

	public function showJobCategory($slug){
		$category = JobCategory::where('slug',$slug);
		if($category->count()<1){
			return redirect('/');
		}
		$category = $category->get()->first();
		$categories = JobCategory::where('id','!=',$category->id)->latest()->limit(5)->get();

		return view('category.show',compact(['category','categories']));
	}

	public function showJobCategories(){
		$categories = \App\JobCategory::latest()->get();
		return view('category.index',compact('categories'));
	}
}
