<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Company;

class CompanyController extends Controller
{
	public function showCompaniesForAdmin(){
		$companies = Company::latest()->paginate(10);
		$countries = \App\Country::get();
		return view('admin.company.index',compact(['companies','countries']));
	}

	public function showAddCompany(){
		$countries = \App\Country::latest()->get();
		return view('admin.company.add',compact('countries'));
	}

	public function addCompany(Request $request){
		$this->validate($request,[
			'name' => 'required',
			'country' => 'required|exists:countries,id',
			'image' => 'required|image'
		]);
		$path = '/images';
		$fileManager = new \App\Http\Controllers\FileManager;
		$fileName = $fileManager->moveFile($request,$path);
		$company = new Company;
		$company->country_id = $request->country;
		$company->name = $request->name;
		$company->image = $fileName;
		if($request->has('website')){
			$company->url = $request->website;
		}
		$company->save();
		flash('New company successfully added.')->success();
		return redirect()->back();
	}

	public function deleteCompany(Request $request){
		$company = Company::find($request->company_id);
		$companyName = $company->name;
		$company->delete();
		flash('The company '.$companyName.' has been successfully deleted.')->success();
		return redirect()->back();
	}

	public function editCompany(Request $request){
		$this->validate($request,[
			'name' => 'required',
			'country' => 'required|exists:countries,id',
		]);
		$company = Company::find($request->company_id);
		$path = '/images';
		$fileManager = new \App\Http\Controllers\FileManager;
		if($fileManager->fileUploaded($request)){
			$fileName = $fileManager->moveFile($request,$path);
			$company->image = $fileName;
		}
		$company->country_id = $request->country;
		$company->name = $request->name;
		if($request->has('website')){
			$company->url = $request->website;
		}
		$company->save();
		flash('Company successfully edited.')->success();
		return redirect()->back();
	}
}
