%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /var/www/html/car_rent/app/Http/Controllers/
Upload File :
Create Path :
Current File : /var/www/html/car_rent/app/Http/Controllers/DriversController.php

<?php namespace App\Http\Controllers;

use App\Models\Reservation;
use App\Models\Driver;
use App\Models\Country;
use App\Models\Address;
use App\Models\User;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class DriversController extends Controller
{
	public function __construct()
	{
		$this->middleware('auth');
	}
	
    public function searchDrivers(Request $request)
    {
		$searchTerm = $request->get('term');
		if(trim($searchTerm) != "")
		{
			$searchTerm = '%'.$searchTerm.'%';
			
			$currentUser = \Auth::user();
			$AND_getAll_or_UserRelated = " ";		
			if($currentUser->id_role >= 5)
				$AND_getAll_or_UserRelated = " AND drivers.id_user = ".$currentUser->id;
			
			$query = "SELECT drivers.id
							, drivers.firstname
							, drivers.lastname
							, drivers.email
						FROM drivers
						WHERE drivers.deleted = 0 
						 $AND_getAll_or_UserRelated 
						  AND (drivers.firstname LIKE ?
							   OR drivers.lastname LIKE ?
							   OR drivers.email LIKE ?
							  )";
			
			$result = \DB::select($query, array($searchTerm, $searchTerm, $searchTerm));
		}
		else
			$result = [];
		
        return response()->json($result);
    }
	
	public function driversDetails($id)
    {
		$query = "SELECT  drivers.id
						, drivers.firstname
						, drivers.lastname
						, drivers.email
						, DATE_FORMAT(drivers.birthdate,'%d-%b-%Y') AS birthdate
						, drivers.license_number
						, DATE_FORMAT(drivers.license_expiration,'%d-%b-%Y') AS license_expiration
						, address.address
						, address.zip_code
						, address.city
						, countries.name AS address_country 
					FROM drivers 
					  LEFT JOIN address 
						ON (drivers.id = address.id_driver) 
					  LEFT JOIN countries 
						ON (countries.id = address.id_country) 
					WHERE drivers.id = :driversID
					LIMIT 1";
		$result = \DB::select($query, [':driversID'=>$id]);
				
        return response()->json($result[0]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($user_id=0)
    {		
		$currentUser = \Auth::user();
		if($user_id != 0 || $currentUser->id_role >= 5)
		{
			if($currentUser->id_role >= 5)
				$user_id = $currentUser->id;
				
			$userData = User::find($user_id);
			$drivers = Driver::join('address', 'drivers.id', '=', 'address.id_driver')
							->join('countries AS b_country', 'drivers.id_country_birth', '=', 'b_country.id')
							->join('countries AS a_country', 'address.id_country', '=', 'a_country.id')
							->select(\DB::raw("drivers.id
											, drivers.firstname
											, drivers.lastname
											, drivers.passport
											, drivers.idcard
											, DATE_FORMAT(drivers.birthdate,'%d-%b-%Y') AS birthdate
											, drivers.birthplace
											, b_country.name AS birth_country
											, drivers.license_number
											, DATE_FORMAT(drivers.license_expiration,'%d-%b-%y') AS license_expiration
											, drivers.email
											, address.address
											, address.zip_code
											, address.city
											, address.phone_1
											, address.phone_2
											, a_country.name AS address_country")
							)
							->where('address.type_home', 1)
							->where('drivers.id_user', $user_id)
							->where('drivers.deleted', 0)
							->paginate(25);
			return view('admin.drivers', ['resourceName'=>'drivers', 'records' => $drivers, 'user' => $userData]);
		}
		else 
		{	
			$drivers = Driver::join('address', 'drivers.id', '=', 'address.id_driver')
							->join('countries AS b_country', 'drivers.id_country_birth', '=', 'b_country.id')
							->join('countries AS a_country', 'address.id_country', '=', 'a_country.id')
							->select(\DB::raw("drivers.id
											, drivers.firstname
											, drivers.lastname
											, drivers.passport
											, drivers.idcard
											, DATE_FORMAT(drivers.birthdate,'%d-%b-%Y') AS birthdate
											, drivers.birthplace
											, b_country.name AS birth_country
											, drivers.license_number
											, DATE_FORMAT(drivers.license_expiration,'%d-%b-%y') AS license_expiration
											, drivers.email
											, address.address
											, address.zip_code
											, address.city
											, address.phone_1
											, address.phone_2
											, a_country.name AS address_country")
							)
							->where('address.type_home', 1)
							->where('drivers.deleted', 0)
							->paginate(25);
						
			return view('admin.drivers', ['resourceName'=>'drivers', 'records' => $drivers]);		
		}
    }
	
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function selectDriver($reservation_id=null)
    {	
		$data = ['reservation_id' => $reservation_id];
		
		return view('admin.driversSelect', $data);
    }

	public function selectDriverStore(Request $request)
	{	
        $input = $request->all();
		
		try {
			$fieldLabelNames = array(
		        'driver' => 'Driver',
			);
	        $requiredFields = array(
		        'driver' => 'required',
	        );
			
	        $validator = \Validator::make($input, $requiredFields);
	        $validator->setAttributeNames($fieldLabelNames);
			
	        if($validator->fails())
		        throw new \Exception('Validation Failed.');
			
			$driverAlreadyAdded = \DB::table('reservation_drivers')
									->where('id_reservation', $request->get('reservation_id'))
									->where('id_driver', $request->get('driver'))
									->exists();
									
			$redirectTo = "reservations/";	
			if(\Auth::user()->id_role >= 5)
				$redirectTo = "view-reservation/";
			
			if($driverAlreadyAdded)
			{
				$validator = \Validator::make([], 
					['Record_not_found'=>'required'], 
					['Record_not_found.required'=>"Driver already added, please add another driver."]
				);
				$validator->fails();
				return redirect($redirectTo.$request->get('reservation_id'))->withErrors($validator);
			}
			
			\DB::table('reservation_drivers')->insert([
				'id_reservation' => $request->get('reservation_id'), 
				'id_driver' => $request->get('driver'),
				'primary' => 0
			]);
			
			return redirect($redirectTo.$request->get('reservation_id'));
		}
		catch (\Exception $e)
		{
			info($e->getMessage(), [$e->getLine()]);
		}
		
		return back()->withErrors($validator)->withInput();
	}
		
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($reservation_id=null)
    {	
		$countries = Country::all();
		$data = ['countries' => $countries];
		if($reservation_id != null)
			$data['reservation_id'] = $reservation_id;
			
		return view('public.registerDriver', $data);
    }

	public function storeNewDriver(Request $request)
	{	
        $input = $request->all();
		
		\DB::beginTransaction();
		try {
			$fieldLabelNames = array(
		        'firstname' => 'Firstname',
		        'lastname' => 'Lastname',
				
		        'address' => 'Address',
		        //'zip_code' => 'Zip Code',
				'city' => 'City',
				'id_country' => 'Country',
				'phone_1' => 'Phone 1',
				
				'birth_day' => 'Birth Day',
				'birth_month' => 'Birth Month',
				'birth_year' => 'Birth Year',				
		        'birthplace' => 'Birth Place',
		        'id_country_birth' => 'Country of Birth',
				
		        'license_number' => 'Drivers License',
				'license_exp_day' => 'License Expiration Day',
				'license_exp_month' => 'License Expiration Month',
				'license_exp_year' => 'License Expiration Year',	
				'id_country_license' => 'Country',
				
		        'email' => 'Email',
			);
	        $requiredFields = array(
		        'firstname' => 'required',
		        'lastname' => 'required',
				
		        'address' => 'required',
		        //'zip_code' => 'required',
				'city' => 'required',
				'id_country' => 'required',
				'phone_1' => 'required',
				
		        'birth_day' => 'required',
		        'birth_month' => 'required',
		        'birth_year' => 'required|integer|digits:4',
		        'birthplace' => 'required',
		        'id_country_birth' => 'required',
				
		        'license_number' => 'required',
		        'license_exp_day' => 'required',
		        'license_exp_month' => 'required',
		        'license_exp_year' => 'required|integer|digits:4',
		        'id_country_license' => 'required',
				
		        'email' => 'required|email',
	        );
			
	        $validator = \Validator::make($input, $requiredFields);
	        $validator->setAttributeNames($fieldLabelNames);
			
	        if($validator->fails())
		        throw new \Exception('Validation Failed.');
			
			$currentUser = \Auth::user();
			//save driver
			$driver = new Driver();
			$driver->id_user = $currentUser->id;
			$driver->email = $request->get('email');
			$driver->firstname = $request->get('firstname');
			$driver->lastname = $request->get('lastname');
			$bday = $request->get('birth_year').'-'.$request->get('birth_month').'-'.$request->get('birth_day');
			$driver->birthdate = $bday;
			$driver->birthplace = $request->get('birthplace');
			$driver->id_country_birth = $request->get('id_country_birth');
			$driver->license_number = $request->get('license_number');
			$exp_date = $request->get('license_exp_year').'-'.$request->get('license_exp_month').'-'.$request->get('license_exp_day');
			$driver->license_expiration = $exp_date;
			$driver->id_country_license = $request->get('id_country_license');
			$driver->passport = $request->get('passport');
			$driver->idcard = $request->get('idcard');
			$driver->created_at = date('Y-m-d H:i:s');
			$driver->active = 1;
			$driver->save();
			
			$redirectTo = 'drivers';
			if($request->exists('reservation_id'))
			{	
				$reservation_id = $request->get('reservation_id');
				if($reservation_id == -101)
				{
					$redirectTo = 'reservations/complete/new-driver/'.$driver->id;
				}
				else 
				{
					$redirectTo = 'reservations/'.$reservation_id;
					if(\Auth::user()->id_role >= 5)
						$redirectTo = 'view-reservation/'.$reservation_id;
						
					\DB::table('reservation_drivers')->insert([
						'id_reservation' => $reservation_id, 
						'id_driver' => $driver->id,
						'primary' => 0
					]);
				}
			}
			
			//save address
			$address = new Address();
			$address->id_driver = $driver->id;
			$address->type_home = 1;
			$address->firstname = $request->get('firstname');
			$address->lastname = $request->get('lastname');
			$address->address = $request->get('address');
			$address->zip_code = $request->get('zip_code');
			$address->city = $request->get('city');
			$address->id_country = $request->get('id_country');
			$address->phone_1 = $request->get('phone_1');
			$address->phone_2 = $request->get('phone_2');
			$address->created_at = date('Y-m-d H:i:s');
			$address->deleted = 0;
			$address->save();
			
			\DB::commit();
			
			return redirect($redirectTo);
		}
		catch (\Exception $e)
		{
			\DB::rollback();
			info($e->getMessage(), [$e->getLine()]);
			if($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException)
			{
				$validator = \Validator::make($input, ['Record_not_found'=>'required'], ['Record_not_found.required'=>'The record you are trying to edit does not exits!']);
				$validator->fails();
			}
		}
		
		return back()->withErrors($validator)->withInput();
	}
		
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {		
        $input = $request->all();
		try {
			$fieldLabelNames = array(
		        'firstname' => 'Firstname',
		        'lastname' => 'Lastname',
				
				'birth_day' => 'Birth Day',
				'birth_month' => 'Birth Month',
				'birth_year' => 'Birth Year',				
		        'birthplace' => 'Birth Place',
		        'id_country_birth' => 'Country of Birth',
				
		        'license_number' => 'Drivers License',
				'license_exp_day' => 'License Expiration Day',
				'license_exp_month' => 'License Expiration Month',
				'license_exp_year' => 'License Expiration Year',	
				'id_country_license' => 'License Country',
				
		        'passport' => 'Passport Number',
		        'idcard' => 'ID Card Number',
		        'email' => 'Email',
			);
	        $requiredFields = array(
		        'firstname' => 'required',
		        'lastname' => 'required',
				
		        'birth_day' => 'required',
		        'birth_month' => 'required',
		        'birth_year' => 'required|integer|digits:4',
		        'birthplace' => 'required',
		        'id_country_birth' => 'required',
				
		        'license_number' => 'required',
		        'license_exp_day' => 'required',
		        'license_exp_month' => 'required',
		        'license_exp_year' => 'required|integer|digits:4',
		        'id_country_license' => 'required',
				
				'passport' => 'required_without:idcard',
				'idcard' => 'required_without:passport',
	
		        'email' => 'required|email',
	        );
			
	        $validator = \Validator::make($input, $requiredFields);
	        $validator->setAttributeNames($fieldLabelNames);
			
	        if($validator->fails())
		        throw new \Exception('Validation Failed.');
			
			if($request->exists('id'))
			{
				$driver = Driver::findOrFail($request->get('id'));
			}
			else
			{
				$driver = new Driver();
				$driver->created_at = date('Y-m-d H:i:s');
			}
			
			$currentUser = \Auth::user();
			if($currentUser->id_role >= 5 && $driver->id_user != $currentUser->id)
			{
				return view('public.permissionDenied');
			}
			
			$driver->email = $request->get('email');
			$driver->firstname = $request->get('firstname');
			$driver->lastname = $request->get('lastname');
			$bday = $request->get('birth_year').'-'.$request->get('birth_month').'-'.$request->get('birth_day');
			$driver->birthdate = $bday;
			$driver->birthplace = $request->get('birthplace');
			$driver->id_country_birth = $request->get('id_country_birth');
			$driver->license_number = $request->get('license_number');
			$exp_date = $request->get('license_exp_year').'-'.$request->get('license_exp_month').'-'.$request->get('license_exp_day');
			$driver->license_expiration = $exp_date;
			$driver->id_country_license = $request->get('id_country_license');
			$driver->passport = $request->get('passport');
			$driver->idcard = $request->get('idcard');
			$driver->save();
			
			return redirect('drivers');
		}
		catch (\Exception $e)
		{
			info($e->getMessage(), [$e->getLine()]);
			if($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException)
			{
				$validator = \Validator::make($input, ['Record_not_found'=>'required'], ['Record_not_found.required'=>'The record you are trying to edit does not exits!']);
				$validator->fails();
			}
		}
		
		return back()->withErrors($validator)->withInput()->with('model', $input);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
		$query = "SELECT  drivers.id
						, drivers.firstname
						, drivers.lastname
						, drivers.email
						, DATE_FORMAT(drivers.birthdate,'%d-%b-%Y') AS birthdate
						, drivers.license_number
						, DATE_FORMAT(drivers.license_expiration,'%d-%b-%Y') AS license_expiration
						, address.address
						, address.zip_code
						, address.city
						, countries.name AS address_country 
					FROM drivers 
					  LEFT JOIN address 
						ON (drivers.id = address.id_driver) 
					  LEFT JOIN countries 
						ON (countries.id = address.id_country) 
					WHERE drivers.id = :driversID
					LIMIT 1";
		$result = \DB::select($query, [':driversID'=>$id]);
		
        return response()->json($result[0]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
		$currentUser = \Auth::user();
		$modelData = Driver::find($id);	
		if($currentUser->id_role >= 5 && $modelData->id_user != $currentUser->id)
		{
			return view('public.permissionDenied');
		}
		
		$bday = explode('-', $modelData->birthdate);
		$modelData->birth_year  = $bday[0];
		$modelData->birth_month = $bday[1];
		$modelData->birth_day   = $bday[2];
		
		$exp_date = explode('-', $modelData->license_expiration);
		$modelData->license_exp_year  = $exp_date[0];
		$modelData->license_exp_month = $exp_date[1];
		$modelData->license_exp_day   = $exp_date[2];
		
		$countries = Country::all();
		
		$query = " SELECT address.id
						, address.type_home
						, CONCAT(address.firstname, ' ', address.lastname) AS name
						, address.address
						, address.zip_code
						, address.city
						, address.phone_1
						, address.phone_2
						, a_country.name AS address_country
					FROM
						address 
						INNER JOIN countries AS a_country
							ON (address.id_country = a_country.id)
					WHERE address.id_driver = :driverID
					  AND address.deleted = 0
					ORDER BY address.type_home DESC ";
		$addresses = \DB::select($query, [':driverID'=> $id]);
		
		return view('admin.driversForm', ['countries'=>$countries, 'addresses'=>$addresses])->with('model', $modelData);	
    }
	
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }
	
    /**
     * Set Primary Driver 
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function primary($id, $reservation_id)
    {
		\DB::beginTransaction();
		try {
		
			//REMOVE ANY OF THE RESERVATION'S PRIMARY DRIVERS 
			\DB::table('reservation_drivers')->where('id_reservation', $reservation_id)->update(['primary' => 0]);
			//SET THE NEW PRIMARY DRIVER
			\DB::table('reservation_drivers')->where('id_reservation', $reservation_id)->where('id_driver', $id)->update(['primary' => 1]);
			
			$driver = Driver::find($id);
			//UPDATE PRIMARY DRIVER'S NAME
			$reservation = Reservation::find($reservation_id);
			$reservation->primary_driver_name = $driver->firstname.' '.$driver->lastname;
			$reservation->save();
			
			\DB::commit();
		}
		catch (\Exception $e){
			\DB::rollback();			
		}
		
		return back();
    }
	
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function removeFrom($id, $reservation_id)
    {
		try {			
			\DB::table('reservation_drivers')->where('id_reservation', $reservation_id)->where('id_driver', $id)->where('primary', 0)->delete();
		}
		catch (\Exception $e){}//skip errors
		
		return response()->json('ok', 200);
    }
	
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
		try {
		
			$primaryDrivers = \DB::table('reservation_drivers')
									->where('id_driver', $id)
									->where('primary', 1)
									->get();
			
			if(count($primaryDrivers)>0)
			{	
				return response()->json(['message'=>"Driver can NOT be deleted because it is set as primary driver on at least one reservation. <br>You can remove it from a specific reservation by clicking the <b>Remove</b> button."], 200);
			}
			
			$model = Driver::find($id);
			$model->deleted = 1;
			$model->save();
		}
		catch (\Exception $e){}//skip errors
		
		return response()->json('ok', 200);
    }
}

Zerion Mini Shell 1.0