<?php

namespace App\Http\Controllers;


use App\User;
use App\operations;
use App\operationsMembers;
use App\vehicle;
use App\operationsDrivers;
use App\operationsTrucks;
use App\Http\Controllers\documentCreators;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;

use Illuminate\Support\Facades\DB;

const basicTrainingID = 1;  //szkolenie podstawowe
const leaderTrainingID = 2; //szkolenie dowódcy
const driverTrainingID = 3; //szkolenie kierowcy-mechanika

class operationsController extends Controller
{
    //
    

    public function create(){
        if(auth()->user() != null && auth()->user()->fireStationID != null ){
            $operations  = DB::table('operations')->where('operations.fireStationID', "=", auth()->user()->fireStationID)
                ->whereNull('deleted_at')
                ->leftJoin('users', 'operations.commanderID', '=', 'users.id')
                ->select('operations.id', 'operations.operationDate', 'operations.location', 'operations.target', 'operations.dangerType', 'operations.description', 'operations.commanderID', 'operations.fireStationID', 'users.name', 'users.surname')
                ->paginate(10);
            $fireFighters = array();
            $trucks = array();
            foreach($operations as $operation){
                $id =$operation->id;
                $fireFighters[$id] = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )
                    ->leftJoin('operationsMembers', function ($join) use($id){
                        $join->on('users.id', '=', 'operationsMembers.memberID');
                        $join->where('operationsMembers.operationID', '=', $id);
                    })
                    ->select('users.*', 'operationsMembers.memberID', 'operationsMembers.privateTransport')
                    ->get();

                $trucks[$id] = DB::table('vehicles')->where([
                    ["vehicles.fireStationID", "=", auth()->user()->fireStationID ],
                    ])
                    ->leftJoin('operationsTrucks', function ($join) use($id){
                        $join->on('vehicles.id', '=', 'operationsTrucks.truckID');
                        $join->where('operationsTrucks.operationID', '=', $id);
                    })
                    ->leftJoin('users', 'operationsTrucks.driverID', '=', 'users.id')
                    ->select('vehicles.*', 'operationsTrucks.truckID', 'operationsTrucks.driverID', 'users.name as driverName', 'users.surname as driverSurname')
                    ->get();
            }



//            return view('operation', ["operations" => $operations], ["fireFighters" => $fireFighters], ["trucks" => $trucks]);
            return View::make('/operation')->with(compact('operations', 'fireFighters', 'trucks'));
        } else{
            return view('operation');
        }
    }

    public function addForm(){
        if(auth()->user() != null && auth()->user()->accessLevel() == 50 ){ //prezes,naczelnik
            $fireFighters = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )
            ->leftJoin('trainingsFirefighters', 'trainingsFirefighters.firefighterID', '=', 'users.id')
            ->where('trainingsFirefighters.trainingID', '=', basicTrainingID)
            ->select('users.*')
            ->get();
            $leaders = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )
            ->leftJoin('trainingsFirefighters', 'trainingsFirefighters.firefighterID', '=', 'users.id')
            ->where('trainingsFirefighters.trainingID', '=', leaderTrainingID)
            ->select('users.*')
            ->get();
            $drivers = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )
            ->leftJoin('trainingsFirefighters', 'trainingsFirefighters.firefighterID', '=', 'users.id')
            ->where('trainingsFirefighters.trainingID', '=', driverTrainingID)
            ->select('users.*')
            ->get();
            $vehicles = DB::table('vehicles')->where([
                ["fireStationID", '=', auth()->user()->fireStationID],
                ["vehicles.status", "=", 1],
                ["vehicles.deleted_at", "=", null],
            ])
                ->get();
            //return view("operationAdd", ["fireFighters" => $fireFighters], ["vehicles" => $vehicles]);
                return view("operationAdd")
                    ->with(compact('fireFighters'))
                    ->with(compact('leaders'))
                    ->with(compact('drivers'))
                    ->with(compact('vehicles'));

        } else return redirect()->to('/wyjazdy');
    }



    public function editForm($id){
        if(auth()->user() != null && auth()->user()->accessLevel() == 50 ){ //prezes,naczelnik

//            $fireFighters = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )->get();
            $vehicles = DB::table('vehicles')->where([
                ["fireStationID", '=', auth()->user()->fireStationID],
                //["vehicles.status", "=", 1],
            ])
                ->get();
            $operation = DB::table('operations')->where('operations.id', '=', $id)->first();
            $operationMembers = DB::table('operationsMembers')->where('operationID', '=', $id)->get();
//            $operation = DB::table('operations')->where('operations.id', '=', $id)
//                ->leftJoin('users', 'operations.commanderID', '=', 'users.id')
//                ->select('operations.id', 'operations.operationDate', 'operations.location', 'operations.target', 'operations.dangerType', 'operations.description', 'operations.commanderID', 'operations.fireStationID', 'users.id', 'users.name', 'users.surname')
//                ->get();
            $fireFighters = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )
                ->leftJoin('trainingsFirefighters', 'trainingsFirefighters.firefighterID', '=', 'users.id')
                ->where('trainingsFirefighters.trainingID', '=', basicTrainingID)
                ->leftJoin('operationsMembers', function ($join) use($id){
                    $join->on('users.id', '=', 'operationsMembers.memberID');
                    $join->where('operationsMembers.operationID', '=', $id);
                })
                ->select('users.*', 'operationsMembers.memberID', 'operationsMembers.privateTransport')
                ->get();
            $drivers = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )
                ->leftJoin('trainingsFirefighters', 'trainingsFirefighters.firefighterID', '=', 'users.id')
                ->where('trainingsFirefighters.trainingID', '=', driverTrainingID)
                ->leftJoin('operationsMembers', function ($join) use($id){
                    $join->on('users.id', '=', 'operationsMembers.memberID');
                    $join->where('operationsMembers.operationID', '=', $id);
                })
                ->select('users.*', 'operationsMembers.memberID', 'operationsMembers.privateTransport')
                ->get();
            $leaders = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )
                ->leftJoin('trainingsFirefighters', 'trainingsFirefighters.firefighterID', '=', 'users.id')
                ->where('trainingsFirefighters.trainingID', '=', leaderTrainingID)
                ->leftJoin('operationsMembers', function ($join) use($id){
                    $join->on('users.id', '=', 'operationsMembers.memberID');
                    $join->where('operationsMembers.operationID', '=', $id);
                })
                ->select('users.*', 'operationsMembers.memberID', 'operationsMembers.privateTransport')
                ->get();


//            $operationsTrucks = DB::table('vehicles')->where("vehicles.fireStationID", "=", auth()->user()->fireStationID )
//                ->leftJoin('operationsTrucks', function ($join) use($id){
//                    $join->on('vehicles.id', '=', 'operationsTrucks.truckID');
//                    $join->where('operationsTrucks.operationID', '=', $id);
//                })
//                ->leftJoin('users', 'operationsTrucks.driverID', '=', 'users.id')
//                ->select('vehicles.*', 'operationsTrucks.truckID', 'operationsTrucks.driverID', 'users.name as driverName', 'users.surname as driverSurname')
//                ->get();

            $operationsTrucks = DB::table('operationsTrucks')->where("operationsTrucks.operationID", "=", $id)
                ->join('users', 'operationsTrucks.driverID', '=', 'users.ID')
                ->join('vehicles', 'operationsTrucks.truckID', '=', 'vehicles.ID')
                ->select('vehicles.*', 'operationsTrucks.truckID', 'operationsTrucks.driverID', 'users.name as driverName', 'users.surname as driverSurname')
                ->get();

//            if($userFireStation == $fireFighterFireStation && auth()->user()->id == $fireStationCreatorId) {
//            return view('operationEdit', ["operation" => $operation], ["fireFighters" => $fireFighters], ["operationMembers" => $operationMembers] );
            return View::make('/operationEdit')->with(compact('fireFighters', 'drivers', 'leaders', 'operation', 'operationMembers', 'vehicles', 'operationsTrucks'));
//            } else{
//                return "Brak dostepu";
//            }
        } else{
            return redirect()->to('/wyjazdy');
        }
    }

    public function store(){
        $this->validate(request(),[
            'operationDate' => 'required',
            'operationLocation' => 'required|max:100',
            'operationTarget' => 'required|max:100',
            'operationDangerType' => 'required|max:100',
            'operationDescription' => 'required|max:250',
            'operationLeader' => 'required',
            'operationDriver.*' => 'required',
            'operationVehicle.*' => 'required',
            'attendance.*' => 'required',
            'transport.*' => 'required',
        ],
        [
            'required' => ':attribute jest wymagany(e)',
            'max' => ':attribute musi mieć nie więcej niż :max znaków.'
        ]);

        //
        $request = request();
        $operations = operations::create([
            'operationDate' => $request-> operationDate,
            'location' => $request-> operationLocation,
            'target' => $request-> operationTarget,
            'dangerType' => $request-> operationDangerType,
            'description' => $request-> operationDescription,
            'commanderID' => $request-> operationLeader,
            'fireStationID' => auth()->user()->fireStationID,
        ]);

        // Add trucks
        $operationDriver = $request ->operationDriver;
        $operationVehicle = $request -> operationVehicle;
        for($count = 0; $count < count($operationDriver); $count++){
            $operationsTrucks = operationsTrucks::create([
                'operationID' => $operations->id,
				'truckID' => $operationVehicle[$count],
                'driverID' => $operationDriver[$count]
				]);
        }


        // Add members
        $attendance = $request-> attendance;
        $transport = $request-> transport;

        // Count of firefighters (need for length of array)
        $fireFightersCount = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )
            ->leftJoin('trainingsFirefighters', 'trainingsFirefighters.firefighterID', '=', 'users.id')
            ->where('trainingsFirefighters.trainingID', '=', basicTrainingID)
            ->count();
        for($count = 0; $count < $fireFightersCount; $count++){

            // Check privateTransport checklist
            $privateTransport = 2;
            if(isset($transport[$count])){
                $privateTransport = 1;
            } else{
                $privateTransport = 0;
            }

            if(isset($attendance[$count])){
                $operationsMembers = operationsMembers::create([
                    'operationID' => $operations->id,
                    'memberID' => $attendance[$count],
                    'privateTransport' => $privateTransport,
                ]);
            };
        }

        return operationsController::create();
    }

    public function update(){
        $this->validate(request(),[
            'operationDate' => 'required',
            'operationLocation' => 'required|max:100',
            'operationTarget' => 'required|max:100',
            'operationDangerType' => 'required|max:100',
            'operationDescription' => 'required|max:250',
            'operationLeader' => 'required',
            'operationDriver.*' => 'required',
            'operationVehicle.*' => 'required',
            'attendance.*' => 'required',
            'transport.*' => 'required',
        ],
            [
                'required' => ':attribute jest wymagany(e)',
                'max' => ':attribute musi mieć nie więcej niż :max znaków.'
            ]);


        $request = request();
        $operation = operations::where('id', $request->operationID)->update(array(
            'operationDate' => $request-> operationDate,
            'location' => $request-> operationLocation,
            'target' => $request-> operationTarget,
            'dangerType' => $request-> operationDangerType,
            'description' => $request-> operationDescription,
            'commanderID' => $request-> operationLeader,
            'fireStationID' => auth()->user()->fireStationID
        ));


        operationsTrucks::where('operationID', $request->operationID)->delete();

        // Add trucks
        $operationDriver = $request ->operationDriver;
        $operationVehicle = $request -> operationVehicle;
        for($count = 0; $count < count($operationDriver); $count++){
            $operationsTrucks = operationsTrucks::create([
                'operationID' => $request->operationID,
                'truckID' => $operationVehicle[$count],
                'driverID' => $operationDriver[$count]
            ]);
        }

        operationsMembers::where('operationID', $request->operationID)->delete();


        // Add members
        $attendance = $request-> attendance;
        $transport = $request-> transport;

        // Count of firefighters (need for length of array)
        $fireFightersCount = DB::table('users')->where("fireStationID", "=", auth()->user()->fireStationID )->count();
        for($count = 0; $count < $fireFightersCount; $count++){

            // Check privateTransport checklist
            $privateTransport = 2;
            if(isset($transport[$count])){
                $privateTransport = 1;
            } else{
                $privateTransport = 0;
            }

            if(isset($attendance[$count])){
                $operationsMembers = operationsMembers::create([
                    'operationID' => $request->operationID,
                    'memberID' => $attendance[$count],
                    'privateTransport' => $privateTransport,
                ]);
            };
        }

        return redirect()->to('/wyjazdy');
    }

    public function destroy($id)
    {
        operations::find($id)->delete($id);

        return response()->json([
            'success' => 'Record deleted successfully!'
        ]);
    }

    public function createSingleOperationPDF(){
        if(auth()->user() != null && auth()->user()->fireStationID != null ) {
            $request = request();
            $test = new documentCreators();
            $test->createSingleOperationPDF2($request->operationID  );
        }
    }

    public function createAllOperationsPDF(){
        if (auth()->user() != null && auth()->user()->fireStationID != null) {
            $request = request();
            $test = new documentCreators();
            $test->createAllOperationsPDF($request->fireStationID);
        }
    }
}
