<?php

namespace App\Http\Controllers;

use App\Location;
use App\WashingMachine;
use App\WashingReservation;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use function GuzzleHttp\Promise\all;

class LocationController extends Controller
{
    public function __construct()
    {
        $this->middleware([ "auth" ]);
        $this->middleware([ "lang" ]);

        $this->middleware([ "check.auth:locations.list" ])->only("index");
        $this->middleware([ "check.auth:locations.show" ])->only("show");
        $this->middleware([ "check.auth:locations.create" ])->only("create", "store");
        $this->middleware([ "check.auth:locations.edit" ])->only("edit", "update");
        $this->middleware([ "check.auth:locations.delete" ])->only("delete");
    }

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $locations = Location::query()->paginate($request->input("limit", 20));

        return Response::detect("locations.index", [ "locations" => $locations ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return Response::detect("locations.create");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            "name" => "required",
        ]);

        $location = new Location($data);

        $locations = Location::query()->where('name', '=', $request->name)->get();

        // If there already is a washing machine with that name, then don't add it
        if (count($locations) > 0)
            return redirect()->route("locations.index");
        else { // Else - Add it
            $location->save();
            $locations = Location::query()->paginate($request->input("limit", 20));
            return redirect()->route("locations.index", ['locations' => $locations]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Location  $location
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(Location $location)
    {
        return view("admin.locations.show", [ "location" => $location]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Location  $location
     * @return \Illuminate\Http\Response
     */
    public function edit(Location $location)
    {
        return Response::detect("locations.edit", [ "location" => $location] );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Location  $location
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $request->validate([
            "name" => "required",
        ]);

        $location = Location::find($id);


        $allMachines = Location::query()->where('name', '=', $request->name)->where('id', '!=', $id)->get();

        // If there already is a washing machine with that name, then don't change it
        if (count($allMachines) > 0)
            return redirect()->route("locations.index");
        else { // Else - Change the name
            $location->update($data);
            $location->save();

            $locations = Location::query()->paginate($request->input("limit", 20));
            return redirect()->route("locations.index", ["locations" => $locations]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $location = Location::find($id);
        $washingMachines = WashingMachine::query()->where('location_id', '=', $id)->get();

        foreach ($washingMachines as $machine) {
            $washingReservations = WashingReservation::query()->where('machine_id', '=', $machine->id)->get();

            foreach ($washingReservations as $reservation)
            {
                $reservation->delete();
            }

            $machine->delete();
        }

        $location->delete();

        return redirect()->route("locations.index");
    }

    public function nameCheck(Request $request){
        $locations = Location::query()->where('name', 'LIKE',$request->nameCheck)->get();
        if(count($locations) > 0 && $request->nameCheck !== NULL){
            return 1;
        }
    }

    public function nameCheckUpdate(Request $request){
        $locations = Location::query()->where('name', 'LIKE',$request->nameCheck)->where('id', '!=', $request->id)->get();
        if(count($locations) > 0 && $request->nameCheck !== NULL){
            return 1;
        }
    }




    public function search(Request $request){
        if($request->ajax()){
            $output = "<tr>".
                "<th>Navn</th>".
                "<th>Lokation</th>".
                "<th style=\"width: 1em;\"><img class=\"w-100\" src=\"http://127.0.0.1:8000/images/icons/pencil.svg\" alt=\"Update\"></th>".
                "<th style=\"width: 1em;\"><img class=\"w-100\" src=\"http://127.0.0.1:8000/images/icons/trashcan.svg\" alt=\"Delete\"></th>".
                "</tr>";

            if($request->option !== 'all') {
                $locations = DB::table('washing_machines')
                    ->join('locations', 'washing_machines.location_id','=', 'locations.id')
                    ->select(DB::raw('washing_machines.name as washing_name, locations.name as location_name, locations.id as id'))
                    ->where('locations.id', '=', $request->option)
                    ->get();

                if(count($locations) !== 0){
                    foreach ($locations as $key => $location){
                        $output.='<tr>'.
                            '<td>' . $location->washing_name . '</td>'.
                            '<td>' . $location->location_name . '</td>'.
                            '<td><form method="post" action="' .route("locations.destroy", [ "location" => $location->id ]). '" class="w-100 nostyle">'.
                            '<td><form method="post" action="' .route("locations.edit", [ "location" => $location->id ]). '" class="w-100 nostyle">'.
                            csrf_field().
                            method_field("delete").

                            '<button class="w-100 nostyle" onclick="return confirm(\'Are you sure you want to delete?\');" type="submit"><img class="w-100 cursor-pointer" src="'. asset('/images/icons/trashcan-dark.svg') . '" alt="Delete"></button>'.
                            '</form>'.
                            '</td>'.
                            '</tr>';
                    }
                }else{
                    $output.='<tr>'.
                        '<td>Det er ikke blivet oprettet nogen vaskmaskine på denne lokation i nu</td>'.
                        '<td></td>'.
                        '<td></td>'.
                        '<td></td>'.
                        '</tr>';
                }
            }
            elseif($request->option === "all"){
                $machines = WashingMachine::all();

                if(count($machines) !== 0){
                    foreach($machines as $machine) {
                        $output.= '<tr>'.
                            '<td>'.$machine->name.'</td>'.
                            '<td>'.Location::query()->where("id", "=", $machine->location_id)->first()->name.'</td>'.
                            '<td><a href="'. route("washing-machines.edit", [ "washing_machine" => $machine->id]) . '"><img class="w-100" src="'. asset('/images/icons/pencil-dark.svg') . '" alt="Update"></a></td>'.
                            '<td><form method="post" action="'. route('washing-machines.destroy', [ 'washing_machine' => $machine->id ]) .'" class="w-100 nostyle">'.
                                    csrf_field().
                                    method_field("delete").
                                  '<button class="w-100 nostyle" onclick="return confirm('."'Are you sure you want to delete?'".');" type="submit"><img class="w-100 cursor-pointer" src="'. asset('/images/icons/trashcan-dark.svg'). '" alt="Delete"></button>'.
                                '</form>'.
                            '</td>'.
                        '</tr>';
                    }
                }else{
                    $output.='<tr>'.
                        '<td>Det er ikke blivet oprettet nogen vaskmaskine på denne lokation i nu</td>'.
                        '<td></td>'.
                        '<td></td>'.
                        '<td></td>'.
                        '</tr>';
                }
            }




            return Response($output);
        }
    }

}