<?php

namespace App\Http\Controllers\Admin;

use App\Marker;
use App\ResidentialComplex;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreMarkersRequest;
use App\Http\Requests\Admin\UpdateMarkersRequest;

class MarkersController extends Controller
{
    /**
     * Display a listing of Marker.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (! Gate::allows('marker_access')) {
            return abort(401);
        }

        $search_id = $request->query->get('search_id');
        $residental_complex_id = $request->query->get('residental_complex_id');

        if (request('show_deleted') == 1) {
            if (! Gate::allows('marker_delete')) {
                return abort(401);
            }
            $markers = Marker::onlyTrashed()->get();
        } else {
            if (!empty($search_id) || !empty($residental_complex_id)) {
//                $markers = $this->search($search_id);
                $markers = Marker::query()
                    ->with('infrastructure_type')
                    ->leftJoin('residential_complex_markers as rcm', 'markers.id', '=', 'rcm.marker_id')
//                    ->leftJoin('residential_complexes as rc', 'rcm.residential_complex_id', '=',  'rc.id')
                    ->leftJoin('marker_types as mt', 'markers.infrastructure_type_id', '=', 'mt.id')
                    ->whereNull('markers.deleted_at')

                    ->when(!empty($residental_complex_id), function ($query) use ($residental_complex_id) {
                        $query->where('rcm.residential_complex_id', $residental_complex_id);
                    })

                    ->when(!empty($search_id), function ($query) use ($search_id) {
                        $query->where('mt.id', $search_id);
                    })

                    ->select('markers.*')
                    ->groupBy('markers.id')
                    ->get();
            } else {
                $markers = Marker::paginate(Marker::PAGINATE);
            }
        }
        $residential_complexes = ResidentialComplex::get()->
            pluck('name', 'id')->prepend(trans('quickadmin.qa_residential_complex_filter'), '');

        $markersFilter  = Marker::join(Marker::MARKER_TYPES. ' as mt', Marker::MARKERS.'.infrastructure_type_id', '=', 'mt.id')
            ->get()->pluck('type', 'id')->prepend(trans('quickadmin.qa_please_select'). '(тип інфраструктури)', '');

        return view('admin.markers.index', compact('markers','markersFilter', 'search_id', 'residential_complexes', 'residental_complex_id'));
    }

    /**
     * @param $search_id
     * @return mixed
     */
    private function search($search_id){

        $marker_types = Marker::whereInfrastructureTypeId($search_id)->get();

        return $marker_types;
    }

    /**
     * Show the form for creating new Marker.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if (! Gate::allows('marker_create')) {
            return abort(401);
        }
        
        $infrastructure_types = \App\MarkerType::get()
            ->pluck('type', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
        $residential_complexes = ResidentialComplex::get()->pluck('name', 'id');

        return view('admin.markers.create', compact('infrastructure_types','residential_complexes'));
    }

    /**
     * Store a newly created Marker in storage.
     *
     * @param  \App\Http\Requests\StoreMarkersRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreMarkersRequest $request)
    {
        if (! Gate::allows('marker_create')) {
            return abort(401);
        }
        $marker = Marker::create($request->all());
        $marker->residential_complexes()->sync(array_filter((array)$request->input('residential_complex')));
        $marker->save();

        return redirect()->route('admin.markers.index');
    }

    /**
     * Show the form for editing Marker.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if (! Gate::allows('marker_edit')) {
            return abort(401);
        }
        
        $infrastructure_types = \App\MarkerType::get()->pluck('type', 'id')->prepend(trans('quickadmin.qa_please_select'), '');

        $marker = Marker::findOrFail($id);

        $residential_complexes = ResidentialComplex::get()->pluck('name', 'id');

        return view('admin.markers.edit', compact('marker', 'infrastructure_types','residential_complexes'));
    }

    /**
     * Update Marker in storage.
     *
     * @param  \App\Http\Requests\UpdateMarkersRequest  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateMarkersRequest $request, $id)
    {
        if (! Gate::allows('marker_edit')) {
            return abort(401);
        }
        $marker = Marker::findOrFail($id);
        $marker->residential_complexes()->sync(array_filter((array)$request->input('residential_complex')));
        $marker->update($request->all());


        return redirect()->route('admin.markers.index');
    }


    /**
     * Display Marker.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        if (! Gate::allows('marker_view')) {
            return abort(401);
        }
        $marker = Marker::findOrFail($id);

        return view('admin.markers.show', compact('marker'));
    }


    /**
     * Remove Marker from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (! Gate::allows('marker_delete')) {
            return abort(401);
        }
        $marker = Marker::findOrFail($id);
        $marker->forceDelete();

        return redirect()->route('admin.markers.index');
    }

    /**
     * Delete all selected Marker at once.
     *
     * @param Request $request
     */
    public function massDestroy(Request $request)
    {
        if (! Gate::allows('marker_delete')) {
            return abort(401);
        }
        if ($request->input('ids')) {
            $entries = Marker::whereIn('id', $request->input('ids'))->get();

            foreach ($entries as $entry) {
                $entry->forceDelete();
            }
        }
    }

    /**
     * Restore Marker from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function restore($id)
    {
        if (! Gate::allows('marker_delete')) {
            return abort(401);
        }
        $marker = Marker::onlyTrashed()->findOrFail($id);
        $marker->restore();

        return redirect()->route('admin.markers.index');
    }

    /**
     * Permanently delete Marker from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function perma_del($id)
    {
        if (! Gate::allows('marker_delete')) {
            return abort(401);
        }

        $marker = Marker::onlyTrashed()->findOrFail($id);
        $marker->forceDelete();

        return redirect()->route('admin.markers.index');
    }
}
